Ticket #1755: avidec.c

File avidec.c, 54.0 KB (added by Heesuk Jung, 14 years ago)

suggest using sample size to improve current issue

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