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