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 "libavutil/intreadwrite.h"
23 #include "libavutil/mathematics.h"
24 #include "libavutil/bswap.h"
25 #include "libavutil/dict.h"
26 #include "libavutil/avstring.h"
27 #include "avformat.h"
28 #include "internal.h"
29 #include "avi.h"
30 #include "dv.h"
31 #include "riff.h"
32 
33 #undef NDEBUG
34 #include <assert.h>
35 
36 typedef struct AVIStream {
37  int64_t frame_offset; /* current frame (video) or byte (audio) counter
38  (used to compute the pts) */
39  int remaining;
41 
42  uint32_t scale;
43  uint32_t rate;
44  int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
45 
46  int64_t cum_len; /* temporary storage (used during seek) */
47 
48  int prefix;
50  uint32_t pal[256];
51  int has_pal;
53 
57 } AVIStream;
58 
59 typedef struct {
60  int64_t riff_end;
61  int64_t movi_end;
62  int64_t fsize;
63  int64_t movi_list;
64  int64_t last_pkt_pos;
66  int is_odml;
71 #define MAX_ODML_DEPTH 1000
72 } AVIContext;
73 
74 static const char avi_headers[][8] = {
75  { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
76  { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
77  { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
78  { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
79  { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
80  { 0 }
81 };
82 
84  { "strn", "title" },
85  { 0 },
86 };
87 
88 static int avi_load_index(AVFormatContext *s);
89 static int guess_ni_flag(AVFormatContext *s);
90 
91 #define print_tag(str, tag, size) \
92  av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
93  str, tag & 0xff, \
94  (tag >> 8) & 0xff, \
95  (tag >> 16) & 0xff, \
96  (tag >> 24) & 0xff, \
97  size)
98 
99 static inline int get_duration(AVIStream *ast, int len){
100  if(ast->sample_size){
101  return len;
102  }else if (ast->dshow_block_align){
103  return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
104  }else
105  return 1;
106 }
107 
109 {
110  AVIContext *avi = s->priv_data;
111  char header[8];
112  int i;
113 
114  /* check RIFF header */
115  avio_read(pb, header, 4);
116  avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
117  avi->riff_end += avio_tell(pb); /* RIFF chunk end */
118  avio_read(pb, header+4, 4);
119 
120  for(i=0; avi_headers[i][0]; i++)
121  if(!memcmp(header, avi_headers[i], 8))
122  break;
123  if(!avi_headers[i][0])
124  return -1;
125 
126  if(header[7] == 0x19)
127  av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
128 
129  return 0;
130 }
131 
132 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
133  AVIContext *avi = s->priv_data;
134  AVIOContext *pb = s->pb;
135  int longs_pre_entry= avio_rl16(pb);
136  int index_sub_type = avio_r8(pb);
137  int index_type = avio_r8(pb);
138  int entries_in_use = avio_rl32(pb);
139  int chunk_id = avio_rl32(pb);
140  int64_t base = avio_rl64(pb);
141  int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
142  AVStream *st;
143  AVIStream *ast;
144  int i;
145  int64_t last_pos= -1;
146  int64_t filesize= avio_size(s->pb);
147 
148  av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
149  longs_pre_entry,index_type, entries_in_use, chunk_id, base);
150 
151  if(stream_id >= s->nb_streams || stream_id < 0)
152  return -1;
153  st= s->streams[stream_id];
154  ast = st->priv_data;
155 
156  if(index_sub_type)
157  return -1;
158 
159  avio_rl32(pb);
160 
161  if(index_type && longs_pre_entry != 2)
162  return -1;
163  if(index_type>1)
164  return -1;
165 
166  if(filesize > 0 && base >= filesize){
167  av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
168  if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
169  base &= 0xFFFFFFFF;
170  else
171  return -1;
172  }
173 
174  for(i=0; i<entries_in_use; i++){
175  if(index_type){
176  int64_t pos= avio_rl32(pb) + base - 8;
177  int len = avio_rl32(pb);
178  int key= len >= 0;
179  len &= 0x7FFFFFFF;
180 
181  av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
182 
183  if(pb->eof_reached)
184  return -1;
185 
186  if(last_pos == pos || pos == base - 8)
187  avi->non_interleaved= 1;
188  if(last_pos != pos && (len || !ast->sample_size))
189  av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
190 
191  ast->cum_len += get_duration(ast, len);
192  last_pos= pos;
193  }else{
194  int64_t offset, pos;
195  int duration;
196  offset = avio_rl64(pb);
197  avio_rl32(pb); /* size */
198  duration = avio_rl32(pb);
199 
200  if(pb->eof_reached)
201  return -1;
202 
203  pos = avio_tell(pb);
204 
205  if(avi->odml_depth > MAX_ODML_DEPTH){
206  av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
207  return -1;
208  }
209 
210  avio_seek(pb, offset+8, SEEK_SET);
211  avi->odml_depth++;
212  read_braindead_odml_indx(s, frame_num);
213  avi->odml_depth--;
214  frame_num += duration;
215 
216  avio_seek(pb, pos, SEEK_SET);
217  }
218  }
219  avi->index_loaded=1;
220  return 0;
221 }
222 
223 static void clean_index(AVFormatContext *s){
224  int i;
225  int64_t j;
226 
227  for(i=0; i<s->nb_streams; i++){
228  AVStream *st = s->streams[i];
229  AVIStream *ast = st->priv_data;
230  int n= st->nb_index_entries;
231  int max= ast->sample_size;
232  int64_t pos, size, ts;
233 
234  if(n != 1 || ast->sample_size==0)
235  continue;
236 
237  while(max < 1024) max+=max;
238 
239  pos= st->index_entries[0].pos;
240  size= st->index_entries[0].size;
241  ts= st->index_entries[0].timestamp;
242 
243  for(j=0; j<size; j+=max){
244  av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
245  }
246  }
247 }
248 
249 static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
250 {
251  AVIOContext *pb = s->pb;
252  char key[5] = {0}, *value;
253 
254  size += (size & 1);
255 
256  if (size == UINT_MAX)
257  return -1;
258  value = av_malloc(size+1);
259  if (!value)
260  return -1;
261  avio_read(pb, value, size);
262  value[size]=0;
263 
264  AV_WL32(key, tag);
265 
266  return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
268 }
269 
270 static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
271  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
272 
273 static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
274 {
275  char month[4], time[9], buffer[64];
276  int i, day, year;
277  /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
278  if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
279  month, &day, time, &year) == 4) {
280  for (i=0; i<12; i++)
281  if (!av_strcasecmp(month, months[i])) {
282  snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
283  year, i+1, day, time);
284  av_dict_set(metadata, "creation_time", buffer, 0);
285  }
286  } else if (date[4] == '/' && date[7] == '/') {
287  date[4] = date[7] = '-';
288  av_dict_set(metadata, "creation_time", date, 0);
289  }
290 }
291 
292 static void avi_read_nikon(AVFormatContext *s, uint64_t end)
293 {
294  while (avio_tell(s->pb) < end) {
295  uint32_t tag = avio_rl32(s->pb);
296  uint32_t size = avio_rl32(s->pb);
297  switch (tag) {
298  case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
299  uint64_t tag_end = avio_tell(s->pb) + size;
300  while (avio_tell(s->pb) < tag_end) {
301  uint16_t tag = avio_rl16(s->pb);
302  uint16_t size = avio_rl16(s->pb);
303  const char *name = NULL;
304  char buffer[64] = {0};
305  size -= avio_read(s->pb, buffer,
306  FFMIN(size, sizeof(buffer)-1));
307  switch (tag) {
308  case 0x03: name = "maker"; break;
309  case 0x04: name = "model"; break;
310  case 0x13: name = "creation_time";
311  if (buffer[4] == ':' && buffer[7] == ':')
312  buffer[4] = buffer[7] = '-';
313  break;
314  }
315  if (name)
316  av_dict_set(&s->metadata, name, buffer, 0);
317  avio_skip(s->pb, size);
318  }
319  break;
320  }
321  default:
322  avio_skip(s->pb, size);
323  break;
324  }
325  }
326 }
327 
329 {
330  AVIContext *avi = s->priv_data;
331  AVIOContext *pb = s->pb;
332  unsigned int tag, tag1, handler;
333  int codec_type, stream_index, frame_period;
334  unsigned int size;
335  int i;
336  AVStream *st;
337  AVIStream *ast = NULL;
338  int avih_width=0, avih_height=0;
339  int amv_file_format=0;
340  uint64_t list_end = 0;
341  int ret;
342 
343  avi->stream_index= -1;
344 
345  if (get_riff(s, pb) < 0)
346  return -1;
347 
348  avi->fsize = avio_size(pb);
349  if(avi->fsize<=0)
350  avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
351 
352  /* first list tag */
353  stream_index = -1;
354  codec_type = -1;
355  frame_period = 0;
356  for(;;) {
357  if (pb->eof_reached)
358  goto fail;
359  tag = avio_rl32(pb);
360  size = avio_rl32(pb);
361 
362  print_tag("tag", tag, size);
363 
364  switch(tag) {
365  case MKTAG('L', 'I', 'S', 'T'):
366  list_end = avio_tell(pb) + size;
367  /* Ignored, except at start of video packets. */
368  tag1 = avio_rl32(pb);
369 
370  print_tag("list", tag1, 0);
371 
372  if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
373  avi->movi_list = avio_tell(pb) - 4;
374  if(size) avi->movi_end = avi->movi_list + size + (size & 1);
375  else avi->movi_end = avio_size(pb);
376  av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
377  goto end_of_header;
378  }
379  else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
380  ff_read_riff_info(s, size - 4);
381  else if (tag1 == MKTAG('n', 'c', 'd', 't'))
382  avi_read_nikon(s, list_end);
383 
384  break;
385  case MKTAG('I', 'D', 'I', 'T'): {
386  unsigned char date[64] = {0};
387  size += (size & 1);
388  size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
389  avio_skip(pb, size);
391  break;
392  }
393  case MKTAG('d', 'm', 'l', 'h'):
394  avi->is_odml = 1;
395  avio_skip(pb, size + (size & 1));
396  break;
397  case MKTAG('a', 'm', 'v', 'h'):
398  amv_file_format=1;
399  case MKTAG('a', 'v', 'i', 'h'):
400  /* AVI header */
401  /* using frame_period is bad idea */
402  frame_period = avio_rl32(pb);
403  avio_skip(pb, 4);
404  avio_rl32(pb);
406 
407  avio_skip(pb, 2 * 4);
408  avio_rl32(pb);
409  avio_rl32(pb);
410  avih_width=avio_rl32(pb);
411  avih_height=avio_rl32(pb);
412 
413  avio_skip(pb, size - 10 * 4);
414  break;
415  case MKTAG('s', 't', 'r', 'h'):
416  /* stream header */
417 
418  tag1 = avio_rl32(pb);
419  handler = avio_rl32(pb); /* codec tag */
420 
421  if(tag1 == MKTAG('p', 'a', 'd', 's')){
422  avio_skip(pb, size - 8);
423  break;
424  }else{
425  stream_index++;
426  st = avformat_new_stream(s, NULL);
427  if (!st)
428  goto fail;
429 
430  st->id = stream_index;
431  ast = av_mallocz(sizeof(AVIStream));
432  if (!ast)
433  goto fail;
434  st->priv_data = ast;
435  }
436  if(amv_file_format)
437  tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
438 
439  print_tag("strh", tag1, -1);
440 
441  if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
442  int64_t dv_dur;
443 
444  /*
445  * After some consideration -- I don't think we
446  * have to support anything but DV in type1 AVIs.
447  */
448  if (s->nb_streams != 1)
449  goto fail;
450 
451  if (handler != MKTAG('d', 'v', 's', 'd') &&
452  handler != MKTAG('d', 'v', 'h', 'd') &&
453  handler != MKTAG('d', 'v', 's', 'l'))
454  goto fail;
455 
456  ast = s->streams[0]->priv_data;
457  av_freep(&s->streams[0]->codec->extradata);
458  av_freep(&s->streams[0]->codec);
459  av_freep(&s->streams[0]->info);
460  av_freep(&s->streams[0]);
461  s->nb_streams = 0;
462  if (CONFIG_DV_DEMUXER) {
463  avi->dv_demux = avpriv_dv_init_demux(s);
464  if (!avi->dv_demux)
465  goto fail;
466  } else
467  goto fail;
468  s->streams[0]->priv_data = ast;
469  avio_skip(pb, 3 * 4);
470  ast->scale = avio_rl32(pb);
471  ast->rate = avio_rl32(pb);
472  avio_skip(pb, 4); /* start time */
473 
474  dv_dur = avio_rl32(pb);
475  if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
476  dv_dur *= AV_TIME_BASE;
477  s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
478  }
479  /*
480  * else, leave duration alone; timing estimation in utils.c
481  * will make a guess based on bitrate.
482  */
483 
484  stream_index = s->nb_streams - 1;
485  avio_skip(pb, size - 9*4);
486  break;
487  }
488 
489  assert(stream_index < s->nb_streams);
490  st->codec->stream_codec_tag= handler;
491 
492  avio_rl32(pb); /* flags */
493  avio_rl16(pb); /* priority */
494  avio_rl16(pb); /* language */
495  avio_rl32(pb); /* initial frame */
496  ast->scale = avio_rl32(pb);
497  ast->rate = avio_rl32(pb);
498  if(!(ast->scale && ast->rate)){
499  av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
500  if(frame_period){
501  ast->rate = 1000000;
502  ast->scale = frame_period;
503  }else{
504  ast->rate = 25;
505  ast->scale = 1;
506  }
507  }
508  avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
509 
510  ast->cum_len=avio_rl32(pb); /* start */
511  st->nb_frames = avio_rl32(pb);
512 
513  st->start_time = 0;
514  avio_rl32(pb); /* buffer size */
515  avio_rl32(pb); /* quality */
516  ast->sample_size = avio_rl32(pb); /* sample ssize */
517  ast->cum_len *= FFMAX(1, ast->sample_size);
518  av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
519  ast->rate, ast->scale, ast->sample_size);
520 
521  switch(tag1) {
522  case MKTAG('v', 'i', 'd', 's'):
523  codec_type = AVMEDIA_TYPE_VIDEO;
524 
525  ast->sample_size = 0;
526  break;
527  case MKTAG('a', 'u', 'd', 's'):
528  codec_type = AVMEDIA_TYPE_AUDIO;
529  break;
530  case MKTAG('t', 'x', 't', 's'):
531  codec_type = AVMEDIA_TYPE_SUBTITLE;
532  break;
533  case MKTAG('d', 'a', 't', 's'):
534  codec_type = AVMEDIA_TYPE_DATA;
535  break;
536  default:
537  av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
538  goto fail;
539  }
540  if(ast->sample_size == 0)
541  st->duration = st->nb_frames;
542  ast->frame_offset= ast->cum_len;
543  avio_skip(pb, size - 12 * 4);
544  break;
545  case MKTAG('s', 't', 'r', 'f'):
546  /* stream header */
547  if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
548  avio_skip(pb, size);
549  } else {
550  uint64_t cur_pos = avio_tell(pb);
551  if (cur_pos < list_end)
552  size = FFMIN(size, list_end - cur_pos);
553  st = s->streams[stream_index];
554  switch(codec_type) {
555  case AVMEDIA_TYPE_VIDEO:
556  if(amv_file_format){
557  st->codec->width=avih_width;
558  st->codec->height=avih_height;
561  avio_skip(pb, size);
562  break;
563  }
564  tag1 = ff_get_bmp_header(pb, st);
565 
566  if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
568  st->codec->codec_tag = tag1;
570  break;
571  }
572 
573  if(size > 10*4 && size<(1<<30)){
574  st->codec->extradata_size= size - 10*4;
576  if (!st->codec->extradata) {
577  st->codec->extradata_size= 0;
578  return AVERROR(ENOMEM);
579  }
580  avio_read(pb, st->codec->extradata, st->codec->extradata_size);
581  }
582 
583  if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
584  avio_r8(pb);
585 
586  /* Extract palette from extradata if bpp <= 8. */
587  /* This code assumes that extradata contains only palette. */
588  /* This is true for all paletted codecs implemented in Libav. */
589  if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
590  int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
591  const uint8_t *pal_src;
592 
593  pal_size = FFMIN(pal_size, st->codec->extradata_size);
594  pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
595 #if HAVE_BIGENDIAN
596  for (i = 0; i < pal_size/4; i++)
597  ast->pal[i] = av_bswap32(((uint32_t*)pal_src)[i]);
598 #else
599  memcpy(ast->pal, pal_src, pal_size);
600 #endif
601  ast->has_pal = 1;
602  }
603 
604  print_tag("video", tag1, 0);
605 
607  st->codec->codec_tag = tag1;
609  st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
610  // Support "Resolution 1:1" for Avid AVI Codec
611  if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
612  st->codec->extradata_size >= 31 &&
613  !memcmp(&st->codec->extradata[28], "1:1", 3))
615 
616  if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
617  st->codec->extradata_size+= 9;
619  if(st->codec->extradata)
620  memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
621  }
622  st->codec->height= FFABS(st->codec->height);
623 
624 // avio_skip(pb, size - 5 * 4);
625  break;
626  case AVMEDIA_TYPE_AUDIO:
627  ret = ff_get_wav_header(pb, st->codec, size);
628  if (ret < 0)
629  return ret;
631  if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
632  av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
633  ast->sample_size= st->codec->block_align;
634  }
635  if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
636  avio_skip(pb, 1);
637  /* Force parsing as several audio frames can be in
638  * one packet and timestamps refer to packet start. */
640  /* ADTS header is in extradata, AAC without header must be
641  * stored as exact frames. Parser not needed and it will
642  * fail. */
643  if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size)
645  /* AVI files with Xan DPCM audio (wrongly) declare PCM
646  * audio in the header but have Axan as stream_code_tag. */
647  if (st->codec->stream_codec_tag == AV_RL32("Axan")){
649  st->codec->codec_tag = 0;
650  }
651  if (amv_file_format){
653  ast->dshow_block_align = 0;
654  }
655  break;
659  break;
660  default:
663  st->codec->codec_tag= 0;
664  avio_skip(pb, size);
665  break;
666  }
667  }
668  break;
669  case MKTAG('i', 'n', 'd', 'x'):
670  i= avio_tell(pb);
671  if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&
672  read_braindead_odml_indx(s, 0) < 0 &&
674  goto fail;
675  avio_seek(pb, i+size, SEEK_SET);
676  break;
677  case MKTAG('v', 'p', 'r', 'p'):
678  if(stream_index < (unsigned)s->nb_streams && size > 9*4){
679  AVRational active, active_aspect;
680 
681  st = s->streams[stream_index];
682  avio_rl32(pb);
683  avio_rl32(pb);
684  avio_rl32(pb);
685  avio_rl32(pb);
686  avio_rl32(pb);
687 
688  active_aspect.den= avio_rl16(pb);
689  active_aspect.num= avio_rl16(pb);
690  active.num = avio_rl32(pb);
691  active.den = avio_rl32(pb);
692  avio_rl32(pb); //nbFieldsPerFrame
693 
694  if(active_aspect.num && active_aspect.den && active.num && active.den){
695  st->sample_aspect_ratio= av_div_q(active_aspect, active);
696  av_dlog(s, "vprp %d/%d %d/%d\n",
697  active_aspect.num, active_aspect.den,
698  active.num, active.den);
699  }
700  size -= 9*4;
701  }
702  avio_skip(pb, size);
703  break;
704  case MKTAG('s', 't', 'r', 'n'):
705  if(s->nb_streams){
706  avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
707  break;
708  }
709  default:
710  if(size > 1000000){
711  av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
712  "I will ignore it and try to continue anyway.\n");
714  goto fail;
715  avi->movi_list = avio_tell(pb) - 4;
716  avi->movi_end = avio_size(pb);
717  goto end_of_header;
718  }
719  /* skip tag */
720  size += (size & 1);
721  avio_skip(pb, size);
722  break;
723  }
724  }
725  end_of_header:
726  /* check stream number */
727  if (stream_index != s->nb_streams - 1) {
728  fail:
729  return -1;
730  }
731 
732  if(!avi->index_loaded && pb->seekable)
733  avi_load_index(s);
734  avi->index_loaded = 1;
735  avi->non_interleaved |= guess_ni_flag(s);
736  for(i=0; i<s->nb_streams; i++){
737  AVStream *st = s->streams[i];
738  if(st->nb_index_entries)
739  break;
740  }
741  if(i==s->nb_streams && avi->non_interleaved) {
742  av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
743  avi->non_interleaved=0;
744  }
745 
746  if(avi->non_interleaved) {
747  av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
748  clean_index(s);
749  }
750 
751  ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
753 
754  return 0;
755 }
756 
757 static int read_gab2_sub(AVStream *st, AVPacket *pkt)
758 {
759  if (pkt->size >= 7 &&
760  !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
761  uint8_t desc[256];
762  int score = AVPROBE_SCORE_MAX / 2, ret;
763  AVIStream *ast = st->priv_data;
764  AVInputFormat *sub_demuxer;
765  AVRational time_base;
766  AVIOContext *pb = avio_alloc_context( pkt->data + 7,
767  pkt->size - 7,
768  0, NULL, NULL, NULL, NULL);
769  AVProbeData pd;
770  unsigned int desc_len = avio_rl32(pb);
771 
772  if (desc_len > pb->buf_end - pb->buf_ptr)
773  goto error;
774 
775  ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
776  avio_skip(pb, desc_len - ret);
777  if (*desc)
778  av_dict_set(&st->metadata, "title", desc, 0);
779 
780  avio_rl16(pb); /* flags? */
781  avio_rl32(pb); /* data size */
782 
783  pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
784  if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
785  goto error;
786 
787  if (!(ast->sub_ctx = avformat_alloc_context()))
788  goto error;
789 
790  ast->sub_ctx->pb = pb;
791  if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
792  ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
793  *st->codec = *ast->sub_ctx->streams[0]->codec;
794  ast->sub_ctx->streams[0]->codec->extradata = NULL;
795  time_base = ast->sub_ctx->streams[0]->time_base;
796  avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
797  }
798  ast->sub_buffer = pkt->data;
799  memset(pkt, 0, sizeof(*pkt));
800  return 1;
801 error:
802  av_freep(&pb);
803  }
804  return 0;
805 }
806 
808  AVPacket *pkt)
809 {
810  AVIStream *ast, *next_ast = next_st->priv_data;
811  int64_t ts, next_ts, ts_min = INT64_MAX;
812  AVStream *st, *sub_st = NULL;
813  int i;
814 
815  next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
817 
818  for (i=0; i<s->nb_streams; i++) {
819  st = s->streams[i];
820  ast = st->priv_data;
821  if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
823  if (ts <= next_ts && ts < ts_min) {
824  ts_min = ts;
825  sub_st = st;
826  }
827  }
828  }
829 
830  if (sub_st) {
831  ast = sub_st->priv_data;
832  *pkt = ast->sub_pkt;
833  pkt->stream_index = sub_st->index;
834  if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
835  ast->sub_pkt.data = NULL;
836  }
837  return sub_st;
838 }
839 
840 static int get_stream_idx(int *d){
841  if( d[0] >= '0' && d[0] <= '9'
842  && d[1] >= '0' && d[1] <= '9'){
843  return (d[0] - '0') * 10 + (d[1] - '0');
844  }else{
845  return 100; //invalid stream ID
846  }
847 }
848 
849 static int avi_sync(AVFormatContext *s, int exit_early)
850 {
851  AVIContext *avi = s->priv_data;
852  AVIOContext *pb = s->pb;
853  int n;
854  unsigned int d[8];
855  unsigned int size;
856  int64_t i, sync;
857 
858 start_sync:
859  memset(d, -1, sizeof(d));
860  for(i=sync=avio_tell(pb); !pb->eof_reached; i++) {
861  int j;
862 
863  for(j=0; j<7; j++)
864  d[j]= d[j+1];
865  d[7]= avio_r8(pb);
866 
867  size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
868 
869  n= get_stream_idx(d+2);
870  av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
871  d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
872  if(i + (uint64_t)size > avi->fsize || d[0] > 127)
873  continue;
874 
875  //parse ix##
876  if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
877  //parse JUNK
878  ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
879  ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
880  avio_skip(pb, size);
881  goto start_sync;
882  }
883 
884  //parse stray LIST
885  if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
886  avio_skip(pb, 4);
887  goto start_sync;
888  }
889 
890  n = avi->dv_demux ? 0 : get_stream_idx(d);
891 
892  if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
893  continue;
894 
895  //detect ##ix chunk and skip
896  if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
897  avio_skip(pb, size);
898  goto start_sync;
899  }
900 
901  //parse ##dc/##wb
902  if(n < s->nb_streams){
903  AVStream *st;
904  AVIStream *ast;
905  st = s->streams[n];
906  ast = st->priv_data;
907 
908  if(s->nb_streams>=2){
909  AVStream *st1 = s->streams[1];
910  AVIStream *ast1= st1->priv_data;
911  //workaround for broken small-file-bug402.avi
912  if( d[2] == 'w' && d[3] == 'b'
913  && n==0
914  && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
916  && ast->prefix == 'd'*256+'c'
917  && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
918  ){
919  n=1;
920  st = st1;
921  ast = ast1;
922  av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
923  }
924  }
925 
926 
927  if (!avi->dv_demux &&
928  ((st->discard >= AVDISCARD_DEFAULT && size==0) /* ||
929  //FIXME needs a little reordering
930  (st->discard >= AVDISCARD_NONKEY &&
931  !(pkt->flags & AV_PKT_FLAG_KEY)) */
932  || st->discard >= AVDISCARD_ALL)) {
933  if (!exit_early) {
934  ast->frame_offset += get_duration(ast, size);
935  }
936  avio_skip(pb, size);
937  goto start_sync;
938  }
939 
940  if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
941  int k = avio_r8(pb);
942  int last = (k + avio_r8(pb) - 1) & 0xFF;
943 
944  avio_rl16(pb); //flags
945 
946  for (; k <= last; k++)
947  ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
948  ast->has_pal= 1;
949  goto start_sync;
950  } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
951  d[2]*256+d[3] == ast->prefix /*||
952  (d[2] == 'd' && d[3] == 'c') ||
953  (d[2] == 'w' && d[3] == 'b')*/) {
954 
955  if (exit_early)
956  return 0;
957  if(d[2]*256+d[3] == ast->prefix)
958  ast->prefix_count++;
959  else{
960  ast->prefix= d[2]*256+d[3];
961  ast->prefix_count= 0;
962  }
963 
964  avi->stream_index= n;
965  ast->packet_size= size + 8;
966  ast->remaining= size;
967 
968  if(size || !ast->sample_size){
969  uint64_t pos= avio_tell(pb) - 8;
970  if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
971  av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
972  }
973  }
974  return 0;
975  }
976  }
977  }
978 
979  return AVERROR_EOF;
980 }
981 
983 {
984  AVIContext *avi = s->priv_data;
985  AVIOContext *pb = s->pb;
986  int err;
987  void* dstr;
988 
989  if (CONFIG_DV_DEMUXER && avi->dv_demux) {
990  int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
991  if (size >= 0)
992  return size;
993  else
994  goto resync;
995  }
996 
997  if(avi->non_interleaved){
998  int best_stream_index = 0;
999  AVStream *best_st= NULL;
1000  AVIStream *best_ast;
1001  int64_t best_ts= INT64_MAX;
1002  int i;
1003 
1004  for(i=0; i<s->nb_streams; i++){
1005  AVStream *st = s->streams[i];
1006  AVIStream *ast = st->priv_data;
1007  int64_t ts= ast->frame_offset;
1008  int64_t last_ts;
1009 
1010  if(!st->nb_index_entries)
1011  continue;
1012 
1013  last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
1014  if(!ast->remaining && ts > last_ts)
1015  continue;
1016 
1017  ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
1018 
1019  av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
1020  st->time_base.num, st->time_base.den, ast->frame_offset);
1021  if(ts < best_ts){
1022  best_ts= ts;
1023  best_st= st;
1024  best_stream_index= i;
1025  }
1026  }
1027  if(!best_st)
1028  return -1;
1029 
1030  best_ast = best_st->priv_data;
1031  best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
1032  if(best_ast->remaining)
1034  else{
1035  i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
1036  if(i>=0)
1037  best_ast->frame_offset= best_st->index_entries[i].timestamp;
1038  }
1039 
1040  if(i>=0){
1041  int64_t pos= best_st->index_entries[i].pos;
1042  pos += best_ast->packet_size - best_ast->remaining;
1043  avio_seek(s->pb, pos + 8, SEEK_SET);
1044 
1045  assert(best_ast->remaining <= best_ast->packet_size);
1046 
1047  avi->stream_index= best_stream_index;
1048  if(!best_ast->remaining)
1049  best_ast->packet_size=
1050  best_ast->remaining= best_st->index_entries[i].size;
1051  }
1052  }
1053 
1054 resync:
1055  if(avi->stream_index >= 0){
1056  AVStream *st= s->streams[ avi->stream_index ];
1057  AVIStream *ast= st->priv_data;
1058  int size, err;
1059 
1060  if(get_subtitle_pkt(s, st, pkt))
1061  return 0;
1062 
1063  if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
1064  size= INT_MAX;
1065  else if(ast->sample_size < 32)
1066  // arbitrary multiplier to avoid tiny packets for raw PCM data
1067  size= 1024*ast->sample_size;
1068  else
1069  size= ast->sample_size;
1070 
1071  if(size > ast->remaining)
1072  size= ast->remaining;
1073  avi->last_pkt_pos= avio_tell(pb);
1074  err= av_get_packet(pb, pkt, size);
1075  if(err<0)
1076  return err;
1077 
1078  if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
1079  uint8_t *pal;
1081  if(!pal){
1082  av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
1083  }else{
1084  memcpy(pal, ast->pal, AVPALETTE_SIZE);
1085  ast->has_pal = 0;
1086  }
1087  }
1088 
1089  if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1090  dstr = pkt->destruct;
1091  size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
1092  pkt->data, pkt->size);
1093  pkt->destruct = dstr;
1094  pkt->flags |= AV_PKT_FLAG_KEY;
1095  if (size < 0)
1096  av_free_packet(pkt);
1097  } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
1098  && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
1099  ast->frame_offset++;
1100  avi->stream_index = -1;
1101  ast->remaining = 0;
1102  goto resync;
1103  } else {
1104  /* XXX: How to handle B-frames in AVI? */
1105  pkt->dts = ast->frame_offset;
1106 // pkt->dts += ast->start;
1107  if(ast->sample_size)
1108  pkt->dts /= ast->sample_size;
1109  av_dlog(s, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n",
1110  pkt->dts, ast->frame_offset, ast->scale, ast->rate,
1111  ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
1112  pkt->stream_index = avi->stream_index;
1113 
1114  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1115  AVIndexEntry *e;
1116  int index;
1117  assert(st->index_entries);
1118 
1119  index= av_index_search_timestamp(st, ast->frame_offset, 0);
1120  e= &st->index_entries[index];
1121 
1122  if(index >= 0 && e->timestamp == ast->frame_offset){
1123  if (e->flags & AVINDEX_KEYFRAME)
1124  pkt->flags |= AV_PKT_FLAG_KEY;
1125  }
1126  } else {
1127  pkt->flags |= AV_PKT_FLAG_KEY;
1128  }
1129  ast->frame_offset += get_duration(ast, pkt->size);
1130  }
1131  ast->remaining -= err;
1132  if(!ast->remaining){
1133  avi->stream_index= -1;
1134  ast->packet_size= 0;
1135  }
1136 
1137  return 0;
1138  }
1139 
1140  if ((err = avi_sync(s, 0)) < 0)
1141  return err;
1142  goto resync;
1143 }
1144 
1145 /* XXX: We make the implicit supposition that the positions are sorted
1146  for each stream. */
1147 static int avi_read_idx1(AVFormatContext *s, int size)
1148 {
1149  AVIContext *avi = s->priv_data;
1150  AVIOContext *pb = s->pb;
1151  int nb_index_entries, i;
1152  AVStream *st;
1153  AVIStream *ast;
1154  unsigned int index, tag, flags, pos, len, first_packet = 1;
1155  unsigned last_pos= -1;
1156  int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
1157 
1158  nb_index_entries = size / 16;
1159  if (nb_index_entries <= 0)
1160  return -1;
1161 
1162  idx1_pos = avio_tell(pb);
1163  avio_seek(pb, avi->movi_list+4, SEEK_SET);
1164  if (avi_sync(s, 1) == 0) {
1165  first_packet_pos = avio_tell(pb) - 8;
1166  }
1167  avi->stream_index = -1;
1168  avio_seek(pb, idx1_pos, SEEK_SET);
1169 
1170  /* Read the entries and sort them in each stream component. */
1171  for(i = 0; i < nb_index_entries; i++) {
1172  tag = avio_rl32(pb);
1173  flags = avio_rl32(pb);
1174  pos = avio_rl32(pb);
1175  len = avio_rl32(pb);
1176  av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
1177  i, tag, flags, pos, len);
1178 
1179  index = ((tag & 0xff) - '0') * 10;
1180  index += ((tag >> 8) & 0xff) - '0';
1181  if (index >= s->nb_streams)
1182  continue;
1183  st = s->streams[index];
1184  ast = st->priv_data;
1185 
1186  if(first_packet && first_packet_pos && len) {
1187  data_offset = first_packet_pos - pos;
1188  first_packet = 0;
1189  }
1190  pos += data_offset;
1191 
1192  av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
1193 
1194  if(pb->eof_reached)
1195  return -1;
1196 
1197  if(last_pos == pos)
1198  avi->non_interleaved= 1;
1199  else if(len || !ast->sample_size)
1200  av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
1201  ast->cum_len += get_duration(ast, len);
1202  last_pos= pos;
1203  }
1204  return 0;
1205 }
1206 
1208  int i;
1209  int64_t last_start=0;
1210  int64_t first_end= INT64_MAX;
1211  int64_t oldpos= avio_tell(s->pb);
1212 
1213  for(i=0; i<s->nb_streams; i++){
1214  AVStream *st = s->streams[i];
1215  int n= st->nb_index_entries;
1216  unsigned int size;
1217 
1218  if(n <= 0)
1219  continue;
1220 
1221  if(n >= 2){
1222  int64_t pos= st->index_entries[0].pos;
1223  avio_seek(s->pb, pos + 4, SEEK_SET);
1224  size= avio_rl32(s->pb);
1225  if(pos + size > st->index_entries[1].pos)
1226  last_start= INT64_MAX;
1227  }
1228 
1229  if(st->index_entries[0].pos > last_start)
1230  last_start= st->index_entries[0].pos;
1231  if(st->index_entries[n-1].pos < first_end)
1232  first_end= st->index_entries[n-1].pos;
1233  }
1234  avio_seek(s->pb, oldpos, SEEK_SET);
1235  return last_start > first_end;
1236 }
1237 
1239 {
1240  AVIContext *avi = s->priv_data;
1241  AVIOContext *pb = s->pb;
1242  uint32_t tag, size;
1243  int64_t pos= avio_tell(pb);
1244  int ret = -1;
1245 
1246  if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
1247  goto the_end; // maybe truncated file
1248  av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
1249  for(;;) {
1250  if (pb->eof_reached)
1251  break;
1252  tag = avio_rl32(pb);
1253  size = avio_rl32(pb);
1254  av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
1255  tag & 0xff,
1256  (tag >> 8) & 0xff,
1257  (tag >> 16) & 0xff,
1258  (tag >> 24) & 0xff,
1259  size);
1260 
1261  if (tag == MKTAG('i', 'd', 'x', '1') &&
1262  avi_read_idx1(s, size) >= 0) {
1263  ret = 0;
1264  break;
1265  }
1266 
1267  size += (size & 1);
1268  if (avio_skip(pb, size) < 0)
1269  break; // something is wrong here
1270  }
1271  the_end:
1272  avio_seek(pb, pos, SEEK_SET);
1273  return ret;
1274 }
1275 
1276 static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
1277 {
1278  AVIStream *ast2 = st2->priv_data;
1279  int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
1280  av_free_packet(&ast2->sub_pkt);
1281  if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
1282  avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
1283  ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
1284 }
1285 
1286 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1287 {
1288  AVIContext *avi = s->priv_data;
1289  AVStream *st;
1290  int i, index;
1291  int64_t pos;
1292  AVIStream *ast;
1293 
1294  /* Does not matter which stream is requested dv in avi has the
1295  * stream information in the first video stream.
1296  */
1297  if (avi->dv_demux)
1298  stream_index = 0;
1299 
1300  if (!avi->index_loaded) {
1301  /* we only load the index on demand */
1302  avi_load_index(s);
1303  avi->index_loaded = 1;
1304  }
1305 
1306  st = s->streams[stream_index];
1307  ast= st->priv_data;
1308  index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
1309  if(index<0)
1310  return -1;
1311 
1312  /* find the position */
1313  pos = st->index_entries[index].pos;
1314  timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
1315 
1316  av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
1317  timestamp, index, st->index_entries[index].timestamp);
1318 
1319  if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1320  /* One and only one real stream for DV in AVI, and it has video */
1321  /* offsets. Calling with other stream indexes should have failed */
1322  /* the av_index_search_timestamp call above. */
1323 
1324  /* Feed the DV video stream version of the timestamp to the */
1325  /* DV demux so it can synthesize correct timestamps. */
1326  ff_dv_offset_reset(avi->dv_demux, timestamp);
1327 
1328  avio_seek(s->pb, pos, SEEK_SET);
1329  avi->stream_index= -1;
1330  return 0;
1331  }
1332 
1333  for(i = 0; i < s->nb_streams; i++) {
1334  AVStream *st2 = s->streams[i];
1335  AVIStream *ast2 = st2->priv_data;
1336 
1337  ast2->packet_size=
1338  ast2->remaining= 0;
1339 
1340  if (ast2->sub_ctx) {
1341  seek_subtitle(st, st2, timestamp);
1342  continue;
1343  }
1344 
1345  if (st2->nb_index_entries <= 0)
1346  continue;
1347 
1348 // assert(st2->codec->block_align);
1349  assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1350  index = av_index_search_timestamp(
1351  st2,
1352  av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
1353  flags | AVSEEK_FLAG_BACKWARD);
1354  if(index<0)
1355  index=0;
1356 
1357  if(!avi->non_interleaved){
1358  while(index>0 && st2->index_entries[index].pos > pos)
1359  index--;
1360  while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1361  index++;
1362  }
1363 
1364  av_dlog(s, "%"PRId64" %d %"PRId64"\n",
1365  timestamp, index, st2->index_entries[index].timestamp);
1366  /* extract the current frame number */
1367  ast2->frame_offset = st2->index_entries[index].timestamp;
1368  }
1369 
1370  /* do the seek */
1371  avio_seek(s->pb, pos, SEEK_SET);
1372  avi->stream_index= -1;
1373  return 0;
1374 }
1375 
1377 {
1378  int i;
1379  AVIContext *avi = s->priv_data;
1380 
1381  for(i=0;i<s->nb_streams;i++) {
1382  AVStream *st = s->streams[i];
1383  AVIStream *ast = st->priv_data;
1384  if (ast) {
1385  if (ast->sub_ctx) {
1386  av_freep(&ast->sub_ctx->pb);
1388  }
1389  av_free(ast->sub_buffer);
1390  av_free_packet(&ast->sub_pkt);
1391  }
1392  }
1393 
1394  av_free(avi->dv_demux);
1395 
1396  return 0;
1397 }
1398 
1399 static int avi_probe(AVProbeData *p)
1400 {
1401  int i;
1402 
1403  /* check file header */
1404  for(i=0; avi_headers[i][0]; i++)
1405  if(!memcmp(p->buf , avi_headers[i] , 4) &&
1406  !memcmp(p->buf+8, avi_headers[i]+4, 4))
1407  return AVPROBE_SCORE_MAX;
1408 
1409  return 0;
1410 }
1411 
1413  .name = "avi",
1414  .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1415  .priv_data_size = sizeof(AVIContext),
1416  .read_probe = avi_probe,
1421 };
int ff_read_riff_info(AVFormatContext *s, int64_t size)
codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it ...
Definition: avcodec.h:428
static AVStream * get_subtitle_pkt(AVFormatContext *s, AVStream *next_st, AVPacket *pkt)
Definition: avidec.c:807
full parsing and interpolation of timestamps for frames not starting on a packet boundary ...
Definition: avformat.h:578
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:61
unsigned int stream_codec_tag
fourcc from the AVI stream header (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + ...
Definition: avcodec.h:1373
Bytestream IO Context.
Definition: avio.h:68
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:241
uint32_t pal[256]
Definition: avidec.c:50
int size
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:153
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1393
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2126
AVFormatContext * sub_ctx
Definition: avidec.c:54
unsigned char * buf_ptr
Current position in the buffer.
Definition: avio.h:84
unsigned char * buf_end
End of the data, may be less than buffer+buffer_size if the read function returned less data than req...
Definition: avio.h:85
#define MAX_ODML_DEPTH
Definition: avidec.c:71
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:476
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3283
int64_t pos
Definition: avformat.h:583
int64_t last_pkt_pos
Definition: avidec.c:64
uint32_t rate
Definition: avidec.c:43
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:697
int dshow_block_align
block align variable used to emulate bugs in the MS dshow demuxer
Definition: avidec.c:52
int num
numerator
Definition: rational.h:44
int index
stream index in AVFormatContext
Definition: avformat.h:623
int size
Definition: avcodec.h:916
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:186
static int sync(AVFormatContext *s, uint8_t *header)
Read input until we find the next ident.
Definition: lxfdec.c:84
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:786
int is_odml
Definition: avidec.c:66
enum AVMediaType codec_type
Definition: rtp.c:39
int64_t movi_end
Definition: avidec.c:61
uint32_t scale
Definition: avidec.c:42
#define AV_RL16
Definition: intreadwrite.h:42
static int get_duration(AVIStream *ast, int len)
Definition: avidec.c:99
void * priv_data
Definition: avformat.h:653
#define AVIIF_INDEX
Definition: avi.h:36
av_dlog(ac->avr,"%d samples - audio_convert: %s to %s (%s)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic?ac->func_descr_generic:ac->func_descr)
discard all
Definition: avcodec.h:536
struct AVStream::@75 * info
int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a UTF-16 string from pb and convert it to UTF-8.
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:2141
static int64_t duration
Definition: avplay.c:249
static const AVMetadataConv avi_metadata_conv[]
Definition: avidec.c:83
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:151
Format I/O context.
Definition: avformat.h:828
Public dictionary API.
int stream_index
Definition: avidec.c:68
uint8_t
Opaque data information usually continuous.
Definition: avutil.h:181
static int avi_read_close(AVFormatContext *s)
Definition: avidec.c:1376
int64_t riff_end
Definition: avidec.c:60
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:577
enum AVStreamParseType need_parsing
Definition: avformat.h:775
int id
Format-specific stream ID.
Definition: avformat.h:629
#define AV_WL32(p, d)
Definition: intreadwrite.h:255
int64_t movi_list
Definition: avidec.c:63
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1454
const char * name
AVStream ** streams
Definition: avformat.h:876
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:97
static void clean_index(AVFormatContext *s)
Definition: avidec.c:223
DVDemuxContext * avpriv_dv_init_demux(AVFormatContext *s)
Definition: dv.c:295
uint8_t * data
Definition: avcodec.h:915
static int flags
Definition: log.c:42
uint32_t tag
Definition: movenc.c:802
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:218
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:219
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2704
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t *buf, int buf_size)
Definition: dv.c:335
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:446
int packet_size
Definition: avidec.c:40
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:122
#define AVIF_MUSTUSEINDEX
Definition: avi.h:25
AVIOContext * avio_alloc_context(unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Allocate and initialize an AVIOContext for buffered I/O.
Definition: aviobuf.c:107
AVDictionary * metadata
Definition: avformat.h:972
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:139
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1435
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:546
int remaining
Definition: avidec.c:39
int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
int64_t timestamp
Definition: avformat.h:584
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
AVRational av_div_q(AVRational b, AVRational c)
Divide one rational by another.
Definition: rational.c:88
static int read_braindead_odml_indx(AVFormatContext *s, int frame_num)
Definition: avidec.c:132
static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
Definition: avidec.c:249
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2736
AVInputFormat * av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
Guess the file format.
Definition: utils.c:258
Only parse headers, do not repack.
Definition: avformat.h:577
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:437
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:641
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:340
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:875
int prefix_count
Definition: avidec.c:49
int non_interleaved
Definition: avidec.c:67
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:110
void ff_dv_offset_reset(DVDemuxContext *c, int64_t frame_offset)
Definition: dv.c:402
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:31
int av_strcasecmp(const char *a, const char *b)
Definition: avstring.c:140
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:54
int64_t cum_len
Definition: avidec.c:46
int width
picture width / height.
Definition: avcodec.h:1508
static int avi_read_header(AVFormatContext *s)
Definition: avidec.c:328
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:210
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
static const char months[12][4]
Definition: avidec.c:270
static char buffer[20]
Definition: seek-test.c:31
static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
Definition: avidec.c:1276
#define AV_RL32
Definition: intreadwrite.h:146
AVDictionary * metadata
Definition: avformat.h:699
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
Read a transport packet from a media file.
Definition: utils.c:594
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:536
Stream structure.
Definition: avformat.h:622
static const char avi_headers[][8]
Definition: avidec.c:74
static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: avidec.c:982
int prefix
normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
Definition: avidec.c:48
static int read_gab2_sub(AVStream *st, AVPacket *pkt)
Definition: avidec.c:757
NULL
Definition: eval.c:52
#define av_bswap32
Definition: bswap.h:33
struct AVIStream AVIStream
enum AVMediaType codec_type
Definition: avcodec.h:1347
enum AVCodecID codec_id
Definition: avcodec.h:1350
AVIOContext * pb
I/O context.
Definition: avformat.h:861
int index_loaded
Definition: avidec.c:65
static int get_stream_idx(int *d)
Definition: avidec.c:840
#define CONFIG_DV_DEMUXER
Definition: config.h:705
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1365
int extradata_size
Definition: avcodec.h:1455
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:63
int nb_index_entries
Definition: avformat.h:788
static int avi_read_idx1(AVFormatContext *s, int size)
Definition: avidec.c:1147
int index
Definition: gxfenc.c:72
rational number numerator/denominator
Definition: rational.h:43
byte swapping routines
discard useless packets like 0 size packets in avi
Definition: avcodec.h:532
static int avi_probe(AVProbeData *p)
Definition: avidec.c:1399
This structure contains the data a format has to probe a file.
Definition: avformat.h:338
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
Definition: utils.c:1740
const AVMetadataConv ff_riff_info_conv[]
Definition: riff.c:349
static int avi_load_index(AVFormatContext *s)
Definition: avidec.c:1238
Definition: vf_drawbox.c:36
AVInputFormat ff_avi_demuxer
Definition: avidec.c:1412
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:684
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:530
Main libavformat public API header.
static void avi_read_nikon(AVFormatContext *s, uint64_t end)
Definition: avidec.c:292
static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
Definition: avidec.c:273
AVPacket sub_pkt
Definition: avidec.c:55
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:116
int64_t start_time
Decoding: pts of the first frame of the stream, in stream time base.
Definition: avformat.h:677
int error_recognition
Error recognition; higher values will detect more errors but may misdetect some more or less valid pa...
Definition: avformat.h:994
static int get_riff(AVFormatContext *s, AVIOContext *pb)
Definition: avidec.c:108
struct AVProbeData AVProbeData
This structure contains the data a format has to probe a file.
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:686
int den
denominator
Definition: rational.h:45
int avpriv_dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
Definition: dv.c:318
int sample_size
Definition: avidec.c:44
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:2713
int eof_reached
true if eof reached
Definition: avio.h:96
int len
int has_pal
Definition: avidec.c:51
static int guess_ni_flag(AVFormatContext *s)
Definition: avidec.c:1207
void * priv_data
Format private data.
Definition: avformat.h:848
#define print_tag(str, tag, size)
Definition: avidec.c:91
int64_t frame_offset
Definition: avidec.c:37
int64_t fsize
Definition: avidec.c:62
int ff_get_bmp_header(AVIOContext *pb, AVStream *st)
Read BITMAPINFOHEADER structure and set AVStream codec width, height and bits_per_encoded_sample fiel...
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:914
static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: avidec.c:1286
int64_t duration
Decoding: duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:893
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:455
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:165
int stream_index
Definition: avcodec.h:917
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:669
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:690
int odml_depth
Definition: avidec.c:70
This structure stores compressed data.
Definition: avcodec.h:898
uint64_t avio_rl64(AVIOContext *s)
Definition: aviobuf.c:554
static int avi_sync(AVFormatContext *s, int exit_early)
Definition: avidec.c:849
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:158
uint8_t * sub_buffer
Definition: avidec.c:56
DVDemuxContext * dv_demux
Definition: avidec.c:69