FFmpeg
utils.c
Go to the documentation of this file.
1 /*
2  * various utility functions for use within FFmpeg
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <stdint.h>
23 
24 #include "config.h"
25 
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/bprint.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/parseutils.h"
34 #include "libavutil/pixfmt.h"
35 #include "libavutil/thread.h"
36 #include "libavutil/time.h"
37 #include "libavutil/timestamp.h"
38 
39 #include "libavcodec/bsf.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/internal.h"
43 #include "libavcodec/raw.h"
44 
45 #include "avformat.h"
46 #include "avio_internal.h"
47 #include "id3v2.h"
48 #include "internal.h"
49 #if CONFIG_NETWORK
50 #include "network.h"
51 #endif
52 #include "url.h"
53 
54 #include "libavutil/ffversion.h"
55 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
56 
58 
59 /**
60  * @file
61  * various utility functions for use within FFmpeg
62  */
63 
64 unsigned avformat_version(void)
65 {
68 }
69 
70 const char *avformat_configuration(void)
71 {
72  return FFMPEG_CONFIGURATION;
73 }
74 
75 const char *avformat_license(void)
76 {
77 #define LICENSE_PREFIX "libavformat license: "
78  return &LICENSE_PREFIX FFMPEG_LICENSE[sizeof(LICENSE_PREFIX) - 1];
79 }
80 
82 {
83  return ff_mutex_lock(&avformat_mutex) ? -1 : 0;
84 }
85 
87 {
88  return ff_mutex_unlock(&avformat_mutex) ? -1 : 0;
89 }
90 
91 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
92 
93 static int is_relative(int64_t ts) {
94  return ts > (RELATIVE_TS_BASE - (1LL<<48));
95 }
96 
97 /**
98  * Wrap a given time stamp, if there is an indication for an overflow
99  *
100  * @param st stream
101  * @param timestamp the time stamp to wrap
102  * @return resulting time stamp
103  */
104 static int64_t wrap_timestamp(const AVStream *st, int64_t timestamp)
105 {
107  st->internal->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
109  timestamp < st->internal->pts_wrap_reference)
110  return timestamp + (1ULL << st->pts_wrap_bits);
112  timestamp >= st->internal->pts_wrap_reference)
113  return timestamp - (1ULL << st->pts_wrap_bits);
114  }
115  return timestamp;
116 }
117 
118 int64_t av_stream_get_end_pts(const AVStream *st)
119 {
120  if (st->internal->priv_pts) {
121  return st->internal->priv_pts->val;
122  } else
123  return AV_NOPTS_VALUE;
124 }
125 
127 {
128  return st->internal->parser;
129 }
130 
132 {
133  st->internal->need_parsing = type;
134 }
135 
137 {
138  int i;
139  s->internal->inject_global_side_data = 1;
140  for (i = 0; i < s->nb_streams; i++) {
141  AVStream *st = s->streams[i];
143  }
144 }
145 
147 {
148  av_assert0(!dst->codec_whitelist &&
149  !dst->format_whitelist &&
150  !dst->protocol_whitelist &&
151  !dst->protocol_blacklist);
152  dst-> codec_whitelist = av_strdup(src->codec_whitelist);
153  dst->format_whitelist = av_strdup(src->format_whitelist);
154  dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
155  dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
156  if ( (src-> codec_whitelist && !dst-> codec_whitelist)
157  || (src-> format_whitelist && !dst-> format_whitelist)
158  || (src->protocol_whitelist && !dst->protocol_whitelist)
159  || (src->protocol_blacklist && !dst->protocol_blacklist)) {
160  av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
161  return AVERROR(ENOMEM);
162  }
163  return 0;
164 }
165 
167 {
168  switch (st->codecpar->codec_type) {
169  case AVMEDIA_TYPE_VIDEO:
170  if (s->video_codec) return s->video_codec;
171  break;
172  case AVMEDIA_TYPE_AUDIO:
173  if (s->audio_codec) return s->audio_codec;
174  break;
176  if (s->subtitle_codec) return s->subtitle_codec;
177  break;
178  }
179 
181 }
182 
184 {
185  const AVCodec *codec;
186 
187 #if CONFIG_H264_DECODER
188  /* Other parts of the code assume this decoder to be used for h264,
189  * so force it if possible. */
190  if (codec_id == AV_CODEC_ID_H264)
191  return avcodec_find_decoder_by_name("h264");
192 #endif
193 
194  codec = find_decoder(s, st, codec_id);
195  if (!codec)
196  return NULL;
197 
199  const AVCodec *probe_codec = NULL;
200  void *iter = NULL;
201  while ((probe_codec = av_codec_iterate(&iter))) {
202  if (probe_codec->id == codec->id &&
205  return probe_codec;
206  }
207  }
208  }
209 
210  return codec;
211 }
212 
213 /* an arbitrarily chosen "sane" max packet size -- 50M */
214 #define SANE_CHUNK_SIZE (50000000)
215 
217 {
218  if (s->maxsize>= 0) {
219  int64_t pos = avio_tell(s);
220  int64_t remaining= s->maxsize - pos;
221  if (remaining < size) {
222  int64_t newsize = avio_size(s);
223  if (!s->maxsize || s->maxsize<newsize)
224  s->maxsize = newsize - !newsize;
225  if (pos > s->maxsize && s->maxsize >= 0)
226  s->maxsize = AVERROR(EIO);
227  if (s->maxsize >= 0)
228  remaining = s->maxsize - pos;
229  }
230 
231  if (s->maxsize >= 0 && remaining < size && size > 1) {
232  av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG,
233  "Truncating packet of size %d to %"PRId64"\n",
234  size, remaining + !remaining);
235  size = remaining + !remaining;
236  }
237  }
238  return size;
239 }
240 
241 /* Read the data in sane-sized chunks and append to pkt.
242  * Return the number of bytes read or an error. */
244 {
245  int orig_size = pkt->size;
246  int ret;
247 
248  do {
249  int prev_size = pkt->size;
250  int read_size;
251 
252  /* When the caller requests a lot of data, limit it to the amount
253  * left in file or SANE_CHUNK_SIZE when it is not known. */
254  read_size = size;
255  if (read_size > SANE_CHUNK_SIZE/10) {
256  read_size = ffio_limit(s, read_size);
257  // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
258  if (s->maxsize < 0)
259  read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
260  }
261 
262  ret = av_grow_packet(pkt, read_size);
263  if (ret < 0)
264  break;
265 
266  ret = avio_read(s, pkt->data + prev_size, read_size);
267  if (ret != read_size) {
268  av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
269  break;
270  }
271 
272  size -= read_size;
273  } while (size > 0);
274  if (size > 0)
276 
277  if (!pkt->size)
279  return pkt->size > orig_size ? pkt->size - orig_size : ret;
280 }
281 
283 {
284 #if FF_API_INIT_PACKET
287  pkt->data = NULL;
288  pkt->size = 0;
290 #else
292 #endif
293  pkt->pos = avio_tell(s);
294 
295  return append_packet_chunked(s, pkt, size);
296 }
297 
299 {
300  if (!pkt->size)
301  return av_get_packet(s, pkt, size);
302  return append_packet_chunked(s, pkt, size);
303 }
304 
305 int av_filename_number_test(const char *filename)
306 {
307  char buf[1024];
308  return filename &&
309  (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
310 }
311 
313  AVProbeData *pd)
314 {
315  static const struct {
316  const char *name;
317  enum AVCodecID id;
318  enum AVMediaType type;
319  } fmt_id_type[] = {
331  { "mjpeg_2000",AV_CODEC_ID_JPEG2000, AVMEDIA_TYPE_VIDEO },
333  { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
334  { "truehd", AV_CODEC_ID_TRUEHD, AVMEDIA_TYPE_AUDIO },
335  { 0 }
336  };
337  int score;
338  const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
339 
340  if (fmt) {
341  int i;
343  "Probe with size=%d, packets=%d detected %s with score=%d\n",
344  pd->buf_size, s->max_probe_packets - st->internal->probe_packets,
345  fmt->name, score);
346  for (i = 0; fmt_id_type[i].name; i++) {
347  if (!strcmp(fmt->name, fmt_id_type[i].name)) {
348  if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
349  st->codecpar->sample_rate)
350  continue;
351  if (st->internal->request_probe > score &&
352  st->codecpar->codec_id != fmt_id_type[i].id)
353  continue;
354  st->codecpar->codec_id = fmt_id_type[i].id;
355  st->codecpar->codec_type = fmt_id_type[i].type;
356  st->internal->need_context_update = 1;
357  return score;
358  }
359  }
360  }
361  return 0;
362 }
363 
364 /************************************************************/
365 /* input media file */
366 
367 /* Open input file and probe the format if necessary. */
368 static int init_input(AVFormatContext *s, const char *filename,
370 {
371  int ret;
372  AVProbeData pd = { filename, NULL, 0 };
373  int score = AVPROBE_SCORE_RETRY;
374 
375  if (s->pb) {
376  s->flags |= AVFMT_FLAG_CUSTOM_IO;
377  if (!s->iformat)
378  return av_probe_input_buffer2(s->pb, &s->iformat, filename,
379  s, 0, s->format_probesize);
380  else if (s->iformat->flags & AVFMT_NOFILE)
381  av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
382  "will be ignored with AVFMT_NOFILE format.\n");
383  return 0;
384  }
385 
386  if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
387  (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
388  return score;
389 
390  if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
391  return ret;
392 
393  if (s->iformat)
394  return 0;
395  return av_probe_input_buffer2(s->pb, &s->iformat, filename,
396  s, 0, s->format_probesize);
397 }
398 
400 {
401  int i, ret;
402  for (i = 0; i < s->nb_streams; i++)
403  if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
404  s->streams[i]->discard < AVDISCARD_ALL) {
405  if (s->streams[i]->attached_pic.size <= 0) {
407  "Attached picture on stream %d has invalid size, "
408  "ignoring\n", i);
409  continue;
410  }
411 
412  ret = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
413  &s->internal->raw_packet_buffer_end,
414  &s->streams[i]->attached_pic,
415  av_packet_ref, 0);
416  if (ret < 0)
417  return ret;
418  }
419  return 0;
420 }
421 
423  AVBufferRef **buf, int size)
424 {
425  AVStream *st = st0;
426  AVPacket *pkt;
427  int ret;
428 
429  if (!st && !(st = avformat_new_stream(s, NULL)))
430  return AVERROR(ENOMEM);
431  pkt = &st->attached_pic;
432  if (buf) {
433  av_assert1(*buf);
435  pkt->buf = *buf;
436  pkt->data = (*buf)->data;
437  pkt->size = (*buf)->size - AV_INPUT_BUFFER_PADDING_SIZE;
438  *buf = NULL;
439  } else {
440  ret = av_get_packet(pb, pkt, size);
441  if (ret < 0)
442  goto fail;
443  }
446 
447  pkt->stream_index = st->index;
449 
450  return 0;
451 fail:
452  if (!st0)
453  ff_free_stream(s, st);
454  return ret;
455 }
456 
458 {
459  int i, ret;
460  for (i = 0; i < s->nb_streams; i++) {
461  AVStream *st = s->streams[i];
462 
463  if (!st->internal->need_context_update)
464  continue;
465 
466  /* close parser, because it depends on the codec */
467  if (st->internal->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
469  st->internal->parser = NULL;
470  }
471 
472  /* update internal codec context, for the parser */
474  if (ret < 0)
475  return ret;
476 
477  st->internal->need_context_update = 0;
478  }
479  return 0;
480 }
481 
482 
483 int avformat_open_input(AVFormatContext **ps, const char *filename,
484  const AVInputFormat *fmt, AVDictionary **options)
485 {
486  AVFormatContext *s = *ps;
487  int ret = 0;
488  AVDictionary *tmp = NULL;
489  ID3v2ExtraMeta *id3v2_extra_meta = NULL;
490 
491  if (!s && !(s = avformat_alloc_context()))
492  return AVERROR(ENOMEM);
493  if (!s->av_class) {
494  av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
495  return AVERROR(EINVAL);
496  }
497  if (fmt)
498  s->iformat = fmt;
499 
500  if (options)
501  av_dict_copy(&tmp, *options, 0);
502 
503  if (s->pb) // must be before any goto fail
504  s->flags |= AVFMT_FLAG_CUSTOM_IO;
505 
506  if ((ret = av_opt_set_dict(s, &tmp)) < 0)
507  goto fail;
508 
509  if (!(s->url = av_strdup(filename ? filename : ""))) {
510  ret = AVERROR(ENOMEM);
511  goto fail;
512  }
513 
514  if ((ret = init_input(s, filename, &tmp)) < 0)
515  goto fail;
516  s->probe_score = ret;
517 
518  if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
519  s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
520  if (!s->protocol_whitelist) {
521  ret = AVERROR(ENOMEM);
522  goto fail;
523  }
524  }
525 
526  if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
527  s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
528  if (!s->protocol_blacklist) {
529  ret = AVERROR(ENOMEM);
530  goto fail;
531  }
532  }
533 
534  if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
535  av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
536  ret = AVERROR(EINVAL);
537  goto fail;
538  }
539 
540  avio_skip(s->pb, s->skip_initial_bytes);
541 
542  /* Check filename in case an image number is expected. */
543  if (s->iformat->flags & AVFMT_NEEDNUMBER) {
544  if (!av_filename_number_test(filename)) {
545  ret = AVERROR(EINVAL);
546  goto fail;
547  }
548  }
549 
550  s->duration = s->start_time = AV_NOPTS_VALUE;
551 
552  /* Allocate private data. */
553  if (s->iformat->priv_data_size > 0) {
554  if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
555  ret = AVERROR(ENOMEM);
556  goto fail;
557  }
558  if (s->iformat->priv_class) {
559  *(const AVClass **) s->priv_data = s->iformat->priv_class;
560  av_opt_set_defaults(s->priv_data);
561  if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
562  goto fail;
563  }
564  }
565 
566  /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
567  if (s->pb)
568  ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
569 
570  if (s->iformat->read_header)
571  if ((ret = s->iformat->read_header(s)) < 0) {
572  if (s->iformat->flags_internal & FF_FMT_INIT_CLEANUP)
573  goto close;
574  goto fail;
575  }
576 
577  if (!s->metadata) {
578  s->metadata = s->internal->id3v2_meta;
579  s->internal->id3v2_meta = NULL;
580  } else if (s->internal->id3v2_meta) {
581  av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
582  av_dict_free(&s->internal->id3v2_meta);
583  }
584 
585  if (id3v2_extra_meta) {
586  if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
587  !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
588  if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
589  goto close;
590  if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
591  goto close;
592  if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
593  goto close;
594  } else
595  av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
596  }
597  ff_id3v2_free_extra_meta(&id3v2_extra_meta);
598 
600  goto close;
601 
602  if (s->pb && !s->internal->data_offset)
603  s->internal->data_offset = avio_tell(s->pb);
604 
605  s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
606 
608 
609  if (options) {
611  *options = tmp;
612  }
613  *ps = s;
614  return 0;
615 
616 close:
617  if (s->iformat->read_close)
618  s->iformat->read_close(s);
619 fail:
620  ff_id3v2_free_extra_meta(&id3v2_extra_meta);
621  av_dict_free(&tmp);
622  if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
623  avio_closep(&s->pb);
625  *ps = NULL;
626  return ret;
627 }
628 
629 /*******************************************************/
630 
632 {
633  switch (st->codecpar->codec_type) {
634  case AVMEDIA_TYPE_VIDEO:
635  if (s->video_codec_id)
636  st->codecpar->codec_id = s->video_codec_id;
637  break;
638  case AVMEDIA_TYPE_AUDIO:
639  if (s->audio_codec_id)
640  st->codecpar->codec_id = s->audio_codec_id;
641  break;
643  if (s->subtitle_codec_id)
644  st->codecpar->codec_id = s->subtitle_codec_id;
645  break;
646  case AVMEDIA_TYPE_DATA:
647  if (s->data_codec_id)
648  st->codecpar->codec_id = s->data_codec_id;
649  break;
650  }
651 }
652 
654 {
655  if (st->internal->request_probe>0) {
656  AVProbeData *pd = &st->internal->probe_data;
657  int end;
658  av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->internal->probe_packets);
659  --st->internal->probe_packets;
660 
661  if (pkt) {
662  uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
663  if (!new_buf) {
665  "Failed to reallocate probe buffer for stream %d\n",
666  st->index);
667  goto no_packet;
668  }
669  pd->buf = new_buf;
670  memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
671  pd->buf_size += pkt->size;
672  memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
673  } else {
674 no_packet:
675  st->internal->probe_packets = 0;
676  if (!pd->buf_size) {
678  "nothing to probe for stream %d\n", st->index);
679  }
680  }
681 
682  end= s->internal->raw_packet_buffer_remaining_size <= 0
683  || st->internal->probe_packets<= 0;
684 
685  if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
686  int score = set_codec_from_probe_data(s, st, pd);
688  || end) {
689  pd->buf_size = 0;
690  av_freep(&pd->buf);
691  st->internal->request_probe = -1;
692  if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
693  av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
694  } else
695  av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
696  }
697  force_codec_ids(s, st);
698  }
699  }
700  return 0;
701 }
702 
703 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
704 {
705  int64_t ref = pkt->dts;
706  int i, pts_wrap_behavior;
707  int64_t pts_wrap_reference;
708  AVProgram *first_program;
709 
710  if (ref == AV_NOPTS_VALUE)
711  ref = pkt->pts;
712  if (st->internal->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
713  return 0;
714  ref &= (1LL << st->pts_wrap_bits)-1;
715 
716  // reference time stamp should be 60 s before first time stamp
717  pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
718  // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
719  pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
720  (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
722 
723  first_program = av_find_program_from_stream(s, NULL, stream_index);
724 
725  if (!first_program) {
726  int default_stream_index = av_find_default_stream_index(s);
727  if (s->streams[default_stream_index]->internal->pts_wrap_reference == AV_NOPTS_VALUE) {
728  for (i = 0; i < s->nb_streams; i++) {
730  continue;
731  s->streams[i]->internal->pts_wrap_reference = pts_wrap_reference;
732  s->streams[i]->internal->pts_wrap_behavior = pts_wrap_behavior;
733  }
734  }
735  else {
736  st->internal->pts_wrap_reference = s->streams[default_stream_index]->internal->pts_wrap_reference;
737  st->internal->pts_wrap_behavior = s->streams[default_stream_index]->internal->pts_wrap_behavior;
738  }
739  }
740  else {
741  AVProgram *program = first_program;
742  while (program) {
743  if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
744  pts_wrap_reference = program->pts_wrap_reference;
745  pts_wrap_behavior = program->pts_wrap_behavior;
746  break;
747  }
748  program = av_find_program_from_stream(s, program, stream_index);
749  }
750 
751  // update every program with differing pts_wrap_reference
752  program = first_program;
753  while (program) {
754  if (program->pts_wrap_reference != pts_wrap_reference) {
755  for (i = 0; i<program->nb_stream_indexes; i++) {
756  s->streams[program->stream_index[i]]->internal->pts_wrap_reference = pts_wrap_reference;
757  s->streams[program->stream_index[i]]->internal->pts_wrap_behavior = pts_wrap_behavior;
758  }
759 
760  program->pts_wrap_reference = pts_wrap_reference;
761  program->pts_wrap_behavior = pts_wrap_behavior;
762  }
763  program = av_find_program_from_stream(s, program, stream_index);
764  }
765  }
766  return 1;
767 }
768 
770 {
771  int err, i;
772  AVStream *st;
773 
774 #if FF_API_INIT_PACKET
776  pkt->data = NULL;
777  pkt->size = 0;
780 #else
782 #endif
783 
784  for (;;) {
785  PacketList *pktl = s->internal->raw_packet_buffer;
786  const AVPacket *pkt1;
787 
788  if (pktl) {
789  st = s->streams[pktl->pkt.stream_index];
790  if (s->internal->raw_packet_buffer_remaining_size <= 0)
791  if ((err = probe_codec(s, st, NULL)) < 0)
792  return err;
793  if (st->internal->request_probe <= 0) {
794  avpriv_packet_list_get(&s->internal->raw_packet_buffer,
795  &s->internal->raw_packet_buffer_end, pkt);
796  s->internal->raw_packet_buffer_remaining_size += pkt->size;
797  return 0;
798  }
799  }
800 
801  err = s->iformat->read_packet(s, pkt);
802  if (err < 0) {
804 
805  /* Some demuxers return FFERROR_REDO when they consume
806  data and discard it (ignored streams, junk, extradata).
807  We must re-call the demuxer to get the real packet. */
808  if (err == FFERROR_REDO)
809  continue;
810  if (!pktl || err == AVERROR(EAGAIN))
811  return err;
812  for (i = 0; i < s->nb_streams; i++) {
813  st = s->streams[i];
814  if (st->internal->probe_packets || st->internal->request_probe > 0)
815  if ((err = probe_codec(s, st, NULL)) < 0)
816  return err;
817  av_assert0(st->internal->request_probe <= 0);
818  }
819  continue;
820  }
821 
823  if (err < 0) {
825  return err;
826  }
827 
828  if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
830  "Packet corrupt (stream = %d, dts = %s)",
832  if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
833  av_log(s, AV_LOG_WARNING, ", dropping it.\n");
835  continue;
836  }
837  av_log(s, AV_LOG_WARNING, ".\n");
838  }
839 
840  av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
841  "Invalid stream index.\n");
842 
843  st = s->streams[pkt->stream_index];
844 
846  // correct first time stamps to negative values
847  if (!is_relative(st->internal->first_dts))
849  if (!is_relative(st->start_time))
850  st->start_time = wrap_timestamp(st, st->start_time);
851  if (!is_relative(st->internal->cur_dts))
853  }
854 
855  pkt->dts = wrap_timestamp(st, pkt->dts);
856  pkt->pts = wrap_timestamp(st, pkt->pts);
857 
858  force_codec_ids(s, st);
859 
860  /* TODO: audio: time filter; video: frame reordering (pts != dts) */
861  if (s->use_wallclock_as_timestamps)
863 
864  if (!pktl && st->internal->request_probe <= 0)
865  return 0;
866 
867  err = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
868  &s->internal->raw_packet_buffer_end,
869  pkt, NULL, 0);
870  if (err < 0) {
872  return err;
873  }
874  pkt1 = &s->internal->raw_packet_buffer_end->pkt;
875  s->internal->raw_packet_buffer_remaining_size -= pkt1->size;
876 
877  if ((err = probe_codec(s, st, pkt1)) < 0)
878  return err;
879  }
880 }
881 
882 
883 /**********************************************************/
884 
886 {
887  switch(avctx->codec_id) {
888  case AV_CODEC_ID_MP1:
889  case AV_CODEC_ID_MP2:
890  case AV_CODEC_ID_MP3:
891  case AV_CODEC_ID_CODEC2:
892  return 1;
893  }
894 
895  return 0;
896 }
897 
898 /**
899  * Return the frame duration in seconds. Return 0 if not available.
900  */
901 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
903 {
904  AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
905  av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
906  int frame_size, sample_rate;
907 
908  *pnum = 0;
909  *pden = 0;
910  switch (st->codecpar->codec_type) {
911  case AVMEDIA_TYPE_VIDEO:
912  if (st->r_frame_rate.num && !pc && s->iformat) {
913  *pnum = st->r_frame_rate.den;
914  *pden = st->r_frame_rate.num;
915  } else if (st->time_base.num * 1000LL > st->time_base.den) {
916  *pnum = st->time_base.num;
917  *pden = st->time_base.den;
918  } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
920  av_reduce(pnum, pden,
921  codec_framerate.den,
922  codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
923  INT_MAX);
924 
925  if (pc && pc->repeat_pict) {
926  av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
927  av_reduce(pnum, pden,
928  (*pnum) * (1LL + pc->repeat_pict),
929  (*pden),
930  INT_MAX);
931  }
932  /* If this codec can be interlaced or progressive then we need
933  * a parser to compute duration of a packet. Thus if we have
934  * no parser in such case leave duration undefined. */
935  if (st->internal->avctx->ticks_per_frame > 1 && !pc)
936  *pnum = *pden = 0;
937  }
938  break;
939  case AVMEDIA_TYPE_AUDIO:
940  if (st->internal->avctx_inited) {
943  } else {
946  }
947  if (frame_size <= 0 || sample_rate <= 0)
948  break;
949  *pnum = frame_size;
950  *pden = sample_rate;
951  break;
952  default:
953  break;
954  }
955 }
956 
958 {
960  if (!d)
961  return 0;
962  if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
963  !(d->props & AV_CODEC_PROP_INTRA_ONLY))
964  return 0;
965  return 1;
966 }
967 
969 {
970  if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
971  if (!st->internal->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
972  return 1;
973 #if CONFIG_H264_DECODER
974  if (st->internal->avctx->has_b_frames &&
976  return 1;
977 #endif
978  if (st->internal->avctx->has_b_frames<3)
979  return st->internal->nb_decoded_frames >= 7;
980  else if (st->internal->avctx->has_b_frames<4)
981  return st->internal->nb_decoded_frames >= 18;
982  else
983  return st->internal->nb_decoded_frames >= 20;
984 }
985 
987 {
988  if (pktl->next)
989  return pktl->next;
990  if (pktl == s->internal->packet_buffer_end)
991  return s->internal->parse_queue;
992  return NULL;
993 }
994 
995 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
996  int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
998 
999  if(!onein_oneout) {
1000  int delay = st->internal->avctx->has_b_frames;
1001  int i;
1002 
1003  if (dts == AV_NOPTS_VALUE) {
1004  int64_t best_score = INT64_MAX;
1005  for (i = 0; i<delay; i++) {
1006  if (st->internal->pts_reorder_error_count[i]) {
1007  int64_t score = st->internal->pts_reorder_error[i] / st->internal->pts_reorder_error_count[i];
1008  if (score < best_score) {
1009  best_score = score;
1010  dts = pts_buffer[i];
1011  }
1012  }
1013  }
1014  } else {
1015  for (i = 0; i<delay; i++) {
1016  if (pts_buffer[i] != AV_NOPTS_VALUE) {
1017  int64_t diff = FFABS(pts_buffer[i] - dts)
1018  + (uint64_t)st->internal->pts_reorder_error[i];
1020  st->internal->pts_reorder_error[i] = diff;
1022  if (st->internal->pts_reorder_error_count[i] > 250) {
1023  st->internal->pts_reorder_error[i] >>= 1;
1024  st->internal->pts_reorder_error_count[i] >>= 1;
1025  }
1026  }
1027  }
1028  }
1029  }
1030 
1031  if (dts == AV_NOPTS_VALUE)
1032  dts = pts_buffer[0];
1033 
1034  return dts;
1035 }
1036 
1037 /**
1038  * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
1039  * of the packets in a window.
1040  */
1041 static void update_dts_from_pts(AVFormatContext *s, int stream_index,
1042  PacketList *pkt_buffer)
1043 {
1044  AVStream *st = s->streams[stream_index];
1045  int delay = st->internal->avctx->has_b_frames;
1046  int i;
1047 
1048  int64_t pts_buffer[MAX_REORDER_DELAY+1];
1049 
1050  for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1051  pts_buffer[i] = AV_NOPTS_VALUE;
1052 
1053  for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
1054  if (pkt_buffer->pkt.stream_index != stream_index)
1055  continue;
1056 
1057  if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1058  pts_buffer[0] = pkt_buffer->pkt.pts;
1059  for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1060  FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1061 
1062  pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
1063  }
1064  }
1065 }
1066 
1067 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1068  int64_t dts, int64_t pts, AVPacket *pkt)
1069 {
1070  AVStream *st = s->streams[stream_index];
1071  PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1072  PacketList *pktl_it;
1073 
1074  uint64_t shift;
1075 
1076  if (st->internal->first_dts != AV_NOPTS_VALUE ||
1077  dts == AV_NOPTS_VALUE ||
1078  st->internal->cur_dts == AV_NOPTS_VALUE ||
1079  st->internal->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1080  dts < INT_MIN + (st->internal->cur_dts - RELATIVE_TS_BASE) ||
1081  is_relative(dts))
1082  return;
1083 
1084  st->internal->first_dts = dts - (st->internal->cur_dts - RELATIVE_TS_BASE);
1085  st->internal->cur_dts = dts;
1086  shift = (uint64_t)st->internal->first_dts - RELATIVE_TS_BASE;
1087 
1088  if (is_relative(pts))
1089  pts += shift;
1090 
1091  for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
1092  if (pktl_it->pkt.stream_index != stream_index)
1093  continue;
1094  if (is_relative(pktl_it->pkt.pts))
1095  pktl_it->pkt.pts += shift;
1096 
1097  if (is_relative(pktl_it->pkt.dts))
1098  pktl_it->pkt.dts += shift;
1099 
1100  if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1101  st->start_time = pktl_it->pkt.pts;
1103  st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1104  }
1105  }
1106 
1108  update_dts_from_pts(s, stream_index, pktl);
1109  }
1110 
1111  if (st->start_time == AV_NOPTS_VALUE) {
1113  st->start_time = pts;
1114  }
1116  st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1117  }
1118 }
1119 
1121  int stream_index, int64_t duration)
1122 {
1123  PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1124  int64_t cur_dts = RELATIVE_TS_BASE;
1125 
1126  if (st->internal->first_dts != AV_NOPTS_VALUE) {
1128  return;
1130  cur_dts = st->internal->first_dts;
1131  for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1132  if (pktl->pkt.stream_index == stream_index) {
1133  if (pktl->pkt.pts != pktl->pkt.dts ||
1134  pktl->pkt.dts != AV_NOPTS_VALUE ||
1135  pktl->pkt.duration)
1136  break;
1137  cur_dts -= duration;
1138  }
1139  }
1140  if (pktl && pktl->pkt.dts != st->internal->first_dts) {
1141  av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1142  av_ts2str(st->internal->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1143  return;
1144  }
1145  if (!pktl) {
1146  av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->internal->first_dts));
1147  return;
1148  }
1149  pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1150  st->internal->first_dts = cur_dts;
1151  } else if (st->internal->cur_dts != RELATIVE_TS_BASE)
1152  return;
1153 
1154  for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1155  if (pktl->pkt.stream_index != stream_index)
1156  continue;
1157  if ((pktl->pkt.pts == pktl->pkt.dts ||
1158  pktl->pkt.pts == AV_NOPTS_VALUE) &&
1159  (pktl->pkt.dts == AV_NOPTS_VALUE ||
1160  pktl->pkt.dts == st->internal->first_dts ||
1161  pktl->pkt.dts == RELATIVE_TS_BASE) &&
1162  !pktl->pkt.duration &&
1163  av_sat_add64(cur_dts, duration) == cur_dts + (uint64_t)duration
1164  ) {
1165  pktl->pkt.dts = cur_dts;
1166  if (!st->internal->avctx->has_b_frames)
1167  pktl->pkt.pts = cur_dts;
1168  pktl->pkt.duration = duration;
1169  } else
1170  break;
1171  cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1172  }
1173  if (!pktl)
1174  st->internal->cur_dts = cur_dts;
1175 }
1176 
1179  int64_t next_dts, int64_t next_pts)
1180 {
1181  int num, den, presentation_delayed, delay, i;
1182  int64_t offset;
1184  int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1186 
1187  if (s->flags & AVFMT_FLAG_NOFILLIN)
1188  return;
1189 
1192  if (st->internal->last_dts_for_order_check <= pkt->dts) {
1193  st->internal->dts_ordered++;
1194  } else {
1196  "DTS %"PRIi64" < %"PRIi64" out of order\n",
1197  pkt->dts,
1199  st->internal->dts_misordered++;
1200  }
1201  if (st->internal->dts_ordered + st->internal->dts_misordered > 250) {
1202  st->internal->dts_ordered >>= 1;
1203  st->internal->dts_misordered >>= 1;
1204  }
1205  }
1206 
1208  if (st->internal->dts_ordered < 8*st->internal->dts_misordered && pkt->dts == pkt->pts)
1209  pkt->dts = AV_NOPTS_VALUE;
1210  }
1211 
1212  if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1213  pkt->dts = AV_NOPTS_VALUE;
1214 
1215  if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1216  && !st->internal->avctx->has_b_frames)
1217  //FIXME Set low_delay = 0 when has_b_frames = 1
1218  st->internal->avctx->has_b_frames = 1;
1219 
1220  /* do we have a video B-frame ? */
1221  delay = st->internal->avctx->has_b_frames;
1222  presentation_delayed = 0;
1223 
1224  /* XXX: need has_b_frame, but cannot get it if the codec is
1225  * not initialized */
1226  if (delay &&
1227  pc && pc->pict_type != AV_PICTURE_TYPE_B)
1228  presentation_delayed = 1;
1229 
1230  if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1231  st->pts_wrap_bits < 63 && pkt->dts > INT64_MIN + (1LL << st->pts_wrap_bits) &&
1232  pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1233  if (is_relative(st->internal->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->internal->cur_dts) {
1234  pkt->dts -= 1LL << st->pts_wrap_bits;
1235  } else
1236  pkt->pts += 1LL << st->pts_wrap_bits;
1237  }
1238 
1239  /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1240  * We take the conservative approach and discard both.
1241  * Note: If this is misbehaving for an H.264 file, then possibly
1242  * presentation_delayed is not set correctly. */
1243  if (delay == 1 && pkt->dts == pkt->pts &&
1244  pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1245  av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1246  if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1247  && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1248  pkt->dts = AV_NOPTS_VALUE;
1249  }
1250 
1252  if (pkt->duration <= 0) {
1253  ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1254  if (den && num) {
1255  duration = (AVRational) {num, den};
1257  num * (int64_t) st->time_base.den,
1258  den * (int64_t) st->time_base.num,
1259  AV_ROUND_DOWN);
1260  }
1261  }
1262 
1263  if (pkt->duration > 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1265 
1266  /* Correct timestamps with byte offset if demuxers only have timestamps
1267  * on packet boundaries */
1268  if (pc && st->internal->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1269  /* this will estimate bitrate based on this frame's duration and size */
1271  if (pkt->pts != AV_NOPTS_VALUE)
1272  pkt->pts += offset;
1273  if (pkt->dts != AV_NOPTS_VALUE)
1274  pkt->dts += offset;
1275  }
1276 
1277  /* This may be redundant, but it should not hurt. */
1278  if (pkt->dts != AV_NOPTS_VALUE &&
1279  pkt->pts != AV_NOPTS_VALUE &&
1280  pkt->pts > pkt->dts)
1281  presentation_delayed = 1;
1282 
1283  if (s->debug & FF_FDEBUG_TS)
1285  "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1286  presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->internal->cur_dts),
1287  pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1288 
1289  /* Interpolate PTS and DTS if they are not present. We skip H264
1290  * currently because delay and has_b_frames are not reliably set. */
1291  if ((delay == 0 || (delay == 1 && pc)) &&
1292  onein_oneout) {
1293  if (presentation_delayed) {
1294  /* DTS = decompression timestamp */
1295  /* PTS = presentation timestamp */
1296  if (pkt->dts == AV_NOPTS_VALUE)
1297  pkt->dts = st->internal->last_IP_pts;
1299  if (pkt->dts == AV_NOPTS_VALUE)
1300  pkt->dts = st->internal->cur_dts;
1301 
1302  /* This is tricky: the dts must be incremented by the duration
1303  * of the frame we are displaying, i.e. the last I- or P-frame. */
1304  if (st->internal->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1306  if (pkt->dts != AV_NOPTS_VALUE)
1308  if (pkt->dts != AV_NOPTS_VALUE &&
1309  pkt->pts == AV_NOPTS_VALUE &&
1310  st->internal->last_IP_duration > 0 &&
1311  ((uint64_t)st->internal->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1312  next_dts != next_pts &&
1313  next_pts != AV_NOPTS_VALUE)
1314  pkt->pts = next_dts;
1315 
1316  if ((uint64_t)pkt->duration <= INT32_MAX)
1318  st->internal->last_IP_pts = pkt->pts;
1319  /* Cannot compute PTS if not present (we can compute it only
1320  * by knowing the future. */
1321  } else if (pkt->pts != AV_NOPTS_VALUE ||
1322  pkt->dts != AV_NOPTS_VALUE ||
1323  pkt->duration > 0 ) {
1324 
1325  /* presentation is not delayed : PTS and DTS are the same */
1326  if (pkt->pts == AV_NOPTS_VALUE)
1327  pkt->pts = pkt->dts;
1329  pkt->pts, pkt);
1330  if (pkt->pts == AV_NOPTS_VALUE)
1331  pkt->pts = st->internal->cur_dts;
1332  pkt->dts = pkt->pts;
1333  if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1335  }
1336  }
1337 
1338  if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1339  st->internal->pts_buffer[0] = pkt->pts;
1340  for (i = 0; i<delay && st->internal->pts_buffer[i] > st->internal->pts_buffer[i + 1]; i++)
1341  FFSWAP(int64_t, st->internal->pts_buffer[i], st->internal->pts_buffer[i + 1]);
1342 
1345  }
1346  // We skipped it above so we try here.
1347  if (!onein_oneout)
1348  // This should happen on the first packet
1350  if (pkt->dts > st->internal->cur_dts)
1351  st->internal->cur_dts = pkt->dts;
1352 
1353  if (s->debug & FF_FDEBUG_TS)
1354  av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1355  presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->internal->cur_dts), st->index, st->id);
1356 
1357  /* update flags */
1360 }
1361 
1362 /**
1363  * Parse a packet, add all split parts to parse_queue.
1364  *
1365  * @param pkt Packet to parse; must not be NULL.
1366  * @param flush Indicates whether to flush. If set, pkt must be blank.
1367  */
1369  int stream_index, int flush)
1370 {
1371  AVPacket *out_pkt = s->internal->parse_pkt;
1372  AVStream *st = s->streams[stream_index];
1373  uint8_t *data = pkt->data;
1374  int size = pkt->size;
1375  int ret = 0, got_output = flush;
1376 
1378  // preserve 0-size sync packets
1380  }
1381 
1382  while (size > 0 || (flush && got_output)) {
1383  int len;
1384  int64_t next_pts = pkt->pts;
1385  int64_t next_dts = pkt->dts;
1386 
1388  &out_pkt->data, &out_pkt->size, data, size,
1389  pkt->pts, pkt->dts, pkt->pos);
1390 
1391  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1392  pkt->pos = -1;
1393  /* increment read pointer */
1394  av_assert1(data || !len);
1395  data = len ? data + len : data;
1396  size -= len;
1397 
1398  got_output = !!out_pkt->size;
1399 
1400  if (!out_pkt->size)
1401  continue;
1402 
1403  if (pkt->buf && out_pkt->data == pkt->data) {
1404  /* reference pkt->buf only when out_pkt->data is guaranteed to point
1405  * to data in it and not in the parser's internal buffer. */
1406  /* XXX: Ensure this is the case with all parsers when st->internal->parser->flags
1407  * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1408  out_pkt->buf = av_buffer_ref(pkt->buf);
1409  if (!out_pkt->buf) {
1410  ret = AVERROR(ENOMEM);
1411  goto fail;
1412  }
1413  } else {
1414  ret = av_packet_make_refcounted(out_pkt);
1415  if (ret < 0)
1416  goto fail;
1417  }
1418 
1419  if (pkt->side_data) {
1420  out_pkt->side_data = pkt->side_data;
1421  out_pkt->side_data_elems = pkt->side_data_elems;
1422  pkt->side_data = NULL;
1423  pkt->side_data_elems = 0;
1424  }
1425 
1426  /* set the duration */
1429  if (st->internal->avctx->sample_rate > 0) {
1430  out_pkt->duration =
1432  (AVRational) { 1, st->internal->avctx->sample_rate },
1433  st->time_base,
1434  AV_ROUND_DOWN);
1435  }
1436  }
1437 
1438  out_pkt->stream_index = st->index;
1439  out_pkt->pts = st->internal->parser->pts;
1440  out_pkt->dts = st->internal->parser->dts;
1441  out_pkt->pos = st->internal->parser->pos;
1442  out_pkt->flags |= pkt->flags & AV_PKT_FLAG_DISCARD;
1443 
1445  out_pkt->pos = st->internal->parser->frame_offset;
1446 
1447  if (st->internal->parser->key_frame == 1 ||
1448  (st->internal->parser->key_frame == -1 &&
1450  out_pkt->flags |= AV_PKT_FLAG_KEY;
1451 
1453  out_pkt->flags |= AV_PKT_FLAG_KEY;
1454 
1455  compute_pkt_fields(s, st, st->internal->parser, out_pkt, next_dts, next_pts);
1456 
1457  ret = avpriv_packet_list_put(&s->internal->parse_queue,
1458  &s->internal->parse_queue_end,
1459  out_pkt, NULL, 0);
1460  if (ret < 0)
1461  goto fail;
1462  }
1463 
1464  /* end of the stream => close and free the parser */
1465  if (flush) {
1467  st->internal->parser = NULL;
1468  }
1469 
1470 fail:
1471  if (ret < 0)
1472  av_packet_unref(out_pkt);
1474  return ret;
1475 }
1476 
1477 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1478 {
1479  return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1480 }
1481 
1483 {
1484  int ret, i, got_packet = 0;
1485  AVDictionary *metadata = NULL;
1486 
1487  while (!got_packet && !s->internal->parse_queue) {
1488  AVStream *st;
1489 
1490  /* read next packet */
1491  ret = ff_read_packet(s, pkt);
1492  if (ret < 0) {
1493  if (ret == AVERROR(EAGAIN))
1494  return ret;
1495  /* flush the parsers */
1496  for (i = 0; i < s->nb_streams; i++) {
1497  st = s->streams[i];
1498  if (st->internal->parser && st->internal->need_parsing)
1499  parse_packet(s, pkt, st->index, 1);
1500  }
1501  /* all remaining packets are now in parse_queue =>
1502  * really terminate parsing */
1503  break;
1504  }
1505  ret = 0;
1506  st = s->streams[pkt->stream_index];
1507 
1509 
1510  /* update context if required */
1511  if (st->internal->need_context_update) {
1512  if (avcodec_is_open(st->internal->avctx)) {
1513  av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1515  st->internal->info->found_decoder = 0;
1516  }
1517 
1518  /* close parser, because it depends on the codec */
1519  if (st->internal->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
1521  st->internal->parser = NULL;
1522  }
1523 
1525  if (ret < 0) {
1527  return ret;
1528  }
1529 
1530  st->internal->need_context_update = 0;
1531  }
1532 
1533  if (pkt->pts != AV_NOPTS_VALUE &&
1534  pkt->dts != AV_NOPTS_VALUE &&
1535  pkt->pts < pkt->dts) {
1537  "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1538  pkt->stream_index,
1539  av_ts2str(pkt->pts),
1540  av_ts2str(pkt->dts),
1541  pkt->size);
1542  }
1543  if (s->debug & FF_FDEBUG_TS)
1545  "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1546  pkt->stream_index,
1547  av_ts2str(pkt->pts),
1548  av_ts2str(pkt->dts),
1549  pkt->size, pkt->duration, pkt->flags);
1550 
1551  if (st->internal->need_parsing && !st->internal->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1553  if (!st->internal->parser) {
1554  av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1555  "%s, packets or times may be invalid.\n",
1557  /* no parser available: just output the raw packets */
1559  } else if (st->internal->need_parsing == AVSTREAM_PARSE_HEADERS)
1565  }
1566 
1567  if (!st->internal->need_parsing || !st->internal->parser) {
1568  /* no parsing needed: we just output the packet as is */
1570  if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1572  ff_reduce_index(s, st->index);
1573  av_add_index_entry(st, pkt->pos, pkt->dts,
1574  0, 0, AVINDEX_KEYFRAME);
1575  }
1576  got_packet = 1;
1577  } else if (st->discard < AVDISCARD_ALL) {
1578  if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1579  return ret;
1581  st->codecpar->bit_rate = st->internal->avctx->bit_rate;
1582  st->codecpar->channels = st->internal->avctx->channels;
1584  st->codecpar->codec_id = st->internal->avctx->codec_id;
1585  } else {
1586  /* free packet */
1588  }
1589  if (pkt->flags & AV_PKT_FLAG_KEY)
1590  st->internal->skip_to_keyframe = 0;
1591  if (st->internal->skip_to_keyframe) {
1593  got_packet = 0;
1594  }
1595  }
1596 
1597  if (!got_packet && s->internal->parse_queue)
1598  ret = avpriv_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1599 
1600  if (ret >= 0) {
1601  AVStream *st = s->streams[pkt->stream_index];
1602  int discard_padding = 0;
1604  int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1605  int64_t sample = ts_to_samples(st, pts);
1606  int duration = ts_to_samples(st, pkt->duration);
1607  int64_t end_sample = sample + duration;
1608  if (duration > 0 && end_sample >= st->internal->first_discard_sample &&
1609  sample < st->internal->last_discard_sample)
1610  discard_padding = FFMIN(end_sample - st->internal->first_discard_sample, duration);
1611  }
1612  if (st->internal->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1614  if (st->internal->skip_samples || discard_padding) {
1616  if (p) {
1617  AV_WL32(p, st->internal->skip_samples);
1618  AV_WL32(p + 4, discard_padding);
1619  av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->internal->skip_samples, discard_padding);
1620  }
1621  st->internal->skip_samples = 0;
1622  }
1623 
1624  if (st->internal->inject_global_side_data) {
1625  for (i = 0; i < st->nb_side_data; i++) {
1626  AVPacketSideData *src_sd = &st->side_data[i];
1627  uint8_t *dst_data;
1628 
1629  if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1630  continue;
1631 
1632  dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1633  if (!dst_data) {
1634  av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1635  continue;
1636  }
1637 
1638  memcpy(dst_data, src_sd->data, src_sd->size);
1639  }
1641  }
1642  }
1643 
1644  av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1645  if (metadata) {
1646  s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1647  av_dict_copy(&s->metadata, metadata, 0);
1648  av_dict_free(&metadata);
1650  }
1651 
1652  if (s->debug & FF_FDEBUG_TS)
1654  "read_frame_internal stream=%d, pts=%s, dts=%s, "
1655  "size=%d, duration=%"PRId64", flags=%d\n",
1656  pkt->stream_index,
1657  av_ts2str(pkt->pts),
1658  av_ts2str(pkt->dts),
1659  pkt->size, pkt->duration, pkt->flags);
1660 
1661  /* A demuxer might have returned EOF because of an IO error, let's
1662  * propagate this back to the user. */
1663  if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1664  ret = s->pb->error;
1665 
1666  return ret;
1667 }
1668 
1670 {
1671  const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1672  int eof = 0;
1673  int ret;
1674  AVStream *st;
1675 
1676  if (!genpts) {
1677  ret = s->internal->packet_buffer
1678  ? avpriv_packet_list_get(&s->internal->packet_buffer,
1679  &s->internal->packet_buffer_end, pkt)
1681  if (ret < 0)
1682  return ret;
1683  goto return_packet;
1684  }
1685 
1686  for (;;) {
1687  PacketList *pktl = s->internal->packet_buffer;
1688 
1689  if (pktl) {
1690  AVPacket *next_pkt = &pktl->pkt;
1691 
1692  if (next_pkt->dts != AV_NOPTS_VALUE) {
1693  int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1694  // last dts seen for this stream. if any of packets following
1695  // current one had no dts, we will set this to AV_NOPTS_VALUE.
1696  int64_t last_dts = next_pkt->dts;
1697  av_assert2(wrap_bits <= 64);
1698  while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1699  if (pktl->pkt.stream_index == next_pkt->stream_index &&
1700  av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1701  if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1702  // not B-frame
1703  next_pkt->pts = pktl->pkt.dts;
1704  }
1705  if (last_dts != AV_NOPTS_VALUE) {
1706  // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1707  last_dts = pktl->pkt.dts;
1708  }
1709  }
1710  pktl = pktl->next;
1711  }
1712  if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1713  // Fixing the last reference frame had none pts issue (For MXF etc).
1714  // We only do this when
1715  // 1. eof.
1716  // 2. we are not able to resolve a pts value for current packet.
1717  // 3. the packets for this stream at the end of the files had valid dts.
1718  next_pkt->pts = last_dts + next_pkt->duration;
1719  }
1720  pktl = s->internal->packet_buffer;
1721  }
1722 
1723  /* read packet from packet buffer, if there is data */
1724  st = s->streams[next_pkt->stream_index];
1725  if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1726  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1727  ret = avpriv_packet_list_get(&s->internal->packet_buffer,
1728  &s->internal->packet_buffer_end, pkt);
1729  goto return_packet;
1730  }
1731  }
1732 
1734  if (ret < 0) {
1735  if (pktl && ret != AVERROR(EAGAIN)) {
1736  eof = 1;
1737  continue;
1738  } else
1739  return ret;
1740  }
1741 
1742  ret = avpriv_packet_list_put(&s->internal->packet_buffer,
1743  &s->internal->packet_buffer_end,
1744  pkt, NULL, 0);
1745  if (ret < 0) {
1747  return ret;
1748  }
1749  }
1750 
1751 return_packet:
1752 
1753  st = s->streams[pkt->stream_index];
1754  if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1755  ff_reduce_index(s, st->index);
1757  }
1758 
1759  if (is_relative(pkt->dts))
1760  pkt->dts -= RELATIVE_TS_BASE;
1761  if (is_relative(pkt->pts))
1762  pkt->pts -= RELATIVE_TS_BASE;
1763 
1764  return ret;
1765 }
1766 
1767 /* XXX: suppress the packet queue */
1769 {
1770  if (!s->internal)
1771  return;
1772  avpriv_packet_list_free(&s->internal->parse_queue, &s->internal->parse_queue_end);
1773  avpriv_packet_list_free(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1774  avpriv_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1775 
1776  s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1777 }
1778 
1779 /*******************************************************/
1780 /* seek support */
1781 
1783 {
1784  int i;
1785  AVStream *st;
1786  int best_stream = 0;
1787  int best_score = INT_MIN;
1788 
1789  if (s->nb_streams <= 0)
1790  return -1;
1791  for (i = 0; i < s->nb_streams; i++) {
1792  int score = 0;
1793  st = s->streams[i];
1794  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1796  score -= 400;
1797  if (st->codecpar->width && st->codecpar->height)
1798  score += 50;
1799  score+= 25;
1800  }
1801  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1802  if (st->codecpar->sample_rate)
1803  score += 50;
1804  }
1805  if (st->internal->codec_info_nb_frames)
1806  score += 12;
1807 
1808  if (st->discard != AVDISCARD_ALL)
1809  score += 200;
1810 
1811  if (score > best_score) {
1812  best_score = score;
1813  best_stream = i;
1814  }
1815  }
1816  return best_stream;
1817 }
1818 
1819 /** Flush the frame reader. */
1821 {
1822  AVStream *st;
1823  int i, j;
1824 
1826 
1827  /* Reset read state for each stream. */
1828  for (i = 0; i < s->nb_streams; i++) {
1829  st = s->streams[i];
1830 
1831  if (st->internal->parser) {
1833  st->internal->parser = NULL;
1834  }
1837  if (st->internal->first_dts == AV_NOPTS_VALUE)
1839  else
1840  /* We set the current DTS to an unspecified origin. */
1842 
1843  st->internal->probe_packets = s->max_probe_packets;
1844 
1845  for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1847 
1848  if (s->internal->inject_global_side_data)
1850 
1851  st->internal->skip_samples = 0;
1852  }
1853 }
1854 
1855 void avpriv_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1856 {
1857  int i;
1858 
1859  for (i = 0; i < s->nb_streams; i++) {
1860  AVStream *st = s->streams[i];
1861 
1862  st->internal->cur_dts =
1863  av_rescale(timestamp,
1864  st->time_base.den * (int64_t) ref_st->time_base.num,
1865  st->time_base.num * (int64_t) ref_st->time_base.den);
1866  }
1867 }
1868 
1869 void ff_reduce_index(AVFormatContext *s, int stream_index)
1870 {
1871  AVStream *st = s->streams[stream_index];
1872  unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1873 
1874  if ((unsigned) st->internal->nb_index_entries >= max_entries) {
1875  int i;
1876  for (i = 0; 2 * i < st->internal->nb_index_entries; i++)
1877  st->internal->index_entries[i] = st->internal->index_entries[2 * i];
1878  st->internal->nb_index_entries = i;
1879  }
1880 }
1881 
1882 int ff_add_index_entry(AVIndexEntry **index_entries,
1883  int *nb_index_entries,
1884  unsigned int *index_entries_allocated_size,
1885  int64_t pos, int64_t timestamp,
1886  int size, int distance, int flags)
1887 {
1888  AVIndexEntry *entries, *ie;
1889  int index;
1890 
1891  if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1892  return -1;
1893 
1894  if (timestamp == AV_NOPTS_VALUE)
1895  return AVERROR(EINVAL);
1896 
1897  if (size < 0 || size > 0x3FFFFFFF)
1898  return AVERROR(EINVAL);
1899 
1900  if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1901  timestamp -= RELATIVE_TS_BASE;
1902 
1903  entries = av_fast_realloc(*index_entries,
1904  index_entries_allocated_size,
1905  (*nb_index_entries + 1) *
1906  sizeof(AVIndexEntry));
1907  if (!entries)
1908  return -1;
1909 
1910  *index_entries = entries;
1911 
1912  index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1913  timestamp, AVSEEK_FLAG_ANY);
1914 
1915  if (index < 0) {
1916  index = (*nb_index_entries)++;
1917  ie = &entries[index];
1918  av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1919  } else {
1920  ie = &entries[index];
1921  if (ie->timestamp != timestamp) {
1922  if (ie->timestamp <= timestamp)
1923  return -1;
1924  memmove(entries + index + 1, entries + index,
1925  sizeof(AVIndexEntry) * (*nb_index_entries - index));
1926  (*nb_index_entries)++;
1927  } else if (ie->pos == pos && distance < ie->min_distance)
1928  // do not reduce the distance
1929  distance = ie->min_distance;
1930  }
1931 
1932  ie->pos = pos;
1933  ie->timestamp = timestamp;
1934  ie->min_distance = distance;
1935  ie->size = size;
1936  ie->flags = flags;
1937 
1938  return index;
1939 }
1940 
1941 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1942  int size, int distance, int flags)
1943 {
1944  timestamp = wrap_timestamp(st, timestamp);
1947  timestamp, size, distance, flags);
1948 }
1949 
1950 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1951  int64_t wanted_timestamp, int flags)
1952 {
1953  int a, b, m;
1954  int64_t timestamp;
1955 
1956  a = -1;
1957  b = nb_entries;
1958 
1959  // Optimize appending index entries at the end.
1960  if (b && entries[b - 1].timestamp < wanted_timestamp)
1961  a = b - 1;
1962 
1963  while (b - a > 1) {
1964  m = (a + b) >> 1;
1965 
1966  // Search for the next non-discarded packet.
1967  while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
1968  m++;
1969  if (m == b && entries[m].timestamp >= wanted_timestamp) {
1970  m = b - 1;
1971  break;
1972  }
1973  }
1974 
1975  timestamp = entries[m].timestamp;
1976  if (timestamp >= wanted_timestamp)
1977  b = m;
1978  if (timestamp <= wanted_timestamp)
1979  a = m;
1980  }
1981  m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1982 
1983  if (!(flags & AVSEEK_FLAG_ANY))
1984  while (m >= 0 && m < nb_entries &&
1985  !(entries[m].flags & AVINDEX_KEYFRAME))
1986  m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1987 
1988  if (m == nb_entries)
1989  return -1;
1990  return m;
1991 }
1992 
1993 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
1994 {
1995  int ist1, ist2;
1996  int64_t pos_delta = 0;
1997  int64_t skip = 0;
1998  //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
1999  const char *proto = avio_find_protocol_name(s->url);
2000 
2001  av_assert0(time_tolerance >= 0);
2002 
2003  if (!proto) {
2004  av_log(s, AV_LOG_INFO,
2005  "Protocol name not provided, cannot determine if input is local or "
2006  "a network protocol, buffers and access patterns cannot be configured "
2007  "optimally without knowing the protocol\n");
2008  }
2009 
2010  if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2011  return;
2012 
2013  for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
2014  AVStream *st1 = s->streams[ist1];
2015  for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
2016  AVStream *st2 = s->streams[ist2];
2017  int i1, i2;
2018 
2019  if (ist1 == ist2)
2020  continue;
2021 
2022  for (i1 = i2 = 0; i1 < st1->internal->nb_index_entries; i1++) {
2023  AVIndexEntry *e1 = &st1->internal->index_entries[i1];
2024  int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
2025 
2026  skip = FFMAX(skip, e1->size);
2027  for (; i2 < st2->internal->nb_index_entries; i2++) {
2028  AVIndexEntry *e2 = &st2->internal->index_entries[i2];
2029  int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
2030  if (e2_pts < e1_pts || e2_pts - (uint64_t)e1_pts < time_tolerance)
2031  continue;
2032  pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
2033  break;
2034  }
2035  }
2036  }
2037  }
2038 
2039  pos_delta *= 2;
2040  /* XXX This could be adjusted depending on protocol*/
2041  if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
2042  av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
2043 
2044  /* realloc the buffer and the original data will be retained */
2045  if (ffio_realloc_buf(s->pb, pos_delta)) {
2046  av_log(s, AV_LOG_ERROR, "Realloc buffer fail.\n");
2047  return;
2048  }
2049 
2050  s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
2051  }
2052 
2053  if (skip < (1<<23)) {
2054  s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
2055  }
2056 }
2057 
2058 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2059 {
2061  wanted_timestamp, flags);
2062 }
2063 
2065 {
2066  return st->internal->nb_index_entries;
2067 }
2068 
2070 {
2071  if (idx < 0 || idx >= st->internal->nb_index_entries)
2072  return NULL;
2073 
2074  return &st->internal->index_entries[idx];
2075 }
2076 
2078  int64_t wanted_timestamp,
2079  int flags)
2080 {
2083  wanted_timestamp, flags);
2084 
2085  if (idx < 0)
2086  return NULL;
2087 
2088  return &st->internal->index_entries[idx];
2089 }
2090 
2091 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
2092  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2093 {
2094  int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
2095  if (stream_index >= 0)
2096  ts = wrap_timestamp(s->streams[stream_index], ts);
2097  return ts;
2098 }
2099 
2100 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
2101  int64_t target_ts, int flags)
2102 {
2103  const AVInputFormat *avif = s->iformat;
2104  int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2105  int64_t ts_min, ts_max, ts;
2106  int index;
2107  int64_t ret;
2108  AVStream *st;
2109 
2110  if (stream_index < 0)
2111  return -1;
2112 
2113  av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2114 
2115  ts_max =
2116  ts_min = AV_NOPTS_VALUE;
2117  pos_limit = -1; // GCC falsely says it may be uninitialized.
2118 
2119  st = s->streams[stream_index];
2120  if (st->internal->index_entries) {
2121  AVIndexEntry *e;
2122 
2123  /* FIXME: Whole function must be checked for non-keyframe entries in
2124  * index case, especially read_timestamp(). */
2125  index = av_index_search_timestamp(st, target_ts,
2127  index = FFMAX(index, 0);
2128  e = &st->internal->index_entries[index];
2129 
2130  if (e->timestamp <= target_ts || e->pos == e->min_distance) {
2131  pos_min = e->pos;
2132  ts_min = e->timestamp;
2133  av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2134  pos_min, av_ts2str(ts_min));
2135  } else {
2136  av_assert1(index == 0);
2137  }
2138 
2139  index = av_index_search_timestamp(st, target_ts,
2141  av_assert0(index < st->internal->nb_index_entries);
2142  if (index >= 0) {
2143  e = &st->internal->index_entries[index];
2144  av_assert1(e->timestamp >= target_ts);
2145  pos_max = e->pos;
2146  ts_max = e->timestamp;
2147  pos_limit = pos_max - e->min_distance;
2148  av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2149  " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2150  }
2151  }
2152 
2153  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
2154  ts_min, ts_max, flags, &ts, avif->read_timestamp);
2155  if (pos < 0)
2156  return -1;
2157 
2158  /* do the seek */
2159  if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2160  return ret;
2161 
2163  avpriv_update_cur_dts(s, st, ts);
2164 
2165  return 0;
2166 }
2167 
2168 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
2169  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2170 {
2171  int64_t step = 1024;
2172  int64_t limit, ts_max;
2173  int64_t filesize = avio_size(s->pb);
2174  int64_t pos_max = filesize - 1;
2175  do {
2176  limit = pos_max;
2177  pos_max = FFMAX(0, (pos_max) - step);
2178  ts_max = ff_read_timestamp(s, stream_index,
2179  &pos_max, limit, read_timestamp);
2180  step += step;
2181  } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2182  if (ts_max == AV_NOPTS_VALUE)
2183  return -1;
2184 
2185  for (;;) {
2186  int64_t tmp_pos = pos_max + 1;
2187  int64_t tmp_ts = ff_read_timestamp(s, stream_index,
2188  &tmp_pos, INT64_MAX, read_timestamp);
2189  if (tmp_ts == AV_NOPTS_VALUE)
2190  break;
2191  av_assert0(tmp_pos > pos_max);
2192  ts_max = tmp_ts;
2193  pos_max = tmp_pos;
2194  if (tmp_pos >= filesize)
2195  break;
2196  }
2197 
2198  if (ts)
2199  *ts = ts_max;
2200  if (pos)
2201  *pos = pos_max;
2202 
2203  return 0;
2204 }
2205 
2206 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
2207  int64_t pos_min, int64_t pos_max, int64_t pos_limit,
2208  int64_t ts_min, int64_t ts_max,
2209  int flags, int64_t *ts_ret,
2210  int64_t (*read_timestamp)(struct AVFormatContext *, int,
2211  int64_t *, int64_t))
2212 {
2213  int64_t pos, ts;
2214  int64_t start_pos;
2215  int no_change;
2216  int ret;
2217 
2218  av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2219 
2220  if (ts_min == AV_NOPTS_VALUE) {
2221  pos_min = s->internal->data_offset;
2222  ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2223  if (ts_min == AV_NOPTS_VALUE)
2224  return -1;
2225  }
2226 
2227  if (ts_min >= target_ts) {
2228  *ts_ret = ts_min;
2229  return pos_min;
2230  }
2231 
2232  if (ts_max == AV_NOPTS_VALUE) {
2233  if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2234  return ret;
2235  pos_limit = pos_max;
2236  }
2237 
2238  if (ts_max <= target_ts) {
2239  *ts_ret = ts_max;
2240  return pos_max;
2241  }
2242 
2243  av_assert0(ts_min < ts_max);
2244 
2245  no_change = 0;
2246  while (pos_min < pos_limit) {
2248  "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2249  pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2250  av_assert0(pos_limit <= pos_max);
2251 
2252  if (no_change == 0) {
2253  int64_t approximate_keyframe_distance = pos_max - pos_limit;
2254  // interpolate position (better than dichotomy)
2255  pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2256  ts_max - ts_min) +
2257  pos_min - approximate_keyframe_distance;
2258  } else if (no_change == 1) {
2259  // bisection if interpolation did not change min / max pos last time
2260  pos = (pos_min + pos_limit) >> 1;
2261  } else {
2262  /* linear search if bisection failed, can only happen if there
2263  * are very few or no keyframes between min/max */
2264  pos = pos_min;
2265  }
2266  if (pos <= pos_min)
2267  pos = pos_min + 1;
2268  else if (pos > pos_limit)
2269  pos = pos_limit;
2270  start_pos = pos;
2271 
2272  // May pass pos_limit instead of -1.
2273  ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2274  if (pos == pos_max)
2275  no_change++;
2276  else
2277  no_change = 0;
2278  av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2279  " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2280  pos_min, pos, pos_max,
2281  av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2282  pos_limit, start_pos, no_change);
2283  if (ts == AV_NOPTS_VALUE) {
2284  av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2285  return -1;
2286  }
2287  if (target_ts <= ts) {
2288  pos_limit = start_pos - 1;
2289  pos_max = pos;
2290  ts_max = ts;
2291  }
2292  if (target_ts >= ts) {
2293  pos_min = pos;
2294  ts_min = ts;
2295  }
2296  }
2297 
2298  pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2299  ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2300 #if 0
2301  pos_min = pos;
2302  ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2303  pos_min++;
2304  ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2305  av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2306  pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2307 #endif
2308  *ts_ret = ts;
2309  return pos;
2310 }
2311 
2312 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2313  int64_t pos, int flags)
2314 {
2315  int64_t pos_min, pos_max;
2316 
2317  pos_min = s->internal->data_offset;
2318  pos_max = avio_size(s->pb) - 1;
2319 
2320  if (pos < pos_min)
2321  pos = pos_min;
2322  else if (pos > pos_max)
2323  pos = pos_max;
2324 
2325  avio_seek(s->pb, pos, SEEK_SET);
2326 
2327  s->io_repositioned = 1;
2328 
2329  return 0;
2330 }
2331 
2332 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2333  int64_t timestamp, int flags)
2334 {
2335  int index;
2336  int64_t ret;
2337  AVStream *st;
2338  AVIndexEntry *ie;
2339 
2340  st = s->streams[stream_index];
2341 
2342  index = av_index_search_timestamp(st, timestamp, flags);
2343 
2344  if (index < 0 && st->internal->nb_index_entries &&
2345  timestamp < st->internal->index_entries[0].timestamp)
2346  return -1;
2347 
2348  if (index < 0 || index == st->internal->nb_index_entries - 1) {
2349  AVPacket *pkt = s->internal->pkt;
2350  int nonkey = 0;
2351 
2352  if (st->internal->nb_index_entries) {
2354  ie = &st->internal->index_entries[st->internal->nb_index_entries - 1];
2355  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2356  return ret;
2357  avpriv_update_cur_dts(s, st, ie->timestamp);
2358  } else {
2359  if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2360  return ret;
2361  }
2363  for (;;) {
2364  int read_status;
2365  do {
2366  read_status = av_read_frame(s, pkt);
2367  } while (read_status == AVERROR(EAGAIN));
2368  if (read_status < 0)
2369  break;
2370  if (stream_index == pkt->stream_index && pkt->dts > timestamp) {
2371  if (pkt->flags & AV_PKT_FLAG_KEY) {
2373  break;
2374  }
2375  if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2376  av_log(s, AV_LOG_ERROR,"seek_frame_generic failed as this stream seems to contain no keyframes after the target timestamp, %d non keyframes found\n", nonkey);
2378  break;
2379  }
2380  }
2382  }
2383  index = av_index_search_timestamp(st, timestamp, flags);
2384  }
2385  if (index < 0)
2386  return -1;
2387 
2389  if (s->iformat->read_seek)
2390  if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2391  return 0;
2392  ie = &st->internal->index_entries[index];
2393  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2394  return ret;
2395  avpriv_update_cur_dts(s, st, ie->timestamp);
2396 
2397  return 0;
2398 }
2399 
2400 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2401  int64_t timestamp, int flags)
2402 {
2403  int ret;
2404  AVStream *st;
2405 
2406  if (flags & AVSEEK_FLAG_BYTE) {
2407  if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2408  return -1;
2410  return seek_frame_byte(s, stream_index, timestamp, flags);
2411  }
2412 
2413  if (stream_index < 0) {
2414  stream_index = av_find_default_stream_index(s);
2415  if (stream_index < 0)
2416  return -1;
2417 
2418  st = s->streams[stream_index];
2419  /* timestamp for default must be expressed in AV_TIME_BASE units */
2420  timestamp = av_rescale(timestamp, st->time_base.den,
2421  AV_TIME_BASE * (int64_t) st->time_base.num);
2422  }
2423 
2424  /* first, we try the format specific seek */
2425  if (s->iformat->read_seek) {
2427  ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2428  } else
2429  ret = -1;
2430  if (ret >= 0)
2431  return 0;
2432 
2433  if (s->iformat->read_timestamp &&
2434  !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2436  return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2437  } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2439  return seek_frame_generic(s, stream_index, timestamp, flags);
2440  } else
2441  return -1;
2442 }
2443 
2444 int av_seek_frame(AVFormatContext *s, int stream_index,
2445  int64_t timestamp, int flags)
2446 {
2447  int ret;
2448 
2449  if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2450  int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2451  if ((flags & AVSEEK_FLAG_BACKWARD))
2452  max_ts = timestamp;
2453  else
2454  min_ts = timestamp;
2455  return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2457  }
2458 
2459  ret = seek_frame_internal(s, stream_index, timestamp, flags);
2460 
2461  if (ret >= 0)
2463 
2464  return ret;
2465 }
2466 
2467 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2468  int64_t ts, int64_t max_ts, int flags)
2469 {
2470  if (min_ts > ts || max_ts < ts)
2471  return -1;
2472  if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2473  return AVERROR(EINVAL);
2474 
2475  if (s->seek2any>0)
2478 
2479  if (s->iformat->read_seek2) {
2480  int ret;
2482 
2483  if (stream_index == -1 && s->nb_streams == 1) {
2484  AVRational time_base = s->streams[0]->time_base;
2485  ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2486  min_ts = av_rescale_rnd(min_ts, time_base.den,
2487  time_base.num * (int64_t)AV_TIME_BASE,
2489  max_ts = av_rescale_rnd(max_ts, time_base.den,
2490  time_base.num * (int64_t)AV_TIME_BASE,
2492  stream_index = 0;
2493  }
2494 
2495  ret = s->iformat->read_seek2(s, stream_index, min_ts,
2496  ts, max_ts, flags);
2497 
2498  if (ret >= 0)
2500  return ret;
2501  }
2502 
2503  if (s->iformat->read_timestamp) {
2504  // try to seek via read_timestamp()
2505  }
2506 
2507  // Fall back on old API if new is not implemented but old is.
2508  // Note the old API has somewhat different semantics.
2509  if (s->iformat->read_seek || 1) {
2510  int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2511  int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2512  if (ret<0 && ts != min_ts && max_ts != ts) {
2513  ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2514  if (ret >= 0)
2515  ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2516  }
2517  return ret;
2518  }
2519 
2520  // try some generic seek like seek_frame_generic() but with new ts semantics
2521  return -1; //unreachable
2522 }
2523 
2525 {
2527  return 0;
2528 }
2529 
2530 /*******************************************************/
2531 
2532 /**
2533  * Return TRUE if the stream has accurate duration in any stream.
2534  *
2535  * @return TRUE if the stream has accurate duration for at least one component.
2536  */
2538 {
2539  int i;
2540  AVStream *st;
2541 
2542  for (i = 0; i < ic->nb_streams; i++) {
2543  st = ic->streams[i];
2544  if (st->duration != AV_NOPTS_VALUE)
2545  return 1;
2546  }
2547  if (ic->duration != AV_NOPTS_VALUE)
2548  return 1;
2549  return 0;
2550 }
2551 
2552 /**
2553  * Estimate the stream timings from the one of each components.
2554  *
2555  * Also computes the global bitrate if possible.
2556  */
2558 {
2559  int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2560  int64_t duration, duration1, duration_text, filesize;
2561  int i;
2562  AVProgram *p;
2563 
2564  start_time = INT64_MAX;
2565  start_time_text = INT64_MAX;
2566  end_time = INT64_MIN;
2567  end_time_text = INT64_MIN;
2568  duration = INT64_MIN;
2569  duration_text = INT64_MIN;
2570 
2571  for (i = 0; i < ic->nb_streams; i++) {
2572  AVStream *st = ic->streams[i];
2573  int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2575  if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2576  start_time1 = av_rescale_q(st->start_time, st->time_base,
2577  AV_TIME_BASE_Q);
2578  if (is_text)
2579  start_time_text = FFMIN(start_time_text, start_time1);
2580  else
2581  start_time = FFMIN(start_time, start_time1);
2582  end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
2585  if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2586  end_time1 += start_time1;
2587  if (is_text)
2588  end_time_text = FFMAX(end_time_text, end_time1);
2589  else
2590  end_time = FFMAX(end_time, end_time1);
2591  }
2592  for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2593  if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2594  p->start_time = start_time1;
2595  if (p->end_time < end_time1)
2596  p->end_time = end_time1;
2597  }
2598  }
2599  if (st->duration != AV_NOPTS_VALUE) {
2600  duration1 = av_rescale_q(st->duration, st->time_base,
2601  AV_TIME_BASE_Q);
2602  if (is_text)
2603  duration_text = FFMAX(duration_text, duration1);
2604  else
2605  duration = FFMAX(duration, duration1);
2606  }
2607  }
2608  if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2609  start_time = start_time_text;
2610  else if (start_time > start_time_text)
2611  av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2612 
2613  if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2614  end_time = end_time_text;
2615  else if (end_time < end_time_text)
2616  av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
2617 
2618  if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
2619  duration = duration_text;
2620  else if (duration < duration_text)
2621  av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
2622 
2623  if (start_time != INT64_MAX) {
2624  ic->start_time = start_time;
2625  if (end_time != INT64_MIN) {
2626  if (ic->nb_programs > 1) {
2627  for (i = 0; i < ic->nb_programs; i++) {
2628  p = ic->programs[i];
2629  if (p->start_time != AV_NOPTS_VALUE &&
2630  p->end_time > p->start_time &&
2631  p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2633  }
2634  } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2635  duration = FFMAX(duration, end_time - start_time);
2636  }
2637  }
2638  }
2639  if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2640  ic->duration = duration;
2641  }
2642  if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2643  /* compute the bitrate */
2644  double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2645  (double) ic->duration;
2646  if (bitrate >= 0 && bitrate <= INT64_MAX)
2647  ic->bit_rate = bitrate;
2648  }
2649 }
2650 
2652 {
2653  int i;
2654  AVStream *st;
2655 
2657  for (i = 0; i < ic->nb_streams; i++) {
2658  st = ic->streams[i];
2659  if (st->start_time == AV_NOPTS_VALUE) {
2660  if (ic->start_time != AV_NOPTS_VALUE)
2662  st->time_base);
2663  if (ic->duration != AV_NOPTS_VALUE)
2665  st->time_base);
2666  }
2667  }
2668 }
2669 
2671 {
2672  int64_t filesize, duration;
2673  int i, show_warning = 0;
2674  AVStream *st;
2675 
2676  /* if bit_rate is already set, we believe it */
2677  if (ic->bit_rate <= 0) {
2678  int64_t bit_rate = 0;
2679  for (i = 0; i < ic->nb_streams; i++) {
2680  st = ic->streams[i];
2681  if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
2682  st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2683  if (st->codecpar->bit_rate > 0) {
2684  if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2685  bit_rate = 0;
2686  break;
2687  }
2688  bit_rate += st->codecpar->bit_rate;
2689  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->internal->codec_info_nb_frames > 1) {
2690  // If we have a videostream with packets but without a bitrate
2691  // then consider the sum not known
2692  bit_rate = 0;
2693  break;
2694  }
2695  }
2696  ic->bit_rate = bit_rate;
2697  }
2698 
2699  /* if duration is already set, we believe it */
2700  if (ic->duration == AV_NOPTS_VALUE &&
2701  ic->bit_rate != 0) {
2702  filesize = ic->pb ? avio_size(ic->pb) : 0;
2703  if (filesize > ic->internal->data_offset) {
2704  filesize -= ic->internal->data_offset;
2705  for (i = 0; i < ic->nb_streams; i++) {
2706  st = ic->streams[i];
2707  if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2708  && st->duration == AV_NOPTS_VALUE) {
2709  duration = av_rescale(filesize, 8LL * st->time_base.den,
2710  ic->bit_rate *
2711  (int64_t) st->time_base.num);
2712  st->duration = duration;
2713  show_warning = 1;
2714  }
2715  }
2716  }
2717  }
2718  if (show_warning)
2719  av_log(ic, AV_LOG_WARNING,
2720  "Estimating duration from bitrate, this may be inaccurate\n");
2721 }
2722 
2723 #define DURATION_MAX_READ_SIZE 250000LL
2724 #define DURATION_MAX_RETRY 6
2725 
2726 /* only usable for MPEG-PS streams */
2727 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2728 {
2729  AVPacket *pkt = ic->internal->pkt;
2730  AVStream *st;
2731  int num, den, read_size, i, ret;
2732  int found_duration = 0;
2733  int is_end;
2734  int64_t filesize, offset, duration;
2735  int retry = 0;
2736 
2737  /* flush packet queue */
2738  flush_packet_queue(ic);
2739 
2740  for (i = 0; i < ic->nb_streams; i++) {
2741  st = ic->streams[i];
2742  if (st->start_time == AV_NOPTS_VALUE &&
2743  st->internal->first_dts == AV_NOPTS_VALUE &&
2745  av_log(ic, AV_LOG_WARNING,
2746  "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2747 
2748  if (st->internal->parser) {
2750  st->internal->parser = NULL;
2751  }
2752  }
2753 
2755  av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
2756  goto skip_duration_calc;
2757  }
2758 
2759  av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2760  /* estimate the end time (duration) */
2761  /* XXX: may need to support wrapping */
2762  filesize = ic->pb ? avio_size(ic->pb) : 0;
2763  do {
2764  is_end = found_duration;
2765  offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2766  if (offset < 0)
2767  offset = 0;
2768 
2769  avio_seek(ic->pb, offset, SEEK_SET);
2770  read_size = 0;
2771  for (;;) {
2772  if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2773  break;
2774 
2775  do {
2776  ret = ff_read_packet(ic, pkt);
2777  } while (ret == AVERROR(EAGAIN));
2778  if (ret != 0)
2779  break;
2780  read_size += pkt->size;
2781  st = ic->streams[pkt->stream_index];
2782  if (pkt->pts != AV_NOPTS_VALUE &&
2783  (st->start_time != AV_NOPTS_VALUE ||
2784  st->internal->first_dts != AV_NOPTS_VALUE)) {
2785  if (pkt->duration == 0) {
2786  ff_compute_frame_duration(ic, &num, &den, st, st->internal->parser, pkt);
2787  if (den && num) {
2789  num * (int64_t) st->time_base.den,
2790  den * (int64_t) st->time_base.num,
2791  AV_ROUND_DOWN);
2792  }
2793  }
2794  duration = pkt->pts + pkt->duration;
2795  found_duration = 1;
2796  if (st->start_time != AV_NOPTS_VALUE)
2797  duration -= st->start_time;
2798  else
2799  duration -= st->internal->first_dts;
2800  if (duration > 0) {
2801  if (st->duration == AV_NOPTS_VALUE || st->internal->info->last_duration<= 0 ||
2802  (st->duration < duration && FFABS(duration - st->internal->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2803  st->duration = duration;
2805  }
2806  }
2808  }
2809 
2810  /* check if all audio/video streams have valid duration */
2811  if (!is_end) {
2812  is_end = 1;
2813  for (i = 0; i < ic->nb_streams; i++) {
2814  st = ic->streams[i];
2815  switch (st->codecpar->codec_type) {
2816  case AVMEDIA_TYPE_VIDEO:
2817  case AVMEDIA_TYPE_AUDIO:
2818  if (st->duration == AV_NOPTS_VALUE)
2819  is_end = 0;
2820  }
2821  }
2822  }
2823  } while (!is_end &&
2824  offset &&
2825  ++retry <= DURATION_MAX_RETRY);
2826 
2827  av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2828 
2829  /* warn about audio/video streams which duration could not be estimated */
2830  for (i = 0; i < ic->nb_streams; i++) {
2831  st = ic->streams[i];
2832  if (st->duration == AV_NOPTS_VALUE) {
2833  switch (st->codecpar->codec_type) {
2834  case AVMEDIA_TYPE_VIDEO:
2835  case AVMEDIA_TYPE_AUDIO:
2836  if (st->start_time != AV_NOPTS_VALUE || st->internal->first_dts != AV_NOPTS_VALUE) {
2837  av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
2838  } else
2839  av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
2840  }
2841  }
2842  }
2843 skip_duration_calc:
2845 
2846  avio_seek(ic->pb, old_offset, SEEK_SET);
2847  for (i = 0; i < ic->nb_streams; i++) {
2848  int j;
2849 
2850  st = ic->streams[i];
2851  st->internal->cur_dts = st->internal->first_dts;
2854  for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2856  }
2857 }
2858 
2859 /* 1:1 map to AVDurationEstimationMethod */
2860 static const char *const duration_name[] = {
2861  [AVFMT_DURATION_FROM_PTS] = "pts",
2862  [AVFMT_DURATION_FROM_STREAM] = "stream",
2863  [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2864 };
2865 
2867 {
2868  return duration_name[method];
2869 }
2870 
2871 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2872 {
2873  int64_t file_size;
2874 
2875  /* get the file size, if possible */
2876  if (ic->iformat->flags & AVFMT_NOFILE) {
2877  file_size = 0;
2878  } else {
2879  file_size = avio_size(ic->pb);
2880  file_size = FFMAX(0, file_size);
2881  }
2882 
2883  if ((!strcmp(ic->iformat->name, "mpeg") ||
2884  !strcmp(ic->iformat->name, "mpegts")) &&
2885  file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2886  /* get accurate estimate from the PTSes */
2887  estimate_timings_from_pts(ic, old_offset);
2889  } else if (has_duration(ic)) {
2890  /* at least one component has timings - we use them for all
2891  * the components */
2893  /* nut demuxer estimate the duration from PTS */
2894  if(!strcmp(ic->iformat->name, "nut"))
2896  else
2898  } else {
2899  /* less precise: use bitrate info */
2902  }
2904 
2905  for (unsigned i = 0; i < ic->nb_streams; i++) {
2906  AVStream *st = ic->streams[i];
2907  if (st->time_base.den)
2908  av_log(ic, AV_LOG_TRACE, "stream %u: start_time: %s duration: %s\n", i,
2909  av_ts2timestr(st->start_time, &st->time_base),
2910  av_ts2timestr(st->duration, &st->time_base));
2911  }
2912  av_log(ic, AV_LOG_TRACE,
2913  "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
2917  (int64_t)ic->bit_rate / 1000);
2918 }
2919 
2920 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2921 {
2922  AVCodecContext *avctx = st->internal->avctx;
2923 
2924 #define FAIL(errmsg) do { \
2925  if (errmsg_ptr) \
2926  *errmsg_ptr = errmsg; \
2927  return 0; \
2928  } while (0)
2929 
2930  if ( avctx->codec_id == AV_CODEC_ID_NONE
2931  && avctx->codec_type != AVMEDIA_TYPE_DATA)
2932  FAIL("unknown codec");
2933  switch (avctx->codec_type) {
2934  case AVMEDIA_TYPE_AUDIO:
2935  if (!avctx->frame_size && determinable_frame_size(avctx))
2936  FAIL("unspecified frame size");
2937  if (st->internal->info->found_decoder >= 0 &&
2938  avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2939  FAIL("unspecified sample format");
2940  if (!avctx->sample_rate)
2941  FAIL("unspecified sample rate");
2942  if (!avctx->channels)
2943  FAIL("unspecified number of channels");
2944  if (st->internal->info->found_decoder >= 0 && !st->internal->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2945  FAIL("no decodable DTS frames");
2946  break;
2947  case AVMEDIA_TYPE_VIDEO:
2948  if (!avctx->width)
2949  FAIL("unspecified size");
2950  if (st->internal->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2951  FAIL("unspecified pixel format");
2954  FAIL("no frame in rv30/40 and no sar");
2955  break;
2956  case AVMEDIA_TYPE_SUBTITLE:
2957  if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2958  FAIL("unspecified size");
2959  break;
2960  case AVMEDIA_TYPE_DATA:
2961  if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2962  }
2963 
2964  return 1;
2965 }
2966 
2967 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2969  const AVPacket *avpkt, AVDictionary **options)
2970 {
2971  AVCodecContext *avctx = st->internal->avctx;
2972  const AVCodec *codec;
2973  int got_picture = 1, ret = 0;
2975  AVSubtitle subtitle;
2976  AVPacket pkt = *avpkt;
2977  int do_skip_frame = 0;
2978  enum AVDiscard skip_frame;
2979 
2980  if (!frame)
2981  return AVERROR(ENOMEM);
2982 
2983  if (!avcodec_is_open(avctx) &&
2984  st->internal->info->found_decoder <= 0 &&
2985  (st->codecpar->codec_id != -st->internal->info->found_decoder || !st->codecpar->codec_id)) {
2986  AVDictionary *thread_opt = NULL;
2987 
2988  codec = find_probe_decoder(s, st, st->codecpar->codec_id);
2989 
2990  if (!codec) {
2992  ret = -1;
2993  goto fail;
2994  }
2995 
2996  /* Force thread count to 1 since the H.264 decoder will not extract
2997  * SPS and PPS to extradata during multi-threaded decoding. */
2998  av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2999  /* Force lowres to 0. The decoder might reduce the video size by the
3000  * lowres factor, and we don't want that propagated to the stream's
3001  * codecpar */
3002  av_dict_set(options ? options : &thread_opt, "lowres", "0", 0);
3003  if (s->codec_whitelist)
3004  av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3005  ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3006  if (!options)
3007  av_dict_free(&thread_opt);
3008  if (ret < 0) {
3009  st->internal->info->found_decoder = -avctx->codec_id;
3010  goto fail;
3011  }
3012  st->internal->info->found_decoder = 1;
3013  } else if (!st->internal->info->found_decoder)
3014  st->internal->info->found_decoder = 1;
3015 
3016  if (st->internal->info->found_decoder < 0) {
3017  ret = -1;
3018  goto fail;
3019  }
3020 
3022  do_skip_frame = 1;
3023  skip_frame = avctx->skip_frame;
3024  avctx->skip_frame = AVDISCARD_ALL;
3025  }
3026 
3027  while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
3028  ret >= 0 &&
3030  (!st->internal->codec_info_nb_frames &&
3032  got_picture = 0;
3033  if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3034  avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3035  ret = avcodec_send_packet(avctx, &pkt);
3036  if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3037  break;
3038  if (ret >= 0)
3039  pkt.size = 0;
3040  ret = avcodec_receive_frame(avctx, frame);
3041  if (ret >= 0)
3042  got_picture = 1;
3043  if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
3044  ret = 0;
3045  } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3046  ret = avcodec_decode_subtitle2(avctx, &subtitle,
3047  &got_picture, &pkt);
3048  if (got_picture)
3049  avsubtitle_free(&subtitle);
3050  if (ret >= 0)
3051  pkt.size = 0;
3052  }
3053  if (ret >= 0) {
3054  if (got_picture)
3055  st->internal->nb_decoded_frames++;
3056  ret = got_picture;
3057  }
3058  }
3059 
3060  if (!pkt.data && !got_picture)
3061  ret = -1;
3062 
3063 fail:
3064  if (do_skip_frame) {
3065  avctx->skip_frame = skip_frame;
3066  }
3067 
3068  av_frame_free(&frame);
3069  return ret;
3070 }
3071 
3072 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3073 {
3074  while (tags->id != AV_CODEC_ID_NONE) {
3075  if (tags->id == id)
3076  return tags->tag;
3077  tags++;
3078  }
3079  return 0;
3080 }
3081 
3082 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3083 {
3084  int i;
3085  for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3086  if (tag == tags[i].tag)
3087  return tags[i].id;
3088  for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3089  if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3090  return tags[i].id;
3091  return AV_CODEC_ID_NONE;
3092 }
3093 
3094 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
3095 {
3096  if (bps <= 0 || bps > 64)
3097  return AV_CODEC_ID_NONE;
3098 
3099  if (flt) {
3100  switch (bps) {
3101  case 32:
3103  case 64:
3105  default:
3106  return AV_CODEC_ID_NONE;
3107  }
3108  } else {
3109  bps += 7;
3110  bps >>= 3;
3111  if (sflags & (1 << (bps - 1))) {
3112  switch (bps) {
3113  case 1:
3114  return AV_CODEC_ID_PCM_S8;
3115  case 2:
3117  case 3:
3119  case 4:
3121  case 8:
3123  default:
3124  return AV_CODEC_ID_NONE;
3125  }
3126  } else {
3127  switch (bps) {
3128  case 1:
3129  return AV_CODEC_ID_PCM_U8;
3130  case 2:
3132  case 3:
3134  case 4:
3136  default:
3137  return AV_CODEC_ID_NONE;
3138  }
3139  }
3140  }
3141 }
3142 
3143 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3144 {
3145  unsigned int tag;
3146  if (!av_codec_get_tag2(tags, id, &tag))
3147  return 0;
3148  return tag;
3149 }
3150 
3151 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
3152  unsigned int *tag)
3153 {
3154  int i;
3155  for (i = 0; tags && tags[i]; i++) {
3156  const AVCodecTag *codec_tags = tags[i];
3157  while (codec_tags->id != AV_CODEC_ID_NONE) {
3158  if (codec_tags->id == id) {
3159  *tag = codec_tags->tag;
3160  return 1;
3161  }
3162  codec_tags++;
3163  }
3164  }
3165  return 0;
3166 }
3167 
3168 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3169 {
3170  int i;
3171  for (i = 0; tags && tags[i]; i++) {
3172  enum AVCodecID id = ff_codec_get_id(tags[i], tag);
3173  if (id != AV_CODEC_ID_NONE)
3174  return id;
3175  }
3176  return AV_CODEC_ID_NONE;
3177 }
3178 
3179 static int chapter_start_cmp(const void *p1, const void *p2)
3180 {
3181  AVChapter *ch1 = *(AVChapter**)p1;
3182  AVChapter *ch2 = *(AVChapter**)p2;
3183  int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
3184  if (delta)
3185  return delta;
3186  return (ch1 > ch2) - (ch1 < ch2);
3187 }
3188 
3190 {
3191  unsigned int i;
3192  int64_t max_time = 0;
3193  AVChapter **timetable = av_malloc(s->nb_chapters * sizeof(*timetable));
3194 
3195  if (!timetable)
3196  return AVERROR(ENOMEM);
3197 
3198  if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3199  max_time = s->duration +
3200  ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3201 
3202  for (i = 0; i < s->nb_chapters; i++)
3203  timetable[i] = s->chapters[i];
3204  qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
3205 
3206  for (i = 0; i < s->nb_chapters; i++)
3207  if (timetable[i]->end == AV_NOPTS_VALUE) {
3208  AVChapter *ch = timetable[i];
3209  int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3210  ch->time_base)
3211  : INT64_MAX;
3212 
3213  if (i + 1 < s->nb_chapters) {
3214  AVChapter *ch1 = timetable[i + 1];
3215  int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3216  ch->time_base);
3217  if (next_start > ch->start && next_start < end)
3218  end = next_start;
3219  }
3220  ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3221  }
3222  av_free(timetable);
3223  return 0;
3224 }
3225 
3226 static int get_std_framerate(int i)
3227 {
3228  if (i < 30*12)
3229  return (i + 1) * 1001;
3230  i -= 30*12;
3231 
3232  if (i < 30)
3233  return (i + 31) * 1001 * 12;
3234  i -= 30;
3235 
3236  if (i < 3)
3237  return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3238 
3239  i -= 3;
3240 
3241  return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3242 }
3243 
3244 /* Is the time base unreliable?
3245  * This is a heuristic to balance between quick acceptance of the values in
3246  * the headers vs. some extra checks.
3247  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3248  * MPEG-2 commonly misuses field repeat flags to store different framerates.
3249  * And there are "variable" fps files this needs to detect as well. */
3251 {
3252  if (c->time_base.den >= 101LL * c->time_base.num ||
3253  c->time_base.den < 5LL * c->time_base.num ||
3254  // c->codec_tag == AV_RL32("DIVX") ||
3255  // c->codec_tag == AV_RL32("XVID") ||
3256  c->codec_tag == AV_RL32("mp4v") ||
3257  c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3258  c->codec_id == AV_CODEC_ID_GIF ||
3259  c->codec_id == AV_CODEC_ID_HEVC ||
3260  c->codec_id == AV_CODEC_ID_H264)
3261  return 1;
3262  return 0;
3263 }
3264 
3266 {
3267  av_freep(&par->extradata);
3268  par->extradata_size = 0;
3269 
3270  if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3271  return AVERROR(EINVAL);
3272 
3274  if (!par->extradata)
3275  return AVERROR(ENOMEM);
3276 
3277  memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3278  par->extradata_size = size;
3279 
3280  return 0;
3281 }
3282 
3284 {
3285  int ret = ff_alloc_extradata(par, size);
3286  if (ret < 0)
3287  return ret;
3288  ret = avio_read(pb, par->extradata, size);
3289  if (ret != size) {
3290  av_freep(&par->extradata);
3291  par->extradata_size = 0;
3292  av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3293  return ret < 0 ? ret : AVERROR_INVALIDDATA;
3294  }
3295 
3296  return ret;
3297 }
3298 
3299 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3300 {
3301  int i, j;
3302  int64_t last = st->internal->info->last_dts;
3303 
3304  if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3305  && ts - (uint64_t)last < INT64_MAX) {
3306  double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3307  int64_t duration = ts - last;
3308 
3309  if (!st->internal->info->duration_error)
3310  st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3311  if (!st->internal->info->duration_error)
3312  return AVERROR(ENOMEM);
3313 
3314 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3315 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3316  for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3317  if (st->internal->info->duration_error[0][1][i] < 1e10) {
3318  int framerate = get_std_framerate(i);
3319  double sdts = dts*framerate/(1001*12);
3320  for (j= 0; j<2; j++) {
3321  int64_t ticks = llrint(sdts+j*0.5);
3322  double error= sdts - ticks + j*0.5;
3323  st->internal->info->duration_error[j][0][i] += error;
3324  st->internal->info->duration_error[j][1][i] += error*error;
3325  }
3326  }
3327  }
3328  if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3329  st->internal->info->duration_count++;
3331  }
3332 
3333  if (st->internal->info->duration_count % 10 == 0) {
3334  int n = st->internal->info->duration_count;
3335  for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3336  if (st->internal->info->duration_error[0][1][i] < 1e10) {
3337  double a0 = st->internal->info->duration_error[0][0][i] / n;
3338  double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3339  double a1 = st->internal->info->duration_error[1][0][i] / n;
3340  double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3341  if (error0 > 0.04 && error1 > 0.04) {
3342  st->internal->info->duration_error[0][1][i] = 2e10;
3343  st->internal->info->duration_error[1][1][i] = 2e10;
3344  }
3345  }
3346  }
3347  }
3348 
3349  // ignore the first 4 values, they might have some random jitter
3350  if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3352  }
3353  if (ts != AV_NOPTS_VALUE)
3354  st->internal->info->last_dts = ts;
3355 
3356  return 0;
3357 }
3358 
3360 {
3361  int i, j;
3362 
3363  for (i = 0; i < ic->nb_streams; i++) {
3364  AVStream *st = ic->streams[i];
3365 
3367  continue;
3368  // the check for tb_unreliable() is not completely correct, since this is not about handling
3369  // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3370  // ipmovie.c produces.
3371  if (tb_unreliable(st->internal->avctx) && st->internal->info->duration_count > 15 && st->internal->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num &&
3372  st->internal->info->duration_gcd < INT64_MAX / st->time_base.num)
3373  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->internal->info->duration_gcd, INT_MAX);
3374  if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3375  && tb_unreliable(st->internal->avctx)) {
3376  int num = 0;
3377  double best_error= 0.01;
3378  AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3379 
3380  for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3381  int k;
3382 
3383  if (st->internal->info->codec_info_duration &&
3384  st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3385  continue;
3386  if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3387  continue;
3388 
3389  if (av_q2d(st->time_base) * st->internal->info->rfps_duration_sum / st->internal->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3390  continue;
3391 
3392  for (k= 0; k<2; k++) {
3393  int n = st->internal->info->duration_count;
3394  double a= st->internal->info->duration_error[k][0][j] / n;
3395  double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3396 
3397  if (error < best_error && best_error> 0.000000001) {
3398  best_error= error;
3399  num = get_std_framerate(j);
3400  }
3401  if (error < 0.02)
3402  av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3403  }
3404  }
3405  // do not increase frame rate by more than 1 % in order to match a standard rate.
3406  if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3407  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3408  }
3409  if ( !st->avg_frame_rate.num
3411  && st->internal->info->codec_info_duration <= 0
3412  && st->internal->info->duration_count > 2
3413  && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->internal->info->rfps_duration_sum / (double)st->internal->info->duration_count) <= 1.0
3414  ) {
3415  av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3416  st->avg_frame_rate = st->r_frame_rate;
3417  }
3418 
3421  st->internal->info->duration_count = 0;
3422  st->internal->info->rfps_duration_sum = 0;
3423  }
3424 }
3425 
3427 {
3428  const AVBitStreamFilter *f;
3429 
3430  f = av_bsf_get_by_name("extract_extradata");
3431  if (!f)
3432  return 0;
3433 
3434  if (f->codec_ids) {
3435  const enum AVCodecID *ids;
3436  for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3437  if (*ids == st->codecpar->codec_id)
3438  return 1;
3439  }
3440 
3441  return 0;
3442 }
3443 
3445 {
3446  AVStreamInternal *sti = st->internal;
3447  const AVBitStreamFilter *f;
3448  int ret;
3449 
3450  f = av_bsf_get_by_name("extract_extradata");
3451  if (!f)
3452  goto finish;
3453 
3454  /* check that the codec id is supported */
3456  if (!ret)
3457  goto finish;
3458 
3460  if (ret < 0)
3461  return ret;
3462 
3464  st->codecpar);
3465  if (ret < 0)
3466  goto fail;
3467 
3469 
3471  if (ret < 0)
3472  goto fail;
3473 
3474 finish:
3475  sti->extract_extradata.inited = 1;
3476 
3477  return 0;
3478 fail:
3480  return ret;
3481 }
3482 
3484 {
3485  AVStreamInternal *sti = st->internal;
3486  AVPacket *pkt_ref = s->internal->parse_pkt;
3487  int ret;
3488 
3489  if (!sti->extract_extradata.inited) {
3491  if (ret < 0)
3492  return ret;
3493  }
3494 
3495  if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3496  return 0;
3497 
3498  ret = av_packet_ref(pkt_ref, pkt);
3499  if (ret < 0)
3500  return ret;
3501 
3502  ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3503  if (ret < 0) {
3504  av_packet_unref(pkt_ref);
3505  return ret;
3506  }
3507 
3508  while (ret >= 0 && !sti->avctx->extradata) {
3510  if (ret < 0) {
3511  if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3512  return ret;
3513  continue;
3514  }
3515 
3516  for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3517  AVPacketSideData *side_data = &pkt_ref->side_data[i];
3518  if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3519  sti->avctx->extradata = side_data->data;
3520  sti->avctx->extradata_size = side_data->size;
3521  side_data->data = NULL;
3522  side_data->size = 0;
3523  break;
3524  }
3525  }
3526  av_packet_unref(pkt_ref);
3527  }
3528 
3529  return 0;
3530 }
3531 
3533 {
3534  int i;
3535 
3536  for (i = 0; i < avctx->nb_coded_side_data; i++) {
3537  const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3538  uint8_t *dst_data;
3539  dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3540  if (!dst_data)
3541  return AVERROR(ENOMEM);
3542  memcpy(dst_data, sd_src->data, sd_src->size);
3543  }
3544  return 0;
3545 }
3546 
3548 {
3549  int i, count = 0, ret = 0, j;
3550  int64_t read_size;
3551  AVStream *st;
3552  AVCodecContext *avctx;
3553  AVPacket *pkt1 = ic->internal->pkt;
3554  int64_t old_offset = avio_tell(ic->pb);
3555  // new streams might appear, no options for those
3556  int orig_nb_streams = ic->nb_streams;
3557  int flush_codecs;
3558  int64_t max_analyze_duration = ic->max_analyze_duration;
3559  int64_t max_stream_analyze_duration;
3560  int64_t max_subtitle_analyze_duration;
3561  int64_t probesize = ic->probesize;
3562  int eof_reached = 0;
3563  int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3564 
3565  flush_codecs = probesize > 0;
3566 
3567  av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3568 
3569  max_stream_analyze_duration = max_analyze_duration;
3570  max_subtitle_analyze_duration = max_analyze_duration;
3571  if (!max_analyze_duration) {
3572  max_stream_analyze_duration =
3573  max_analyze_duration = 5*AV_TIME_BASE;
3574  max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3575  if (!strcmp(ic->iformat->name, "flv"))
3576  max_stream_analyze_duration = 90*AV_TIME_BASE;
3577  if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3578  max_stream_analyze_duration = 7*AV_TIME_BASE;
3579  }
3580 
3581  if (ic->pb)
3582  av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3583  avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3584 
3585  for (i = 0; i < ic->nb_streams; i++) {
3586  const AVCodec *codec;
3587  AVDictionary *thread_opt = NULL;
3588  st = ic->streams[i];
3589  avctx = st->internal->avctx;
3590 
3591  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3593 /* if (!st->time_base.num)
3594  st->time_base = */
3595  if (!avctx->time_base.num)
3596  avctx->time_base = st->time_base;
3597  }
3598 
3599  /* check if the caller has overridden the codec id */
3600  // only for the split stuff
3601  if (!st->internal->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3603  if (st->internal->parser) {
3606  } else if (st->internal->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3608  }
3609  } else if (st->internal->need_parsing) {
3610  av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3611  "%s, packets or times may be invalid.\n",
3613  }
3614  }
3615 
3617  if (ret < 0)
3618  goto find_stream_info_err;
3619  if (st->internal->request_probe <= 0)
3620  st->internal->avctx_inited = 1;
3621 
3622  codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3623 
3624  /* Force thread count to 1 since the H.264 decoder will not extract
3625  * SPS and PPS to extradata during multi-threaded decoding. */
3626  av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3627  /* Force lowres to 0. The decoder might reduce the video size by the
3628  * lowres factor, and we don't want that propagated to the stream's
3629  * codecpar */
3630  av_dict_set(options ? &options[i] : &thread_opt, "lowres", "0", 0);
3631 
3632  if (ic->codec_whitelist)
3633  av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3634 
3635  // Try to just open decoders, in case this is enough to get parameters.
3636  // Also ensure that subtitle_header is properly set.
3637  if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0 ||
3639  if (codec && !avctx->codec)
3640  if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3641  av_log(ic, AV_LOG_WARNING,
3642  "Failed to open codec in %s\n",__FUNCTION__);
3643  }
3644  if (!options)
3645  av_dict_free(&thread_opt);
3646  }
3647 
3648  for (i = 0; i < ic->nb_streams; i++) {
3649 #if FF_API_R_FRAME_RATE
3651 #endif
3654  }
3655 
3656  read_size = 0;
3657  for (;;) {
3658  const AVPacket *pkt;
3659  int analyzed_all_streams;
3661  ret = AVERROR_EXIT;
3662  av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3663  break;
3664  }
3665 
3666  /* check if one codec still needs to be handled */
3667  for (i = 0; i < ic->nb_streams; i++) {
3668  int fps_analyze_framecount = 20;
3669  int count;
3670 
3671  st = ic->streams[i];
3672  if (!has_codec_parameters(st, NULL))
3673  break;
3674  /* If the timebase is coarse (like the usual millisecond precision
3675  * of mkv), we need to analyze more frames to reliably arrive at
3676  * the correct fps. */
3677  if (av_q2d(st->time_base) > 0.0005)
3678  fps_analyze_framecount *= 2;
3679  if (!tb_unreliable(st->internal->avctx))
3680  fps_analyze_framecount = 0;
3681  if (ic->fps_probe_size >= 0)
3682  fps_analyze_framecount = ic->fps_probe_size;
3684  fps_analyze_framecount = 0;
3685  /* variable fps and no guess at the real fps */
3686  count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3689  if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3691  if (count < fps_analyze_framecount)
3692  break;
3693  }
3694  // Look at the first 3 frames if there is evidence of frame delay
3695  // but the decoder delay is not set.
3696  if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3697  break;
3698  if (!st->internal->avctx->extradata &&
3700  st->internal->extract_extradata.bsf) &&
3702  break;
3703  if (st->internal->first_dts == AV_NOPTS_VALUE &&
3704  !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3708  break;
3709  }
3710  analyzed_all_streams = 0;
3711  if (!missing_streams || !*missing_streams)
3712  if (i == ic->nb_streams) {
3713  analyzed_all_streams = 1;
3714  /* NOTE: If the format has no header, then we need to read some
3715  * packets to get most of the streams, so we cannot stop here. */
3716  if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3717  /* If we found the info for all the codecs, we can stop. */
3718  ret = count;
3719  av_log(ic, AV_LOG_DEBUG, "All info found\n");
3720  flush_codecs = 0;
3721  break;
3722  }
3723  }
3724  /* We did not get all the codec info, but we read too much data. */
3725  if (read_size >= probesize) {
3726  ret = count;
3727  av_log(ic, AV_LOG_DEBUG,
3728  "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3729  for (i = 0; i < ic->nb_streams; i++)
3730  if (!ic->streams[i]->r_frame_rate.num &&
3731  ic->streams[i]->internal->info->duration_count <= 1 &&
3733  strcmp(ic->iformat->name, "image2"))
3734  av_log(ic, AV_LOG_WARNING,
3735  "Stream #%d: not enough frames to estimate rate; "
3736  "consider increasing probesize\n", i);
3737  break;
3738  }
3739 
3740  /* NOTE: A new stream can be added there if no header in file
3741  * (AVFMTCTX_NOHEADER). */
3742  ret = read_frame_internal(ic, pkt1);
3743  if (ret == AVERROR(EAGAIN))
3744  continue;
3745 
3746  if (ret < 0) {
3747  /* EOF or error*/
3748  eof_reached = 1;
3749  break;
3750  }
3751 
3752  if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3755  pkt1, NULL, 0);
3756  if (ret < 0)
3757  goto unref_then_goto_end;
3758 
3759  pkt = &ic->internal->packet_buffer_end->pkt;
3760  } else {
3761  pkt = pkt1;
3762  }
3763 
3764  st = ic->streams[pkt->stream_index];
3766  read_size += pkt->size;
3767 
3768  avctx = st->internal->avctx;
3769  if (!st->internal->avctx_inited) {
3771  if (ret < 0)
3772  goto unref_then_goto_end;
3773  st->internal->avctx_inited = 1;
3774  }
3775 
3776  if (pkt->dts != AV_NOPTS_VALUE && st->internal->codec_info_nb_frames > 1) {
3777  /* check for non-increasing dts */
3778  if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3779  st->internal->info->fps_last_dts >= pkt->dts) {
3780  av_log(ic, AV_LOG_DEBUG,
3781  "Non-increasing DTS in stream %d: packet %d with DTS "
3782  "%"PRId64", packet %d with DTS %"PRId64"\n",
3783  st->index, st->internal->info->fps_last_dts_idx,
3785  pkt->dts);
3786  st->internal->info->fps_first_dts =
3788  }
3789  /* Check for a discontinuity in dts. If the difference in dts
3790  * is more than 1000 times the average packet duration in the
3791  * sequence, we treat it as a discontinuity. */
3792  if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3794  (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3795  (st->internal->info->fps_last_dts - (uint64_t)st->internal->info->fps_first_dts) /
3797  av_log(ic, AV_LOG_WARNING,
3798  "DTS discontinuity in stream %d: packet %d with DTS "
3799  "%"PRId64", packet %d with DTS %"PRId64"\n",
3800  st->index, st->internal->info->fps_last_dts_idx,
3802  pkt->dts);
3803  st->internal->info->fps_first_dts =
3805  }
3806 
3807  /* update stored dts values */
3808  if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3809  st->internal->info->fps_first_dts = pkt->dts;
3811  }
3812  st->internal->info->fps_last_dts = pkt->dts;
3814  }
3815  if (st->internal->codec_info_nb_frames>1) {
3816  int64_t t = 0;
3817  int64_t limit;
3818 
3819  if (st->time_base.den > 0)
3821  if (st->avg_frame_rate.num > 0)
3823 
3824  if ( t == 0
3825  && st->internal->codec_info_nb_frames>30
3827  && st->internal->info->fps_last_dts != AV_NOPTS_VALUE) {
3828  int64_t dur = av_sat_sub64(st->internal->info->fps_last_dts, st->internal->info->fps_first_dts);
3829  t = FFMAX(t, av_rescale_q(dur, st->time_base, AV_TIME_BASE_Q));
3830  }
3831 
3832  if (analyzed_all_streams) limit = max_analyze_duration;
3833  else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3834  else limit = max_stream_analyze_duration;
3835 
3836  if (t >= limit) {
3837  av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3838  limit,
3839  t, pkt->stream_index);
3840  if (ic->flags & AVFMT_FLAG_NOBUFFER)
3841  av_packet_unref(pkt1);
3842  break;
3843  }
3844  if (pkt->duration) {
3846  && (uint64_t)pkt->pts - st->start_time < INT64_MAX
3847  ) {
3849  } else
3852  ? st->internal->parser->repeat_pict + 1 : 2;
3853  }
3854  }
3855  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3856 #if FF_API_R_FRAME_RATE
3857  ff_rfps_add_frame(ic, st, pkt->dts);
3858 #endif
3859  if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3861  }
3862  if (!st->internal->avctx->extradata) {
3863  ret = extract_extradata(ic, st, pkt);
3864  if (ret < 0)
3865  goto unref_then_goto_end;
3866  }
3867 
3868  /* If still no information, we try to open the codec and to
3869  * decompress the frame. We try to avoid that in most cases as
3870  * it takes longer and uses more memory. For MPEG-4, we need to
3871  * decompress for QuickTime.
3872  *
3873  * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3874  * least one frame of codec data, this makes sure the codec initializes
3875  * the channel configuration and does not only trust the values from
3876  * the container. */
3877  try_decode_frame(ic, st, pkt,
3878  (options && i < orig_nb_streams) ? &options[i] : NULL);
3879 
3880  if (ic->flags & AVFMT_FLAG_NOBUFFER)
3881  av_packet_unref(pkt1);
3882 
3884  count++;
3885  }
3886 
3887  if (eof_reached) {
3888  int stream_index;
3889  for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3890  st = ic->streams[stream_index];
3891  avctx = st->internal->avctx;
3892  if (!has_codec_parameters(st, NULL)) {
3893  const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3894  if (codec && !avctx->codec) {
3895  AVDictionary *opts = NULL;
3896  if (ic->codec_whitelist)
3897  av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3898  if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3899  av_log(ic, AV_LOG_WARNING,
3900  "Failed to open codec in %s\n",__FUNCTION__);
3901  av_dict_free(&opts);
3902  }
3903  }
3904 
3905  // EOF already reached while reading the stream above.
3906  // So continue with reoordering DTS with whatever delay we have.
3908  update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
3909  }
3910  }
3911  }
3912 
3913  if (flush_codecs) {
3914  AVPacket *empty_pkt = ic->internal->pkt;
3915  int err = 0;
3916  av_packet_unref(empty_pkt);
3917 
3918  for (i = 0; i < ic->nb_streams; i++) {
3919 
3920  st = ic->streams[i];
3921 
3922  /* flush the decoders */
3923  if (st->internal->info->found_decoder == 1) {
3924  do {
3925  err = try_decode_frame(ic, st, empty_pkt,
3926  (options && i < orig_nb_streams)
3927  ? &options[i] : NULL);
3928  } while (err > 0 && !has_codec_parameters(st, NULL));
3929 
3930  if (err < 0) {
3931  av_log(ic, AV_LOG_INFO,
3932  "decoding for stream %d failed\n", st->index);
3933  }
3934  }
3935  }
3936  }
3937 
3938  ff_rfps_calculate(ic);
3939 
3940  for (i = 0; i < ic->nb_streams; i++) {
3941  st = ic->streams[i];
3942  avctx = st->internal->avctx;
3943  if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3944  if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
3945  uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
3947  avctx->codec_tag= tag;
3948  }
3949 
3950  /* estimate average framerate if not set by demuxer */
3952  !st->avg_frame_rate.num &&
3954  int best_fps = 0;
3955  double best_error = 0.01;
3956  AVRational codec_frame_rate = avctx->framerate;
3957 
3958  if (st->internal->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3959  st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3960  st->internal->info->codec_info_duration < 0)
3961  continue;
3963  st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3964  st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3965 
3966  /* Round guessed framerate to a "standard" framerate if it's
3967  * within 1% of the original estimate. */
3968  for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3969  AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3970  double error = fabs(av_q2d(st->avg_frame_rate) /
3971  av_q2d(std_fps) - 1);
3972 
3973  if (error < best_error) {
3974  best_error = error;
3975  best_fps = std_fps.num;
3976  }
3977 
3978  if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
3979  error = fabs(av_q2d(codec_frame_rate) /
3980  av_q2d(std_fps) - 1);
3981  if (error < best_error) {
3982  best_error = error;
3983  best_fps = std_fps.num;
3984  }
3985  }
3986  }
3987  if (best_fps)
3989  best_fps, 12 * 1001, INT_MAX);
3990  }
3991 
3992  if (!st->r_frame_rate.num) {
3993  if ( avctx->time_base.den * (int64_t) st->time_base.num
3994  <= avctx->time_base.num * (uint64_t)avctx->ticks_per_frame * st->time_base.den) {
3996  avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
3997  } else {
3998  st->r_frame_rate.num = st->time_base.den;
3999  st->r_frame_rate.den = st->time_base.num;
4000  }
4001  }
4003  AVRational hw_ratio = { avctx->height, avctx->width };
4005  hw_ratio);
4006  }
4007  } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4008  if (!avctx->bits_per_coded_sample)
4009  avctx->bits_per_coded_sample =
4011  // set stream disposition based on audio service type
4012  switch (avctx->audio_service_type) {
4015  break;
4018  break;
4021  break;
4024  break;
4027  break;
4028  }
4029  }
4030  }
4031 
4032  if (probesize)
4033  estimate_timings(ic, old_offset);
4034 
4035  av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4036 
4037  if (ret >= 0 && ic->nb_streams)
4038  /* We could not have all the codec parameters before EOF. */
4039  ret = -1;
4040  for (i = 0; i < ic->nb_streams; i++) {
4041  const char *errmsg;
4042  st = ic->streams[i];
4043 
4044  /* if no packet was ever seen, update context now for has_codec_parameters */
4045  if (!st->internal->avctx_inited) {
4046  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4048  st->codecpar->format = st->internal->avctx->sample_fmt;
4050  if (ret < 0)
4051  goto find_stream_info_err;
4052  }
4053  if (!has_codec_parameters(st, &errmsg)) {
4054  char buf[256];
4055  avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4056  av_log(ic, AV_LOG_WARNING,
4057  "Could not find codec parameters for stream %d (%s): %s\n"
4058  "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4059  i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4060  } else {
4061  ret = 0;
4062  }
4063  }
4064 
4065  ret = compute_chapters_end(ic);
4066  if (ret < 0)
4067  goto find_stream_info_err;
4068 
4069  /* update the stream parameters from the internal codec contexts */
4070  for (i = 0; i < ic->nb_streams; i++) {
4071  st = ic->streams[i];
4072 
4073  if (st->internal->avctx_inited) {
4075  if (ret < 0)
4076  goto find_stream_info_err;
4077  ret =