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