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