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