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