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