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