1 /*
2 * AVI demuxer
3 * Copyright (c) 2001 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "config_components.h"
23
24 #include <inttypes.h>
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/mathematics.h"
33 #include "avformat.h"
34 #include "avi.h"
35 #include "demux.h"
36 #include "dv.h"
37 #include "internal.h"
38 #include "isom.h"
39 #include "riff.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/exif.h"
42 #include "libavcodec/startcode.h"
43
44 typedef struct AVIStream {
45 int64_t frame_offset; /* current frame (video) or byte (audio) counter
46 * (used to compute the pts) */
47 int remaining;
48 int packet_size;
49
50 uint32_t handler;
51 uint32_t scale;
52 uint32_t rate;
53 int sample_size; /* size of one sample (or packet)
54 * (in the rate/scale sense) in bytes */
55
56 int64_t cum_len; /* temporary storage (used during seek) */
57 int prefix; /* normally 'd'<<8 + 'c' or 'w'<<8 + 'b' */
58 int prefix_count;
59 uint32_t pal[256];
60 int has_pal;
61 int dshow_block_align; /* block align variable used to emulate bugs in
62 * the MS dshow demuxer */
63
64 AVFormatContext *sub_ctx;
65 AVPacket *sub_pkt;
66 AVBufferRef *sub_buffer;
67
68 int64_t seek_pos;
69 } AVIStream;
70
71 typedef struct AVIContext {
72 const AVClass *class;
73 int64_t riff_end;
74 int64_t movi_end;
75 int64_t fsize;
76 int64_t io_fsize;
77 int64_t movi_list;
78 int64_t last_pkt_pos;
79 int index_loaded;
80 int is_odml;
81 int non_interleaved;
82 int stream_index;
83 DVDemuxContext *dv_demux;
84 int odml_depth;
85 int64_t odml_read;
86 int64_t odml_max_pos;
87 int use_odml;
88 #define MAX_ODML_DEPTH 1000
89 int64_t dts_max;
90 } AVIContext;
91
92
93 static const AVOption options[] = {
94 { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
95 { NULL },
96 };
97
98 static const AVClass demuxer_class = {
99 .class_name = "avi",
100 .item_name = av_default_item_name,
101 .option = options,
102 .version = LIBAVUTIL_VERSION_INT,
103 .category = AV_CLASS_CATEGORY_DEMUXER,
104 };
105
106
107 static const char avi_headers[][8] = {
108 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
109 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
110 { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19 },
111 { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
112 { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
113 { 0 }
114 };
115
116 static const AVMetadataConv avi_metadata_conv[] = {
117 { "strn", "title" },
118 { "isbj", "subject" },
119 { "inam", "title" },
120 { "iart", "artist" },
121 { "icop", "copyright" },
122 { "icmt", "comment" },
123 { "ignr", "genre" },
124 { "iprd", "product" },
125 { "isft", "software" },
126
127 { 0 },
128 };
129
130 static int avi_load_index(AVFormatContext *s);
131 static int guess_ni_flag(AVFormatContext *s);
132
133 #define print_tag(s, str, tag, size) \
134 av_log(s, AV_LOG_TRACE, "pos:%"PRIX64" %s: tag=%s size=0x%x\n", \
135 avio_tell(pb), str, av_fourcc2str(tag), size) \
136
get_duration(AVIStream *ast, int len)137 static inline int get_duration(AVIStream *ast, int len)
138 {
139 if (ast->sample_size)
140 return len;
141 else if (ast->dshow_block_align)
142 return (len + (int64_t)ast->dshow_block_align - 1) / ast->dshow_block_align;
143 else
144 return 1;
145 }
146
get_riff(AVFormatContext *s, AVIOContext *pb)147 static int get_riff(AVFormatContext *s, AVIOContext *pb)
148 {
149 AVIContext *avi = s->priv_data;
150 char header[8] = {0};
151 int i;
152
153 /* check RIFF header */
154 avio_read(pb, header, 4);
155 avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
156 avi->riff_end += avio_tell(pb); /* RIFF chunk end */
157 avio_read(pb, header + 4, 4);
158
159 for (i = 0; avi_headers[i][0]; i++)
160 if (!memcmp(header, avi_headers[i], 8))
161 break;
162 if (!avi_headers[i][0])
163 return AVERROR_INVALIDDATA;
164
165 if (header[7] == 0x19)
166 av_log(s, AV_LOG_INFO,
167 "This file has been generated by a totally broken muxer.\n");
168
169 return 0;
170 }
171
read_odml_index(AVFormatContext *s, int64_t frame_num)172 static int read_odml_index(AVFormatContext *s, int64_t frame_num)
173 {
174 AVIContext *avi = s->priv_data;
175 AVIOContext *pb = s->pb;
176 int longs_per_entry = avio_rl16(pb);
177 int index_sub_type = avio_r8(pb);
178 int index_type = avio_r8(pb);
179 int entries_in_use = avio_rl32(pb);
180 int chunk_id = avio_rl32(pb);
181 int64_t base = avio_rl64(pb);
182 int stream_id = ((chunk_id & 0xFF) - '0') * 10 +
183 ((chunk_id >> 8 & 0xFF) - '0');
184 AVStream *st;
185 AVIStream *ast;
186 int i;
187 int64_t last_pos = -1;
188 int64_t filesize = avi->fsize;
189
190 av_log(s, AV_LOG_TRACE,
191 "longs_per_entry:%d index_type:%d entries_in_use:%d "
192 "chunk_id:%X base:%16"PRIX64" frame_num:%"PRId64"\n",
193 longs_per_entry,
194 index_type,
195 entries_in_use,
196 chunk_id,
197 base,
198 frame_num);
199
200 if (stream_id >= s->nb_streams || stream_id < 0)
201 return AVERROR_INVALIDDATA;
202 st = s->streams[stream_id];
203 ast = st->priv_data;
204
205 if (index_sub_type || entries_in_use < 0)
206 return AVERROR_INVALIDDATA;
207
208 avio_rl32(pb);
209
210 if (index_type && longs_per_entry != 2)
211 return AVERROR_INVALIDDATA;
212 if (index_type > 1)
213 return AVERROR_INVALIDDATA;
214
215 if (filesize > 0 && base >= filesize) {
216 av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
217 if (base >> 32 == (base & 0xFFFFFFFF) &&
218 (base & 0xFFFFFFFF) < filesize &&
219 filesize <= 0xFFFFFFFF)
220 base &= 0xFFFFFFFF;
221 else
222 return AVERROR_INVALIDDATA;
223 }
224
225 for (i = 0; i < entries_in_use; i++) {
226 avi->odml_max_pos = FFMAX(avi->odml_max_pos, avio_tell(pb));
227
228 // If we read more than there are bytes then we must have been reading something twice
229 if (avi->odml_read > avi->odml_max_pos)
230 return AVERROR_INVALIDDATA;
231
232 if (index_type) {
233 int64_t pos = avio_rl32(pb) + base - 8;
234 int len = avio_rl32(pb);
235 int key = len >= 0;
236 len &= 0x7FFFFFFF;
237 avi->odml_read += 8;
238
239 av_log(s, AV_LOG_TRACE, "pos:%"PRId64", len:%X\n", pos, len);
240
241 if (avio_feof(pb))
242 return AVERROR_INVALIDDATA;
243
244 if (last_pos == pos || pos == base - 8)
245 avi->non_interleaved = 1;
246 if (last_pos != pos && len)
247 av_add_index_entry(st, pos, ast->cum_len, len, 0,
248 key ? AVINDEX_KEYFRAME : 0);
249
250 ast->cum_len += get_duration(ast, len);
251 last_pos = pos;
252 } else {
253 int64_t offset, pos;
254 int duration;
255 int ret;
256 avi->odml_read += 16;
257
258 offset = avio_rl64(pb);
259 avio_rl32(pb); /* size */
260 duration = avio_rl32(pb);
261
262 if (avio_feof(pb) || offset > INT64_MAX - 8)
263 return AVERROR_INVALIDDATA;
264
265 pos = avio_tell(pb);
266
267 if (avi->odml_depth > MAX_ODML_DEPTH) {
268 av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
269 return AVERROR_INVALIDDATA;
270 }
271
272 if (avio_seek(pb, offset + 8, SEEK_SET) < 0)
273 return -1;
274 avi->odml_depth++;
275 ret = read_odml_index(s, frame_num);
276 avi->odml_depth--;
277 frame_num += duration;
278
279 if (avio_seek(pb, pos, SEEK_SET) < 0) {
280 av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index\n");
281 return -1;
282 }
283 if (ret < 0)
284 return ret;
285 }
286 }
287 avi->index_loaded = 2;
288 return 0;
289 }
290
clean_index(AVFormatContext *s)291 static void clean_index(AVFormatContext *s)
292 {
293 int i;
294 int64_t j;
295
296 for (i = 0; i < s->nb_streams; i++) {
297 AVStream *st = s->streams[i];
298 FFStream *const sti = ffstream(st);
299 AVIStream *ast = st->priv_data;
300 int n = sti->nb_index_entries;
301 int max = ast->sample_size;
302 int64_t pos, size, ts;
303
304 if (n != 1 || ast->sample_size == 0)
305 continue;
306
307 while (max < 1024)
308 max += max;
309
310 pos = sti->index_entries[0].pos;
311 size = sti->index_entries[0].size;
312 ts = sti->index_entries[0].timestamp;
313
314 for (j = 0; j < size; j += max)
315 av_add_index_entry(st, pos + j, ts + j, FFMIN(max, size - j), 0,
316 AVINDEX_KEYFRAME);
317 }
318 }
319
avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)320 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag,
321 uint32_t size)
322 {
323 AVIOContext *pb = s->pb;
324 char key[5] = { 0 };
325 char *value;
326
327 size += (size & 1);
328
329 if (size == UINT_MAX)
330 return AVERROR(EINVAL);
331 value = av_malloc(size + 1);
332 if (!value)
333 return AVERROR(ENOMEM);
334 if (avio_read(pb, value, size) != size) {
335 av_freep(&value);
336 return AVERROR_INVALIDDATA;
337 }
338 value[size] = 0;
339
340 AV_WL32(key, tag);
341
342 return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
343 AV_DICT_DONT_STRDUP_VAL);
344 }
345
346 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
347 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
348
avi_metadata_creation_time(AVDictionary **metadata, char *date)349 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
350 {
351 char month[4], time[9], buffer[64];
352 int i, day, year;
353 /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
354 if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
355 month, &day, time, &year) == 4) {
356 for (i = 0; i < 12; i++)
357 if (!av_strcasecmp(month, months[i])) {
358 snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
359 year, i + 1, day, time);
360 av_dict_set(metadata, "creation_time", buffer, 0);
361 }
362 } else if (date[4] == '/' && date[7] == '/') {
363 date[4] = date[7] = '-';
364 av_dict_set(metadata, "creation_time", date, 0);
365 }
366 }
367
avi_read_nikon(AVFormatContext *s, uint64_t end)368 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
369 {
370 while (avio_tell(s->pb) < end && !avio_feof(s->pb)) {
371 uint32_t tag = avio_rl32(s->pb);
372 uint32_t size = avio_rl32(s->pb);
373 switch (tag) {
374 case MKTAG('n', 'c', 't', 'g'): /* Nikon Tags */
375 {
376 uint64_t tag_end = avio_tell(s->pb) + size;
377 while (avio_tell(s->pb) < tag_end && !avio_feof(s->pb)) {
378 uint16_t tag = avio_rl16(s->pb);
379 uint16_t size = avio_rl16(s->pb);
380 const char *name = NULL;
381 char buffer[64] = { 0 };
382 uint64_t remaining = tag_end - avio_tell(s->pb);
383 size = FFMIN(size, remaining);
384 size -= avio_read(s->pb, buffer,
385 FFMIN(size, sizeof(buffer) - 1));
386 switch (tag) {
387 case 0x03:
388 name = "maker";
389 break;
390 case 0x04:
391 name = "model";
392 break;
393 case 0x13:
394 name = "creation_time";
395 if (buffer[4] == ':' && buffer[7] == ':')
396 buffer[4] = buffer[7] = '-';
397 break;
398 }
399 if (name)
400 av_dict_set(&s->metadata, name, buffer, 0);
401 avio_skip(s->pb, size);
402 }
403 break;
404 }
405 default:
406 avio_skip(s->pb, size);
407 break;
408 }
409 }
410 }
411
avi_extract_stream_metadata(AVFormatContext *s, AVStream *st)412 static int avi_extract_stream_metadata(AVFormatContext *s, AVStream *st)
413 {
414 GetByteContext gb;
415 uint8_t *data = st->codecpar->extradata;
416 int data_size = st->codecpar->extradata_size;
417 int tag, offset;
418
419 if (!data || data_size < 8) {
420 return AVERROR_INVALIDDATA;
421 }
422
423 bytestream2_init(&gb, data, data_size);
424
425 tag = bytestream2_get_le32(&gb);
426
427 switch (tag) {
428 case MKTAG('A', 'V', 'I', 'F'):
429 // skip 4 byte padding
430 bytestream2_skip(&gb, 4);
431 offset = bytestream2_tell(&gb);
432
433 // decode EXIF tags from IFD, AVI is always little-endian
434 return avpriv_exif_decode_ifd(s, data + offset, data_size - offset,
435 1, 0, &st->metadata);
436 break;
437 case MKTAG('C', 'A', 'S', 'I'):
438 avpriv_request_sample(s, "RIFF stream data tag type CASI (%u)", tag);
439 break;
440 case MKTAG('Z', 'o', 'r', 'a'):
441 avpriv_request_sample(s, "RIFF stream data tag type Zora (%u)", tag);
442 break;
443 default:
444 break;
445 }
446
447 return 0;
448 }
449
calculate_bitrate(AVFormatContext *s)450 static int calculate_bitrate(AVFormatContext *s)
451 {
452 AVIContext *avi = s->priv_data;
453 int i, j;
454 int64_t lensum = 0;
455 int64_t maxpos = 0;
456
457 for (i = 0; i<s->nb_streams; i++) {
458 int64_t len = 0;
459 FFStream *const sti = ffstream(s->streams[i]);
460
461 if (!sti->nb_index_entries)
462 continue;
463
464 for (j = 0; j < sti->nb_index_entries; j++)
465 len += sti->index_entries[j].size;
466 maxpos = FFMAX(maxpos, sti->index_entries[j-1].pos);
467 lensum += len;
468 }
469 if (maxpos < av_rescale(avi->io_fsize, 9, 10)) // index does not cover the whole file
470 return 0;
471 if (lensum*9/10 > maxpos || lensum < maxpos*9/10) // frame sum and filesize mismatch
472 return 0;
473
474 for (i = 0; i<s->nb_streams; i++) {
475 int64_t len = 0;
476 AVStream *st = s->streams[i];
477 FFStream *const sti = ffstream(st);
478 int64_t duration;
479 int64_t bitrate;
480
481 for (j = 0; j < sti->nb_index_entries; j++)
482 len += sti->index_entries[j].size;
483
484 if (sti->nb_index_entries < 2 || st->codecpar->bit_rate > 0)
485 continue;
486 duration = sti->index_entries[j-1].timestamp - sti->index_entries[0].timestamp;
487 bitrate = av_rescale(8*len, st->time_base.den, duration * st->time_base.num);
488 if (bitrate > 0) {
489 st->codecpar->bit_rate = bitrate;
490 }
491 }
492 return 1;
493 }
494
avi_read_header(AVFormatContext *s)495 static int avi_read_header(AVFormatContext *s)
496 {
497 AVIContext *avi = s->priv_data;
498 AVIOContext *pb = s->pb;
499 unsigned int tag, tag1, handler;
500 int codec_type, stream_index, frame_period;
501 unsigned int size;
502 int i;
503 AVStream *st;
504 AVIStream *ast = NULL;
505 int avih_width = 0, avih_height = 0;
506 int amv_file_format = 0;
507 uint64_t list_end = 0;
508 int64_t pos;
509 int ret;
510 AVDictionaryEntry *dict_entry;
511
512 avi->stream_index = -1;
513
514 ret = get_riff(s, pb);
515 if (ret < 0)
516 return ret;
517
518 av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
519
520 avi->io_fsize = avi->fsize = avio_size(pb);
521 if (avi->fsize <= 0 || avi->fsize < avi->riff_end)
522 avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
523
524 /* first list tag */
525 stream_index = -1;
526 codec_type = -1;
527 frame_period = 0;
528 for (;;) {
529 if (avio_feof(pb))
530 return AVERROR_INVALIDDATA;
531 tag = avio_rl32(pb);
532 size = avio_rl32(pb);
533
534 print_tag(s, "tag", tag, size);
535
536 switch (tag) {
537 case MKTAG('L', 'I', 'S', 'T'):
538 list_end = avio_tell(pb) + size;
539 /* Ignored, except at start of video packets. */
540 tag1 = avio_rl32(pb);
541
542 print_tag(s, "list", tag1, 0);
543
544 if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
545 avi->movi_list = avio_tell(pb) - 4;
546 if (size)
547 avi->movi_end = avi->movi_list + size + (size & 1);
548 else
549 avi->movi_end = avi->fsize;
550 av_log(s, AV_LOG_TRACE, "movi end=%"PRIx64"\n", avi->movi_end);
551 goto end_of_header;
552 } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
553 ff_read_riff_info(s, size - 4);
554 else if (tag1 == MKTAG('n', 'c', 'd', 't'))
555 avi_read_nikon(s, list_end);
556
557 break;
558 case MKTAG('I', 'D', 'I', 'T'):
559 {
560 unsigned char date[64] = { 0 };
561 size += (size & 1);
562 size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));
563 avio_skip(pb, size);
564 avi_metadata_creation_time(&s->metadata, date);
565 break;
566 }
567 case MKTAG('d', 'm', 'l', 'h'):
568 avi->is_odml = 1;
569 avio_skip(pb, size + (size & 1));
570 break;
571 case MKTAG('a', 'm', 'v', 'h'):
572 amv_file_format = 1;
573 case MKTAG('a', 'v', 'i', 'h'):
574 /* AVI header */
575 /* using frame_period is bad idea */
576 frame_period = avio_rl32(pb);
577 avio_rl32(pb); /* max. bytes per second */
578 avio_rl32(pb);
579 avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
580
581 avio_skip(pb, 2 * 4);
582 avio_rl32(pb);
583 avio_rl32(pb);
584 avih_width = avio_rl32(pb);
585 avih_height = avio_rl32(pb);
586
587 avio_skip(pb, size - 10 * 4);
588 break;
589 case MKTAG('s', 't', 'r', 'h'):
590 /* stream header */
591
592 tag1 = avio_rl32(pb);
593 handler = avio_rl32(pb); /* codec tag */
594
595 if (tag1 == MKTAG('p', 'a', 'd', 's')) {
596 avio_skip(pb, size - 8);
597 break;
598 } else {
599 stream_index++;
600 st = avformat_new_stream(s, NULL);
601 if (!st)
602 return AVERROR(ENOMEM);
603
604 st->id = stream_index;
605 ast = av_mallocz(sizeof(AVIStream));
606 if (!ast)
607 return AVERROR(ENOMEM);
608 st->priv_data = ast;
609 }
610 if (amv_file_format)
611 tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')
612 : MKTAG('v', 'i', 'd', 's');
613
614 print_tag(s, "strh", tag1, -1);
615
616 if (tag1 == MKTAG('i', 'a', 'v', 's') ||
617 tag1 == MKTAG('i', 'v', 'a', 's')) {
618 int64_t dv_dur;
619
620 /* After some consideration -- I don't think we
621 * have to support anything but DV in type1 AVIs. */
622 if (s->nb_streams != 1)
623 return AVERROR_INVALIDDATA;
624
625 if (handler != MKTAG('d', 'v', 's', 'd') &&
626 handler != MKTAG('d', 'v', 'h', 'd') &&
627 handler != MKTAG('d', 'v', 's', 'l'))
628 return AVERROR_INVALIDDATA;
629
630 if (!CONFIG_DV_DEMUXER)
631 return AVERROR_DEMUXER_NOT_FOUND;
632
633 ast = s->streams[0]->priv_data;
634 st->priv_data = NULL;
635 ff_remove_stream(s, st);
636
637 avi->dv_demux = avpriv_dv_init_demux(s);
638 if (!avi->dv_demux) {
639 av_free(ast);
640 return AVERROR(ENOMEM);
641 }
642
643 s->streams[0]->priv_data = ast;
644 avio_skip(pb, 3 * 4);
645 ast->scale = avio_rl32(pb);
646 ast->rate = avio_rl32(pb);
647 avio_skip(pb, 4); /* start time */
648
649 dv_dur = avio_rl32(pb);
650 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
651 dv_dur *= AV_TIME_BASE;
652 s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
653 }
654 /* else, leave duration alone; timing estimation in utils.c
655 * will make a guess based on bitrate. */
656
657 stream_index = s->nb_streams - 1;
658 avio_skip(pb, size - 9 * 4);
659 break;
660 }
661
662 av_assert0(stream_index < s->nb_streams);
663 ast->handler = handler;
664
665 avio_rl32(pb); /* flags */
666 avio_rl16(pb); /* priority */
667 avio_rl16(pb); /* language */
668 avio_rl32(pb); /* initial frame */
669 ast->scale = avio_rl32(pb);
670 ast->rate = avio_rl32(pb);
671 if (!(ast->scale && ast->rate)) {
672 av_log(s, AV_LOG_WARNING,
673 "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "
674 "(This file has been generated by broken software.)\n",
675 ast->scale,
676 ast->rate);
677 if (frame_period) {
678 ast->rate = 1000000;
679 ast->scale = frame_period;
680 } else {
681 ast->rate = 25;
682 ast->scale = 1;
683 }
684 }
685 avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
686
687 ast->cum_len = avio_rl32(pb); /* start */
688 st->nb_frames = avio_rl32(pb);
689
690 st->start_time = 0;
691 avio_rl32(pb); /* buffer size */
692 avio_rl32(pb); /* quality */
693 if (ast->cum_len > 3600LL * ast->rate / ast->scale) {
694 av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
695 ast->cum_len = 0;
696 }
697 ast->sample_size = avio_rl32(pb);
698 ast->cum_len *= FFMAX(1, ast->sample_size);
699 av_log(s, AV_LOG_TRACE, "%"PRIu32" %"PRIu32" %d\n",
700 ast->rate, ast->scale, ast->sample_size);
701
702 switch (tag1) {
703 case MKTAG('v', 'i', 'd', 's'):
704 codec_type = AVMEDIA_TYPE_VIDEO;
705
706 ast->sample_size = 0;
707 st->avg_frame_rate = av_inv_q(st->time_base);
708 break;
709 case MKTAG('a', 'u', 'd', 's'):
710 codec_type = AVMEDIA_TYPE_AUDIO;
711 break;
712 case MKTAG('t', 'x', 't', 's'):
713 codec_type = AVMEDIA_TYPE_SUBTITLE;
714 break;
715 case MKTAG('d', 'a', 't', 's'):
716 codec_type = AVMEDIA_TYPE_DATA;
717 break;
718 default:
719 av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
720 }
721
722 if (ast->sample_size < 0) {
723 if (s->error_recognition & AV_EF_EXPLODE) {
724 av_log(s, AV_LOG_ERROR,
725 "Invalid sample_size %d at stream %d\n",
726 ast->sample_size,
727 stream_index);
728 return AVERROR_INVALIDDATA;
729 }
730 av_log(s, AV_LOG_WARNING,
731 "Invalid sample_size %d at stream %d "
732 "setting it to 0\n",
733 ast->sample_size,
734 stream_index);
735 ast->sample_size = 0;
736 }
737
738 if (ast->sample_size == 0) {
739 st->duration = st->nb_frames;
740 if (st->duration > 0 && avi->io_fsize > 0 && avi->riff_end > avi->io_fsize) {
741 av_log(s, AV_LOG_DEBUG, "File is truncated adjusting duration\n");
742 st->duration = av_rescale(st->duration, avi->io_fsize, avi->riff_end);
743 }
744 }
745 ast->frame_offset = ast->cum_len;
746 avio_skip(pb, size - 12 * 4);
747 break;
748 case MKTAG('s', 't', 'r', 'f'):
749 /* stream header */
750 if (!size && (codec_type == AVMEDIA_TYPE_AUDIO ||
751 codec_type == AVMEDIA_TYPE_VIDEO))
752 break;
753 if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
754 avio_skip(pb, size);
755 } else {
756 uint64_t cur_pos = avio_tell(pb);
757 FFStream *sti;
758 unsigned esize;
759 if (cur_pos < list_end)
760 size = FFMIN(size, list_end - cur_pos);
761 st = s->streams[stream_index];
762 sti = ffstream(st);
763 if (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN) {
764 avio_skip(pb, size);
765 break;
766 }
767 switch (codec_type) {
768 case AVMEDIA_TYPE_VIDEO:
769 if (amv_file_format) {
770 st->codecpar->width = avih_width;
771 st->codecpar->height = avih_height;
772 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
773 st->codecpar->codec_id = AV_CODEC_ID_AMV;
774 avio_skip(pb, size);
775 break;
776 }
777 tag1 = ff_get_bmp_header(pb, st, &esize);
778
779 if (tag1 == MKTAG('D', 'X', 'S', 'B') ||
780 tag1 == MKTAG('D', 'X', 'S', 'A')) {
781 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
782 st->codecpar->codec_tag = tag1;
783 st->codecpar->codec_id = AV_CODEC_ID_XSUB;
784 break;
785 }
786
787 if (size > 10 * 4 && size < (1 << 30) && size < avi->fsize) {
788 if (esize == size-1 && (esize&1)) {
789 st->codecpar->extradata_size = esize - 10 * 4;
790 } else
791 st->codecpar->extradata_size = size - 10 * 4;
792 if (st->codecpar->extradata) {
793 av_log(s, AV_LOG_WARNING, "New extradata in strf chunk, freeing previous one.\n");
794 }
795 ret = ff_get_extradata(s, st->codecpar, pb,
796 st->codecpar->extradata_size);
797 if (ret < 0)
798 return ret;
799 }
800
801 // FIXME: check if the encoder really did this correctly
802 if (st->codecpar->extradata_size & 1)
803 avio_r8(pb);
804
805 /* Extract palette from extradata if bpp <= 8.
806 * This code assumes that extradata contains only palette.
807 * This is true for all paletted codecs implemented in
808 * FFmpeg. */
809 if (st->codecpar->extradata_size &&
810 (st->codecpar->bits_per_coded_sample <= 8)) {
811 int pal_size = (1 << st->codecpar->bits_per_coded_sample) << 2;
812 const uint8_t *pal_src;
813
814 pal_size = FFMIN(pal_size, st->codecpar->extradata_size);
815 pal_src = st->codecpar->extradata +
816 st->codecpar->extradata_size - pal_size;
817 /* Exclude the "BottomUp" field from the palette */
818 if (pal_src - st->codecpar->extradata >= 9 &&
819 !memcmp(st->codecpar->extradata + st->codecpar->extradata_size - 9, "BottomUp", 9))
820 pal_src -= 9;
821 for (i = 0; i < pal_size / 4; i++)
822 ast->pal[i] = 0xFFU<<24 | AV_RL32(pal_src + 4 * i);
823 ast->has_pal = 1;
824 }
825
826 print_tag(s, "video", tag1, 0);
827
828 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
829 st->codecpar->codec_tag = tag1;
830 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags,
831 tag1);
832 /* If codec is not found yet, try with the mov tags. */
833 if (!st->codecpar->codec_id) {
834 st->codecpar->codec_id =
835 ff_codec_get_id(ff_codec_movvideo_tags, tag1);
836 if (st->codecpar->codec_id)
837 av_log(s, AV_LOG_WARNING,
838 "mov tag found in avi (fourcc %s)\n",
839 av_fourcc2str(tag1));
840 }
841 if (!st->codecpar->codec_id)
842 st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags_unofficial, tag1);
843
844 /* This is needed to get the pict type which is necessary
845 * for generating correct pts. */
846 sti->need_parsing = AVSTREAM_PARSE_HEADERS;
847
848 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 &&
849 ast->handler == MKTAG('X', 'V', 'I', 'D'))
850 st->codecpar->codec_tag = MKTAG('X', 'V', 'I', 'D');
851
852 if (st->codecpar->codec_tag == MKTAG('V', 'S', 'S', 'H'))
853 sti->need_parsing = AVSTREAM_PARSE_FULL;
854 if (st->codecpar->codec_id == AV_CODEC_ID_RV40)
855 sti->need_parsing = AVSTREAM_PARSE_NONE;
856 if (st->codecpar->codec_id == AV_CODEC_ID_HEVC &&
857 st->codecpar->codec_tag == MKTAG('H', '2', '6', '5'))
858 sti->need_parsing = AVSTREAM_PARSE_FULL;
859
860 if (st->codecpar->codec_id == AV_CODEC_ID_AVRN &&
861 st->codecpar->codec_tag == MKTAG('A', 'V', 'R', 'n') &&
862 (st->codecpar->extradata_size < 31 ||
863 memcmp(&st->codecpar->extradata[28], "1:1", 3)))
864 st->codecpar->codec_id = AV_CODEC_ID_MJPEG;
865
866 if (st->codecpar->codec_tag == 0 && st->codecpar->height > 0 &&
867 st->codecpar->extradata_size < 1U << 30) {
868 st->codecpar->extradata_size += 9;
869 if ((ret = av_reallocp(&st->codecpar->extradata,
870 st->codecpar->extradata_size +
871 AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {
872 st->codecpar->extradata_size = 0;
873 return ret;
874 } else
875 memcpy(st->codecpar->extradata + st->codecpar->extradata_size - 9,
876 "BottomUp", 9);
877 }
878 if (st->codecpar->height == INT_MIN)
879 return AVERROR_INVALIDDATA;
880 st->codecpar->height = FFABS(st->codecpar->height);
881
882 // avio_skip(pb, size - 5 * 4);
883 break;
884 case AVMEDIA_TYPE_AUDIO:
885 ret = ff_get_wav_header(s, pb, st->codecpar, size, 0);
886 if (ret < 0)
887 return ret;
888 ast->dshow_block_align = st->codecpar->block_align;
889 if (ast->sample_size && st->codecpar->block_align &&
890 ast->sample_size != st->codecpar->block_align) {
891 av_log(s,
892 AV_LOG_WARNING,
893 "sample size (%d) != block align (%d)\n",
894 ast->sample_size,
895 st->codecpar->block_align);
896 ast->sample_size = st->codecpar->block_align;
897 }
898 /* 2-aligned
899 * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
900 if (size & 1)
901 avio_skip(pb, 1);
902 /* Force parsing as several audio frames can be in
903 * one packet and timestamps refer to packet start. */
904 sti->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
905 /* ADTS header is in extradata, AAC without header must be
906 * stored as exact frames. Parser not needed and it will
907 * fail. */
908 if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
909 st->codecpar->extradata_size)
910 sti->need_parsing = AVSTREAM_PARSE_NONE;
911 // The flac parser does not work with AVSTREAM_PARSE_TIMESTAMPS
912 if (st->codecpar->codec_id == AV_CODEC_ID_FLAC)
913 sti->need_parsing = AVSTREAM_PARSE_NONE;
914 /* AVI files with Xan DPCM audio (wrongly) declare PCM
915 * audio in the header but have Axan as stream_code_tag. */
916 if (ast->handler == AV_RL32("Axan")) {
917 st->codecpar->codec_id = AV_CODEC_ID_XAN_DPCM;
918 st->codecpar->codec_tag = 0;
919 ast->dshow_block_align = 0;
920 }
921 if (amv_file_format) {
922 st->codecpar->codec_id = AV_CODEC_ID_ADPCM_IMA_AMV;
923 ast->dshow_block_align = 0;
924 }
925 if ((st->codecpar->codec_id == AV_CODEC_ID_AAC ||
926 st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
927 st->codecpar->codec_id == AV_CODEC_ID_MP2 ) && ast->dshow_block_align <= 4 && ast->dshow_block_align) {
928 av_log(s, AV_LOG_DEBUG, "overriding invalid dshow_block_align of %d\n", ast->dshow_block_align);
929 ast->dshow_block_align = 0;
930 }
931 if (st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 1024 && ast->sample_size == 1024 ||
932 st->codecpar->codec_id == AV_CODEC_ID_AAC && ast->dshow_block_align == 4096 && ast->sample_size == 4096 ||
933 st->codecpar->codec_id == AV_CODEC_ID_MP3 && ast->dshow_block_align == 1152 && ast->sample_size == 1152) {
934 av_log(s, AV_LOG_DEBUG, "overriding sample_size\n");
935 ast->sample_size = 0;
936 }
937 break;
938 case AVMEDIA_TYPE_SUBTITLE:
939 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
940 sti->request_probe = 1;
941 avio_skip(pb, size);
942 break;
943 default:
944 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
945 st->codecpar->codec_id = AV_CODEC_ID_NONE;
946 st->codecpar->codec_tag = 0;
947 avio_skip(pb, size);
948 break;
949 }
950 }
951 break;
952 case MKTAG('s', 't', 'r', 'd'):
953 if (stream_index >= (unsigned)s->nb_streams
954 || s->streams[stream_index]->codecpar->extradata_size
955 || s->streams[stream_index]->codecpar->codec_tag == MKTAG('H','2','6','4')) {
956 avio_skip(pb, size);
957 } else {
958 uint64_t cur_pos = avio_tell(pb);
959 if (cur_pos < list_end)
960 size = FFMIN(size, list_end - cur_pos);
961 st = s->streams[stream_index];
962
963 if (size<(1<<30)) {
964 if (st->codecpar->extradata) {
965 av_log(s, AV_LOG_WARNING, "New extradata in strd chunk, freeing previous one.\n");
966 }
967 if ((ret = ff_get_extradata(s, st->codecpar, pb, size)) < 0)
968 return ret;
969 }
970
971 if (st->codecpar->extradata_size & 1) //FIXME check if the encoder really did this correctly
972 avio_r8(pb);
973
974 ret = avi_extract_stream_metadata(s, st);
975 if (ret < 0) {
976 av_log(s, AV_LOG_WARNING, "could not decoding EXIF data in stream header.\n");
977 }
978 }
979 break;
980 case MKTAG('i', 'n', 'd', 'x'):
981 pos = avio_tell(pb);
982 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) &&
983 avi->use_odml &&
984 read_odml_index(s, 0) < 0 &&
985 (s->error_recognition & AV_EF_EXPLODE))
986 return AVERROR_INVALIDDATA;
987 avio_seek(pb, pos + size, SEEK_SET);
988 break;
989 case MKTAG('v', 'p', 'r', 'p'):
990 if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {
991 AVRational active, active_aspect;
992
993 st = s->streams[stream_index];
994 avio_rl32(pb);
995 avio_rl32(pb);
996 avio_rl32(pb);
997 avio_rl32(pb);
998 avio_rl32(pb);
999
1000 active_aspect.den = avio_rl16(pb);
1001 active_aspect.num = avio_rl16(pb);
1002 active.num = avio_rl32(pb);
1003 active.den = avio_rl32(pb);
1004 avio_rl32(pb); // nbFieldsPerFrame
1005
1006 if (active_aspect.num && active_aspect.den &&
1007 active.num && active.den) {
1008 st->sample_aspect_ratio = av_div_q(active_aspect, active);
1009 av_log(s, AV_LOG_TRACE, "vprp %d/%d %d/%d\n",
1010 active_aspect.num, active_aspect.den,
1011 active.num, active.den);
1012 }
1013 size -= 9 * 4;
1014 }
1015 avio_skip(pb, size);
1016 break;
1017 case MKTAG('s', 't', 'r', 'n'):
1018 case MKTAG('i', 's', 'b', 'j'):
1019 case MKTAG('i', 'n', 'a', 'm'):
1020 case MKTAG('i', 'a', 'r', 't'):
1021 case MKTAG('i', 'c', 'o', 'p'):
1022 case MKTAG('i', 'c', 'm', 't'):
1023 case MKTAG('i', 'g', 'n', 'r'):
1024 case MKTAG('i', 'p', 'o', 'd'):
1025 case MKTAG('i', 's', 'o', 'f'):
1026 if (s->nb_streams) {
1027 ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);
1028 if (ret < 0)
1029 return ret;
1030 break;
1031 }
1032 default:
1033 if (size > 1000000) {
1034 av_log(s, AV_LOG_ERROR,
1035 "Something went wrong during header parsing, "
1036 "tag %s has size %u, "
1037 "I will ignore it and try to continue anyway.\n",
1038 av_fourcc2str(tag), size);
1039 if (s->error_recognition & AV_EF_EXPLODE)
1040 return AVERROR_INVALIDDATA;
1041 avi->movi_list = avio_tell(pb) - 4;
1042 avi->movi_end = avi->fsize;
1043 goto end_of_header;
1044 }
1045 /* Do not fail for very large idx1 tags */
1046 case MKTAG('i', 'd', 'x', '1'):
1047 /* skip tag */
1048 size += (size & 1);
1049 avio_skip(pb, size);
1050 break;
1051 }
1052 }
1053
1054 end_of_header:
1055 /* check stream number */
1056 if (stream_index != s->nb_streams - 1)
1057 return AVERROR_INVALIDDATA;
1058
1059 if (!avi->index_loaded && (pb->seekable & AVIO_SEEKABLE_NORMAL))
1060 avi_load_index(s);
1061 calculate_bitrate(s);
1062 avi->index_loaded |= 1;
1063
1064 if ((ret = guess_ni_flag(s)) < 0)
1065 return ret;
1066
1067 avi->non_interleaved |= ret | (s->flags & AVFMT_FLAG_SORT_DTS);
1068
1069 dict_entry = av_dict_get(s->metadata, "ISFT", NULL, 0);
1070 if (dict_entry && !strcmp(dict_entry->value, "PotEncoder"))
1071 for (i = 0; i < s->nb_streams; i++) {
1072 AVStream *st = s->streams[i];
1073 if ( st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO
1074 || st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO)
1075 ffstream(st)->need_parsing = AVSTREAM_PARSE_FULL;
1076 }
1077
1078 for (i = 0; i < s->nb_streams; i++) {
1079 AVStream *st = s->streams[i];
1080 if (ffstream(st)->nb_index_entries)
1081 break;
1082 }
1083 // DV-in-AVI cannot be non-interleaved, if set this must be
1084 // a mis-detection.
1085 if (avi->dv_demux)
1086 avi->non_interleaved = 0;
1087 if (i == s->nb_streams && avi->non_interleaved) {
1088 av_log(s, AV_LOG_WARNING,
1089 "Non-interleaved AVI without index, switching to interleaved\n");
1090 avi->non_interleaved = 0;
1091 }
1092
1093 if (avi->non_interleaved) {
1094 av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
1095 clean_index(s);
1096 }
1097
1098 ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
1099 ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
1100
1101 return 0;
1102 }
1103
read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)1104 static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
1105 {
1106 if (pkt->size >= 7 &&
1107 pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
1108 !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
1109 uint8_t desc[256];
1110 int score = AVPROBE_SCORE_EXTENSION, ret;
1111 AVIStream *ast = st->priv_data;
1112 const AVInputFormat *sub_demuxer;
1113 AVRational time_base;
1114 int size;
1115 AVProbeData pd;
1116 unsigned int desc_len;
1117 AVIOContext *pb = avio_alloc_context(pkt->data + 7,
1118 pkt->size - 7,
1119 0, NULL, NULL, NULL, NULL);
1120 if (!pb)
1121 goto error;
1122
1123 desc_len = avio_rl32(pb);
1124
1125 if (desc_len > pb->buf_end - pb->buf_ptr)
1126 goto error;
1127
1128 ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
1129 avio_skip(pb, desc_len - ret);
1130 if (*desc)
1131 av_dict_set(&st->metadata, "title", desc, 0);
1132
1133 avio_rl16(pb); /* flags? */
1134 avio_rl32(pb); /* data size */
1135
1136 size = pb->buf_end - pb->buf_ptr;
1137 pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
1138 .buf_size = size };
1139 if (!pd.buf)
1140 goto error;
1141 memcpy(pd.buf, pb->buf_ptr, size);
1142 sub_demuxer = av_probe_input_format2(&pd, 1, &score);
1143 av_freep(&pd.buf);
1144 if (!sub_demuxer)
1145 goto error;
1146
1147 if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
1148 goto error;
1149
1150 if (!(ast->sub_pkt = av_packet_alloc()))
1151 goto error;
1152
1153 if (!(ast->sub_ctx = avformat_alloc_context()))
1154 goto error;
1155
1156 ast->sub_ctx->pb = pb;
1157
1158 if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
1159 goto error;
1160
1161 if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
1162 if (ast->sub_ctx->nb_streams != 1)
1163 goto error;
1164 ff_read_packet(ast->sub_ctx, ast->sub_pkt);
1165 avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
1166 time_base = ast->sub_ctx->streams[0]->time_base;
1167 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
1168 }
1169 ast->sub_buffer = pkt->buf;
1170 pkt->buf = NULL;
1171 av_packet_unref(pkt);
1172 return 1;
1173
1174 error:
1175 av_packet_free(&ast->sub_pkt);
1176 av_freep(&ast->sub_ctx);
1177 avio_context_free(&pb);
1178 }
1179 return 0;
1180 }
1181
get_subtitle_pkt(AVFormatContext *s, AVStream *next_st, AVPacket *pkt)1182 static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
1183 AVPacket *pkt)
1184 {
1185 AVIStream *ast, *next_ast = next_st->priv_data;
1186 int64_t ts, next_ts, ts_min = INT64_MAX;
1187 AVStream *st, *sub_st = NULL;
1188 int i;
1189
1190 next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
1191 AV_TIME_BASE_Q);
1192
1193 for (i = 0; i < s->nb_streams; i++) {
1194 st = s->streams[i];
1195 ast = st->priv_data;
1196 if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt && ast->sub_pkt->data) {
1197 ts = av_rescale_q(ast->sub_pkt->dts, st->time_base, AV_TIME_BASE_Q);
1198 if (ts <= next_ts && ts < ts_min) {
1199 ts_min = ts;
1200 sub_st = st;
1201 }
1202 }
1203 }
1204
1205 if (sub_st) {
1206 ast = sub_st->priv_data;
1207 av_packet_move_ref(pkt, ast->sub_pkt);
1208 pkt->stream_index = sub_st->index;
1209
1210 if (ff_read_packet(ast->sub_ctx, ast->sub_pkt) < 0)
1211 ast->sub_pkt->data = NULL;
1212 }
1213 return sub_st;
1214 }
1215
get_stream_idx(const unsigned *d)1216 static int get_stream_idx(const unsigned *d)
1217 {
1218 if (d[0] >= '0' && d[0] <= '9' &&
1219 d[1] >= '0' && d[1] <= '9') {
1220 return (d[0] - '0') * 10 + (d[1] - '0');
1221 } else {
1222 return 100; // invalid stream ID
1223 }
1224 }
1225
1226 /**
1227 *
1228 * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
1229 */
avi_sync(AVFormatContext *s, int exit_early)1230 static int avi_sync(AVFormatContext *s, int exit_early)
1231 {
1232 AVIContext *avi = s->priv_data;
1233 AVIOContext *pb = s->pb;
1234 int n;
1235 unsigned int d[8];
1236 unsigned int size;
1237 int64_t i, sync;
1238
1239 start_sync:
1240 memset(d, -1, sizeof(d));
1241 for (i = sync = avio_tell(pb); !avio_feof(pb); i++) {
1242 int j;
1243
1244 for (j = 0; j < 7; j++)
1245 d[j] = d[j + 1];
1246 d[7] = avio_r8(pb);
1247
1248 size = d[4] + (d[5] << 8) + (d[6] << 16) + (d[7] << 24);
1249
1250 n = get_stream_idx(d + 2);
1251 ff_tlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
1252 d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
1253 if (i*(avi->io_fsize>0) + (uint64_t)size > avi->fsize || d[0] > 127)
1254 continue;
1255
1256 // parse ix##
1257 if ((d[0] == 'i' && d[1] == 'x' && n < s->nb_streams) ||
1258 // parse JUNK
1259 (d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K') ||
1260 (d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1') ||
1261 (d[0] == 'i' && d[1] == 'n' && d[2] == 'd' && d[3] == 'x')) {
1262 avio_skip(pb, size);
1263 goto start_sync;
1264 }
1265
1266 // parse stray LIST
1267 if (d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T') {
1268 avio_skip(pb, 4);
1269 goto start_sync;
1270 }
1271
1272 n = get_stream_idx(d);
1273
1274 if (!((i - avi->last_pkt_pos) & 1) &&
1275 get_stream_idx(d + 1) < s->nb_streams)
1276 continue;
1277
1278 // detect ##ix chunk and skip
1279 if (d[2] == 'i' && d[3] == 'x' && n < s->nb_streams) {
1280 avio_skip(pb, size);
1281 goto start_sync;
1282 }
1283
1284 if (d[2] == 'w' && d[3] == 'c' && n < s->nb_streams) {
1285 avio_skip(pb, 16 * 3 + 8);
1286 goto start_sync;
1287 }
1288
1289 if (avi->dv_demux && n != 0)
1290 continue;
1291
1292 // parse ##dc/##wb
1293 if (n < s->nb_streams) {
1294 AVStream *st;
1295 AVIStream *ast;
1296 st = s->streams[n];
1297 ast = st->priv_data;
1298
1299 if (!ast) {
1300 av_log(s, AV_LOG_WARNING, "Skipping foreign stream %d packet\n", n);
1301 continue;
1302 }
1303
1304 if (s->nb_streams >= 2) {
1305 AVStream *st1 = s->streams[1];
1306 AVIStream *ast1 = st1->priv_data;
1307 // workaround for broken small-file-bug402.avi
1308 if (ast1 && d[2] == 'w' && d[3] == 'b'
1309 && n == 0
1310 && st ->codecpar->codec_type == AVMEDIA_TYPE_VIDEO
1311 && st1->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
1312 && ast->prefix == 'd'*256+'c'
1313 && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
1314 ) {
1315 n = 1;
1316 st = st1;
1317 ast = ast1;
1318 av_log(s, AV_LOG_WARNING,
1319 "Invalid stream + prefix combination, assuming audio.\n");
1320 }
1321 }
1322
1323 if (d[2] == 'p' && d[3] == 'c' && size <= 4 * 256 + 4) {
1324 int k = avio_r8(pb);
1325 int last = (k + avio_r8(pb) - 1) & 0xFF;
1326
1327 avio_rl16(pb); // flags
1328
1329 // b + (g << 8) + (r << 16);
1330 for (; k <= last; k++)
1331 ast->pal[k] = 0xFFU<<24 | avio_rb32(pb)>>8;
1332
1333 ast->has_pal = 1;
1334 goto start_sync;
1335 } else if (((ast->prefix_count < 5 || sync + 9 > i) &&
1336 d[2] < 128 && d[3] < 128) ||
1337 d[2] * 256 + d[3] == ast->prefix /* ||
1338 (d[2] == 'd' && d[3] == 'c') ||
1339 (d[2] == 'w' && d[3] == 'b') */) {
1340 if (exit_early)
1341 return 0;
1342 if (d[2] * 256 + d[3] == ast->prefix)
1343 ast->prefix_count++;
1344 else {
1345 ast->prefix = d[2] * 256 + d[3];
1346 ast->prefix_count = 0;
1347 }
1348
1349 if (!avi->dv_demux &&
1350 ((st->discard >= AVDISCARD_DEFAULT && size == 0) /* ||
1351 // FIXME: needs a little reordering
1352 (st->discard >= AVDISCARD_NONKEY &&
1353 !(pkt->flags & AV_PKT_FLAG_KEY)) */
1354 || st->discard >= AVDISCARD_ALL)) {
1355
1356 ast->frame_offset += get_duration(ast, size);
1357 avio_skip(pb, size);
1358 goto start_sync;
1359 }
1360
1361 avi->stream_index = n;
1362 ast->packet_size = size + 8;
1363 ast->remaining = size;
1364
1365 if (size) {
1366 FFStream *const sti = ffstream(st);
1367 uint64_t pos = avio_tell(pb) - 8;
1368 if (!sti->index_entries || !sti->nb_index_entries ||
1369 sti->index_entries[sti->nb_index_entries - 1].pos < pos) {
1370 av_add_index_entry(st, pos, ast->frame_offset, size,
1371 0, AVINDEX_KEYFRAME);
1372 }
1373 }
1374 return 0;
1375 }
1376 }
1377 }
1378
1379 if (pb->error)
1380 return pb->error;
1381 return AVERROR_EOF;
1382 }
1383
ni_prepare_read(AVFormatContext *s)1384 static int ni_prepare_read(AVFormatContext *s)
1385 {
1386 AVIContext *avi = s->priv_data;
1387 int best_stream_index = 0;
1388 AVStream *best_st = NULL;
1389 FFStream *best_sti;
1390 AVIStream *best_ast;
1391 int64_t best_ts = INT64_MAX;
1392 int i;
1393
1394 for (i = 0; i < s->nb_streams; i++) {
1395 AVStream *st = s->streams[i];
1396 FFStream *const sti = ffstream(st);
1397 AVIStream *ast = st->priv_data;
1398 int64_t ts = ast->frame_offset;
1399 int64_t last_ts;
1400
1401 if (!sti->nb_index_entries)
1402 continue;
1403
1404 last_ts = sti->index_entries[sti->nb_index_entries - 1].timestamp;
1405 if (!ast->remaining && ts > last_ts)
1406 continue;
1407
1408 ts = av_rescale_q(ts, st->time_base,
1409 (AVRational) { FFMAX(1, ast->sample_size),
1410 AV_TIME_BASE });
1411
1412 av_log(s, AV_LOG_TRACE, "%"PRId64" %d/%d %"PRId64"\n", ts,
1413 st->time_base.num, st->time_base.den, ast->frame_offset);
1414 if (ts < best_ts) {
1415 best_ts = ts;
1416 best_st = st;
1417 best_stream_index = i;
1418 }
1419 }
1420 if (!best_st)
1421 return AVERROR_EOF;
1422
1423 best_sti = ffstream(best_st);
1424 best_ast = best_st->priv_data;
1425 best_ts = best_ast->frame_offset;
1426 if (best_ast->remaining) {
1427 i = av_index_search_timestamp(best_st,
1428 best_ts,
1429 AVSEEK_FLAG_ANY |
1430 AVSEEK_FLAG_BACKWARD);
1431 } else {
1432 i = av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1433 if (i >= 0)
1434 best_ast->frame_offset = best_sti->index_entries[i].timestamp;
1435 }
1436
1437 if (i >= 0) {
1438 int64_t pos = best_sti->index_entries[i].pos;
1439 pos += best_ast->packet_size - best_ast->remaining;
1440 if (avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
1441 return AVERROR_EOF;
1442
1443 av_assert0(best_ast->remaining <= best_ast->packet_size);
1444
1445 avi->stream_index = best_stream_index;
1446 if (!best_ast->remaining)
1447 best_ast->packet_size =
1448 best_ast->remaining = best_sti->index_entries[i].size;
1449 }
1450 else
1451 return AVERROR_EOF;
1452
1453 return 0;
1454 }
1455
avi_read_packet(AVFormatContext *s, AVPacket *pkt)1456 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
1457 {
1458 AVIContext *avi = s->priv_data;
1459 AVIOContext *pb = s->pb;
1460 int err;
1461
1462 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1463 int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
1464 if (size >= 0)
1465 return size;
1466 else
1467 goto resync;
1468 }
1469
1470 if (avi->non_interleaved) {
1471 err = ni_prepare_read(s);
1472 if (err < 0)
1473 return err;
1474 }
1475
1476 resync:
1477 if (avi->stream_index >= 0) {
1478 AVStream *st = s->streams[avi->stream_index];
1479 FFStream *const sti = ffstream(st);
1480 AVIStream *ast = st->priv_data;
1481 int dv_demux = CONFIG_DV_DEMUXER && avi->dv_demux;
1482 int size, err;
1483
1484 if (get_subtitle_pkt(s, st, pkt))
1485 return 0;
1486
1487 // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1488 if (ast->sample_size <= 1)
1489 size = INT_MAX;
1490 else if (ast->sample_size < 32)
1491 // arbitrary multiplier to avoid tiny packets for raw PCM data
1492 size = 1024 * ast->sample_size;
1493 else
1494 size = ast->sample_size;
1495
1496 if (size > ast->remaining)
1497 size = ast->remaining;
1498 avi->last_pkt_pos = avio_tell(pb);
1499 err = av_get_packet(pb, pkt, size);
1500 if (err < 0)
1501 return err;
1502 size = err;
1503
1504 if (ast->has_pal && pkt->size < (unsigned)INT_MAX / 2 && !dv_demux) {
1505 uint8_t *pal;
1506 pal = av_packet_new_side_data(pkt,
1507 AV_PKT_DATA_PALETTE,
1508 AVPALETTE_SIZE);
1509 if (!pal) {
1510 av_log(s, AV_LOG_ERROR,
1511 "Failed to allocate data for palette\n");
1512 } else {
1513 memcpy(pal, ast->pal, AVPALETTE_SIZE);
1514 ast->has_pal = 0;
1515 }
1516 }
1517
1518 if (CONFIG_DV_DEMUXER && dv_demux) {
1519 size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1520 pkt->data, pkt->size, pkt->pos);
1521 pkt->flags |= AV_PKT_FLAG_KEY;
1522 if (size < 0)
1523 av_packet_unref(pkt);
1524 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1525 !st->codecpar->codec_tag && read_gab2_sub(s, st, pkt)) {
1526 ast->frame_offset++;
1527 avi->stream_index = -1;
1528 ast->remaining = 0;
1529 goto resync;
1530 } else {
1531 /* XXX: How to handle B-frames in AVI? */
1532 pkt->dts = ast->frame_offset;
1533 // pkt->dts += ast->start;
1534 if (ast->sample_size)
1535 pkt->dts /= ast->sample_size;
1536 pkt->stream_index = avi->stream_index;
1537
1538 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sti->index_entries) {
1539 AVIndexEntry *e;
1540 int index;
1541
1542 index = av_index_search_timestamp(st, ast->frame_offset, AVSEEK_FLAG_ANY);
1543 e = &sti->index_entries[index];
1544
1545 if (index >= 0 && e->timestamp == ast->frame_offset) {
1546 if (index == sti->nb_index_entries-1) {
1547 int key=1;
1548 uint32_t state=-1;
1549 if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
1550 const uint8_t *ptr = pkt->data, *end = ptr + FFMIN(size, 256);
1551 while (ptr < end) {
1552 ptr = avpriv_find_start_code(ptr, end, &state);
1553 if (state == 0x1B6 && ptr < end) {
1554 key = !(*ptr & 0xC0);
1555 break;
1556 }
1557 }
1558 }
1559 if (!key)
1560 e->flags &= ~AVINDEX_KEYFRAME;
1561 }
1562 if (e->flags & AVINDEX_KEYFRAME)
1563 pkt->flags |= AV_PKT_FLAG_KEY;
1564 }
1565 } else {
1566 pkt->flags |= AV_PKT_FLAG_KEY;
1567 }
1568 ast->frame_offset += get_duration(ast, pkt->size);
1569 }
1570 ast->remaining -= err;
1571 if (!ast->remaining) {
1572 avi->stream_index = -1;
1573 ast->packet_size = 0;
1574 }
1575
1576 if (!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos) {
1577 av_packet_unref(pkt);
1578 goto resync;
1579 }
1580 ast->seek_pos= 0;
1581
1582 if (!avi->non_interleaved && sti->nb_index_entries > 1 && avi->index_loaded > 1) {
1583 int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
1584
1585 if (avi->dts_max < dts) {
1586 avi->dts_max = dts;
1587 } else if (avi->dts_max - (uint64_t)dts > 2*AV_TIME_BASE) {
1588 avi->non_interleaved= 1;
1589 av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
1590 }
1591 }
1592
1593 return 0;
1594 }
1595
1596 if ((err = avi_sync(s, 0)) < 0)
1597 return err;
1598 goto resync;
1599 }
1600
1601 /* XXX: We make the implicit supposition that the positions are sorted
1602 * for each stream. */
avi_read_idx1(AVFormatContext *s, int size)1603 static int avi_read_idx1(AVFormatContext *s, int size)
1604 {
1605 AVIContext *avi = s->priv_data;
1606 AVIOContext *pb = s->pb;
1607 int nb_index_entries, i;
1608 AVStream *st;
1609 AVIStream *ast;
1610 int64_t pos;
1611 unsigned int index, tag, flags, len, first_packet = 1;
1612 int64_t last_pos = -1;
1613 unsigned last_idx = -1;
1614 int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1615 int anykey = 0;
1616
1617 nb_index_entries = size / 16;
1618 if (nb_index_entries <= 0)
1619 return AVERROR_INVALIDDATA;
1620
1621 idx1_pos = avio_tell(pb);
1622 avio_seek(pb, avi->movi_list + 4, SEEK_SET);
1623 if (avi_sync(s, 1) == 0)
1624 first_packet_pos = avio_tell(pb) - 8;
1625 avi->stream_index = -1;
1626 avio_seek(pb, idx1_pos, SEEK_SET);
1627
1628 if (s->nb_streams == 1 && s->streams[0]->codecpar->codec_tag == AV_RL32("MMES")) {
1629 first_packet_pos = 0;
1630 data_offset = avi->movi_list;
1631 }
1632
1633 /* Read the entries and sort them in each stream component. */
1634 for (i = 0; i < nb_index_entries; i++) {
1635 if (avio_feof(pb))
1636 return -1;
1637
1638 tag = avio_rl32(pb);
1639 flags = avio_rl32(pb);
1640 pos = avio_rl32(pb);
1641 len = avio_rl32(pb);
1642 av_log(s, AV_LOG_TRACE, "%d: tag=0x%x flags=0x%x pos=0x%"PRIx64" len=%d/",
1643 i, tag, flags, pos, len);
1644
1645 index = ((tag & 0xff) - '0') * 10;
1646 index += (tag >> 8 & 0xff) - '0';
1647 if (index >= s->nb_streams)
1648 continue;
1649 st = s->streams[index];
1650 ast = st->priv_data;
1651
1652 /* Skip 'xxpc' palette change entries in the index until a logic
1653 * to process these is properly implemented. */
1654 if ((tag >> 16 & 0xff) == 'p' && (tag >> 24 & 0xff) == 'c')
1655 continue;
1656
1657 if (first_packet && first_packet_pos) {
1658 if (avi->movi_list + 4 != pos || pos + 500 > first_packet_pos)
1659 data_offset = first_packet_pos - pos;
1660 first_packet = 0;
1661 }
1662 pos += data_offset;
1663
1664 av_log(s, AV_LOG_TRACE, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1665
1666 // even if we have only a single stream, we should
1667 // switch to non-interleaved to get correct timestamps
1668 if (last_pos == pos)
1669 avi->non_interleaved = 1;
1670 if (last_idx != pos && len) {
1671 av_add_index_entry(st, pos, ast->cum_len, len, 0,
1672 (flags & AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1673 last_idx= pos;
1674 }
1675 ast->cum_len += get_duration(ast, len);
1676 last_pos = pos;
1677 anykey |= flags&AVIIF_INDEX;
1678 }
1679 if (!anykey) {
1680 for (index = 0; index < s->nb_streams; index++) {
1681 FFStream *const sti = ffstream(s->streams[index]);
1682 if (sti->nb_index_entries)
1683 sti->index_entries[0].flags |= AVINDEX_KEYFRAME;
1684 }
1685 }
1686 return 0;
1687 }
1688
1689 /* Scan the index and consider any file with streams more than
1690 * 2 seconds or 64MB apart non-interleaved. */
check_stream_max_drift(AVFormatContext *s)1691 static int check_stream_max_drift(AVFormatContext *s)
1692 {
1693 int64_t min_pos, pos;
1694 int i;
1695 int *idx = av_calloc(s->nb_streams, sizeof(*idx));
1696 if (!idx)
1697 return AVERROR(ENOMEM);
1698 for (min_pos = pos = 0; min_pos != INT64_MAX; pos = min_pos + 1LU) {
1699 int64_t max_dts = INT64_MIN / 2;
1700 int64_t min_dts = INT64_MAX / 2;
1701 int64_t max_buffer = 0;
1702
1703 min_pos = INT64_MAX;
1704
1705 for (i = 0; i < s->nb_streams; i++) {
1706 AVStream *st = s->streams[i];
1707 AVIStream *ast = st->priv_data;
1708 FFStream *const sti = ffstream(st);
1709 int n = sti->nb_index_entries;
1710 while (idx[i] < n && sti->index_entries[idx[i]].pos < pos)
1711 idx[i]++;
1712 if (idx[i] < n) {
1713 int64_t dts;
1714 dts = av_rescale_q(sti->index_entries[idx[i]].timestamp /
1715 FFMAX(ast->sample_size, 1),
1716 st->time_base, AV_TIME_BASE_Q);
1717 min_dts = FFMIN(min_dts, dts);
1718 min_pos = FFMIN(min_pos, sti->index_entries[idx[i]].pos);
1719 }
1720 }
1721 for (i = 0; i < s->nb_streams; i++) {
1722 AVStream *st = s->streams[i];
1723 FFStream *const sti = ffstream(st);
1724 AVIStream *ast = st->priv_data;
1725
1726 if (idx[i] && min_dts != INT64_MAX / 2) {
1727 int64_t dts, delta_dts;
1728 dts = av_rescale_q(sti->index_entries[idx[i] - 1].timestamp /
1729 FFMAX(ast->sample_size, 1),
1730 st->time_base, AV_TIME_BASE_Q);
1731 delta_dts = av_sat_sub64(dts, min_dts);
1732 max_dts = FFMAX(max_dts, dts);
1733 max_buffer = FFMAX(max_buffer,
1734 av_rescale(delta_dts,
1735 st->codecpar->bit_rate,
1736 AV_TIME_BASE));
1737 }
1738 }
1739 if (av_sat_sub64(max_dts, min_dts) > 2 * AV_TIME_BASE ||
1740 max_buffer > 1024 * 1024 * 8 * 8) {
1741 av_free(idx);
1742 return 1;
1743 }
1744 }
1745 av_free(idx);
1746 return 0;
1747 }
1748
guess_ni_flag(AVFormatContext *s)1749 static int guess_ni_flag(AVFormatContext *s)
1750 {
1751 int i;
1752 int64_t last_start = 0;
1753 int64_t first_end = INT64_MAX;
1754 int64_t oldpos = avio_tell(s->pb);
1755
1756 for (i = 0; i < s->nb_streams; i++) {
1757 AVStream *st = s->streams[i];
1758 FFStream *const sti = ffstream(st);
1759 int n = sti->nb_index_entries;
1760 unsigned int size;
1761
1762 if (n <= 0)
1763 continue;
1764
1765 if (n >= 2) {
1766 int64_t pos = sti->index_entries[0].pos;
1767 unsigned tag[2];
1768 avio_seek(s->pb, pos, SEEK_SET);
1769 tag[0] = avio_r8(s->pb);
1770 tag[1] = avio_r8(s->pb);
1771 avio_rl16(s->pb);
1772 size = avio_rl32(s->pb);
1773 if (get_stream_idx(tag) == i && pos + size > sti->index_entries[1].pos)
1774 last_start = INT64_MAX;
1775 if (get_stream_idx(tag) == i && size == sti->index_entries[0].size + 8)
1776 last_start = INT64_MAX;
1777 }
1778
1779 if (sti->index_entries[0].pos > last_start)
1780 last_start = sti->index_entries[0].pos;
1781 if (sti->index_entries[n - 1].pos < first_end)
1782 first_end = sti->index_entries[n - 1].pos;
1783 }
1784 avio_seek(s->pb, oldpos, SEEK_SET);
1785
1786 if (last_start > first_end)
1787 return 1;
1788
1789 return check_stream_max_drift(s);
1790 }
1791
avi_load_index(AVFormatContext *s)1792 static int avi_load_index(AVFormatContext *s)
1793 {
1794 AVIContext *avi = s->priv_data;
1795 AVIOContext *pb = s->pb;
1796 uint32_t tag, size;
1797 int64_t pos = avio_tell(pb);
1798 int64_t next;
1799 int ret = -1;
1800
1801 if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1802 goto the_end; // maybe truncated file
1803 av_log(s, AV_LOG_TRACE, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1804 for (;;) {
1805 tag = avio_rl32(pb);
1806 size = avio_rl32(pb);
1807 if (avio_feof(pb))
1808 break;
1809 next = avio_tell(pb);
1810 if (next < 0 || next > INT64_MAX - size - (size & 1))
1811 break;
1812 next += size + (size & 1LL);
1813
1814 if (tag == MKTAG('i', 'd', 'x', '1') &&
1815 avi_read_idx1(s, size) >= 0) {
1816 avi->index_loaded=2;
1817 ret = 0;
1818 }else if (tag == MKTAG('L', 'I', 'S', 'T')) {
1819 uint32_t tag1 = avio_rl32(pb);
1820
1821 if (tag1 == MKTAG('I', 'N', 'F', 'O'))
1822 ff_read_riff_info(s, size - 4);
1823 }else if (!ret)
1824 break;
1825
1826 if (avio_seek(pb, next, SEEK_SET) < 0)
1827 break; // something is wrong here
1828 }
1829
1830 the_end:
1831 avio_seek(pb, pos, SEEK_SET);
1832 return ret;
1833 }
1834
seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)1835 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1836 {
1837 AVIStream *ast2 = st2->priv_data;
1838 int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1839 av_packet_unref(ast2->sub_pkt);
1840 if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1841 avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1842 ff_read_packet(ast2->sub_ctx, ast2->sub_pkt);
1843 }
1844
avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)1845 static int avi_read_seek(AVFormatContext *s, int stream_index,
1846 int64_t timestamp, int flags)
1847 {
1848 AVIContext *avi = s->priv_data;
1849 AVStream *st;
1850 FFStream *sti;
1851 int i, index;
1852 int64_t pos, pos_min;
1853 AVIStream *ast;
1854
1855 /* Does not matter which stream is requested dv in avi has the
1856 * stream information in the first video stream.
1857 */
1858 if (avi->dv_demux)
1859 stream_index = 0;
1860
1861 if (!avi->index_loaded) {
1862 /* we only load the index on demand */
1863 avi_load_index(s);
1864 avi->index_loaded |= 1;
1865 }
1866 av_assert0(stream_index >= 0);
1867
1868 st = s->streams[stream_index];
1869 sti = ffstream(st);
1870 ast = st->priv_data;
1871 index = av_index_search_timestamp(st,
1872 timestamp * FFMAX(ast->sample_size, 1),
1873 flags);
1874 if (index < 0) {
1875 if (sti->nb_index_entries > 0)
1876 av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
1877 timestamp * FFMAX(ast->sample_size, 1),
1878 sti->index_entries[0].timestamp,
1879 sti->index_entries[sti->nb_index_entries - 1].timestamp);
1880 return AVERROR_INVALIDDATA;
1881 }
1882
1883 /* find the position */
1884 pos = sti->index_entries[index].pos;
1885 timestamp = sti->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1886
1887 av_log(s, AV_LOG_TRACE, "XX %"PRId64" %d %"PRId64"\n",
1888 timestamp, index, sti->index_entries[index].timestamp);
1889
1890 if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1891 /* One and only one real stream for DV in AVI, and it has video */
1892 /* offsets. Calling with other stream indexes should have failed */
1893 /* the av_index_search_timestamp call above. */
1894
1895 if (avio_seek(s->pb, pos, SEEK_SET) < 0)
1896 return -1;
1897
1898 /* Feed the DV video stream version of the timestamp to the */
1899 /* DV demux so it can synthesize correct timestamps. */
1900 ff_dv_offset_reset(avi->dv_demux, timestamp);
1901
1902 avi->stream_index = -1;
1903 return 0;
1904 }
1905
1906 pos_min = pos;
1907 for (i = 0; i < s->nb_streams; i++) {
1908 AVStream *st2 = s->streams[i];
1909 FFStream *const sti2 = ffstream(st2);
1910 AVIStream *ast2 = st2->priv_data;
1911
1912 ast2->packet_size =
1913 ast2->remaining = 0;
1914
1915 if (ast2->sub_ctx) {
1916 seek_subtitle(st, st2, timestamp);
1917 continue;
1918 }
1919
1920 if (sti2->nb_index_entries <= 0)
1921 continue;
1922
1923 // av_assert1(st2->codecpar->block_align);
1924 index = av_index_search_timestamp(st2,
1925 av_rescale_q(timestamp,
1926 st->time_base,
1927 st2->time_base) *
1928 FFMAX(ast2->sample_size, 1),
1929 flags |
1930 AVSEEK_FLAG_BACKWARD |
1931 (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1932 if (index < 0)
1933 index = 0;
1934 ast2->seek_pos = sti2->index_entries[index].pos;
1935 pos_min = FFMIN(pos_min,ast2->seek_pos);
1936 }
1937 for (i = 0; i < s->nb_streams; i++) {
1938 AVStream *st2 = s->streams[i];
1939 FFStream *const sti2 = ffstream(st2);
1940 AVIStream *ast2 = st2->priv_data;
1941
1942 if (ast2->sub_ctx || sti2->nb_index_entries <= 0)
1943 continue;
1944
1945 index = av_index_search_timestamp(
1946 st2,
1947 av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1948 flags | AVSEEK_FLAG_BACKWARD | (st2->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
1949 if (index < 0)
1950 index = 0;
1951 while (!avi->non_interleaved && index > 0 && sti2->index_entries[index-1].pos >= pos_min)
1952 index--;
1953 ast2->frame_offset = sti2->index_entries[index].timestamp;
1954 }
1955
1956 /* do the seek */
1957 if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
1958 av_log(s, AV_LOG_ERROR, "Seek failed\n");
1959 return -1;
1960 }
1961 avi->stream_index = -1;
1962 avi->dts_max = INT_MIN;
1963 return 0;
1964 }
1965
avi_read_close(AVFormatContext *s)1966 static int avi_read_close(AVFormatContext *s)
1967 {
1968 int i;
1969 AVIContext *avi = s->priv_data;
1970
1971 for (i = 0; i < s->nb_streams; i++) {
1972 AVStream *st = s->streams[i];
1973 AVIStream *ast = st->priv_data;
1974 if (ast) {
1975 if (ast->sub_ctx) {
1976 av_freep(&ast->sub_ctx->pb);
1977 avformat_close_input(&ast->sub_ctx);
1978 }
1979 av_buffer_unref(&ast->sub_buffer);
1980 av_packet_free(&ast->sub_pkt);
1981 }
1982 }
1983
1984 av_freep(&avi->dv_demux);
1985
1986 return 0;
1987 }
1988
avi_probe(const AVProbeData *p)1989 static int avi_probe(const AVProbeData *p)
1990 {
1991 int i;
1992
1993 /* check file header */
1994 for (i = 0; avi_headers[i][0]; i++)
1995 if (AV_RL32(p->buf ) == AV_RL32(avi_headers[i] ) &&
1996 AV_RL32(p->buf + 8) == AV_RL32(avi_headers[i] + 4))
1997 return AVPROBE_SCORE_MAX;
1998
1999 return 0;
2000 }
2001
2002 const AVInputFormat ff_avi_demuxer = {
2003 .name = "avi",
2004 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
2005 .priv_data_size = sizeof(AVIContext),
2006 .flags_internal = FF_FMT_INIT_CLEANUP,
2007 .extensions = "avi",
2008 .read_probe = avi_probe,
2009 .read_header = avi_read_header,
2010 .read_packet = avi_read_packet,
2011 .read_close = avi_read_close,
2012 .read_seek = avi_read_seek,
2013 .priv_class = &demuxer_class,
2014 };
2015