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