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