FFmpeg  2.8.15
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules 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 #include <stdarg.h>
23 #include <stdint.h>
24 
25 #include "config.h"
26 
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/parseutils.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/time.h"
36 #include "libavutil/timestamp.h"
37 
38 #include "libavcodec/bytestream.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/raw.h"
41 
42 #include "audiointerleave.h"
43 #include "avformat.h"
44 #include "avio_internal.h"
45 #include "id3v2.h"
46 #include "internal.h"
47 #include "metadata.h"
48 #if CONFIG_NETWORK
49 #include "network.h"
50 #endif
51 #include "riff.h"
52 #include "url.h"
53 
54 #include "libavutil/ffversion.h"
55 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
56 
57 /**
58  * @file
59  * various utility functions for use within FFmpeg
60  */
61 
62 unsigned avformat_version(void)
63 {
66 }
67 
68 const char *avformat_configuration(void)
69 {
70  return FFMPEG_CONFIGURATION;
71 }
72 
73 const char *avformat_license(void)
74 {
75 #define LICENSE_PREFIX "libavformat license: "
76  return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
77 }
78 
79 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
80 
81 static int is_relative(int64_t ts) {
82  return ts > (RELATIVE_TS_BASE - (1LL<<48));
83 }
84 
85 /**
86  * Wrap a given time stamp, if there is an indication for an overflow
87  *
88  * @param st stream
89  * @param timestamp the time stamp to wrap
90  * @return resulting time stamp
91  */
92 static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
93 {
95  st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
97  timestamp < st->pts_wrap_reference)
98  return timestamp + (1ULL << st->pts_wrap_bits);
99  else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
100  timestamp >= st->pts_wrap_reference)
101  return timestamp - (1ULL << st->pts_wrap_bits);
102  }
103  return timestamp;
104 }
105 
106 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
107 MAKE_ACCESSORS(AVStream, stream, char *, recommended_encoder_configuration)
108 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
109 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
110 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
111 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
112 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
113 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
114 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
115 MAKE_ACCESSORS(AVFormatContext, format, AVOpenCallback, open_cb)
116 
117 int64_t av_stream_get_end_pts(const AVStream *st)
118 {
119  if (st->priv_pts) {
120  return st->priv_pts->val;
121  } else
122  return AV_NOPTS_VALUE;
123 }
124 
126 {
127  return st->parser;
128 }
129 
131 {
132  int i;
134  for (i = 0; i < s->nb_streams; i++) {
135  AVStream *st = s->streams[i];
136  st->inject_global_side_data = 1;
137  }
138 }
139 
141 {
143  dst-> codec_whitelist = av_strdup(src->codec_whitelist);
145  if ( (src-> codec_whitelist && !dst-> codec_whitelist)
146  || (src->format_whitelist && !dst->format_whitelist)) {
147  av_log(dst, AV_LOG_ERROR, "Failed to duplicate whitelist\n");
148  return AVERROR(ENOMEM);
149  }
150  return 0;
151 }
152 
154 {
155  if (st->codec->codec)
156  return st->codec->codec;
157 
158  switch (st->codec->codec_type) {
159  case AVMEDIA_TYPE_VIDEO:
160  if (s->video_codec) return s->video_codec;
161  break;
162  case AVMEDIA_TYPE_AUDIO:
163  if (s->audio_codec) return s->audio_codec;
164  break;
166  if (s->subtitle_codec) return s->subtitle_codec;
167  break;
168  }
169 
170  return avcodec_find_decoder(codec_id);
171 }
172 
174 {
175  return s->probe_score;
176 }
177 
178 /* an arbitrarily chosen "sane" max packet size -- 50M */
179 #define SANE_CHUNK_SIZE (50000000)
180 
182 {
183  if (s->maxsize>= 0) {
184  int64_t remaining= s->maxsize - avio_tell(s);
185  if (remaining < size) {
186  int64_t newsize = avio_size(s);
187  if (!s->maxsize || s->maxsize<newsize)
188  s->maxsize = newsize - !newsize;
189  remaining= s->maxsize - avio_tell(s);
190  remaining= FFMAX(remaining, 0);
191  }
192 
193  if (s->maxsize>= 0 && remaining+1 < size) {
194  av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
195  size = remaining+1;
196  }
197  }
198  return size;
199 }
200 
201 /* Read the data in sane-sized chunks and append to pkt.
202  * Return the number of bytes read or an error. */
204 {
205  int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
206  int orig_size = pkt->size;
207  int ret;
208 
209  do {
210  int prev_size = pkt->size;
211  int read_size;
212 
213  /* When the caller requests a lot of data, limit it to the amount
214  * left in file or SANE_CHUNK_SIZE when it is not known. */
215  read_size = size;
216  if (read_size > SANE_CHUNK_SIZE/10) {
217  read_size = ffio_limit(s, read_size);
218  // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
219  if (s->maxsize < 0)
220  read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
221  }
222 
223  ret = av_grow_packet(pkt, read_size);
224  if (ret < 0)
225  break;
226 
227  ret = avio_read(s, pkt->data + prev_size, read_size);
228  if (ret != read_size) {
229  av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
230  break;
231  }
232 
233  size -= read_size;
234  } while (size > 0);
235  if (size > 0)
236  pkt->flags |= AV_PKT_FLAG_CORRUPT;
237 
238  pkt->pos = orig_pos;
239  if (!pkt->size)
240  av_free_packet(pkt);
241  return pkt->size > orig_size ? pkt->size - orig_size : ret;
242 }
243 
245 {
246  av_init_packet(pkt);
247  pkt->data = NULL;
248  pkt->size = 0;
249  pkt->pos = avio_tell(s);
250 
251  return append_packet_chunked(s, pkt, size);
252 }
253 
255 {
256  if (!pkt->size)
257  return av_get_packet(s, pkt, size);
258  return append_packet_chunked(s, pkt, size);
259 }
260 
261 int av_filename_number_test(const char *filename)
262 {
263  char buf[1024];
264  return filename &&
265  (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
266 }
267 
269  AVProbeData *pd)
270 {
271  static const struct {
272  const char *name;
273  enum AVCodecID id;
274  enum AVMediaType type;
275  } fmt_id_type[] = {
286  { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
287  { 0 }
288  };
289  int score;
290  AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
291 
292  if (fmt && st->request_probe <= score) {
293  int i;
294  av_log(s, AV_LOG_DEBUG,
295  "Probe with size=%d, packets=%d detected %s with score=%d\n",
297  fmt->name, score);
298  for (i = 0; fmt_id_type[i].name; i++) {
299  if (!strcmp(fmt->name, fmt_id_type[i].name)) {
300  st->codec->codec_id = fmt_id_type[i].id;
301  st->codec->codec_type = fmt_id_type[i].type;
302  return score;
303  }
304  }
305  }
306  return 0;
307 }
308 
309 /************************************************************/
310 /* input media file */
311 
313  int err;
314 
315  if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
316  av_log(ic, AV_LOG_ERROR, "Format not on whitelist\n");
317  return AVERROR(EINVAL);
318  }
319 
320  if (ic->iformat->read_header) {
321  err = ic->iformat->read_header(ic);
322  if (err < 0)
323  return err;
324  }
325 
326  if (ic->pb && !ic->internal->data_offset)
327  ic->internal->data_offset = avio_tell(ic->pb);
328 
329  return 0;
330 }
331 
332 /* Open input file and probe the format if necessary. */
333 static int init_input(AVFormatContext *s, const char *filename,
335 {
336  int ret;
337  AVProbeData pd = { filename, NULL, 0 };
338  int score = AVPROBE_SCORE_RETRY;
339 
340  if (s->pb) {
342  if (!s->iformat)
343  return av_probe_input_buffer2(s->pb, &s->iformat, filename,
344  s, 0, s->format_probesize);
345  else if (s->iformat->flags & AVFMT_NOFILE)
346  av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
347  "will be ignored with AVFMT_NOFILE format.\n");
348  return 0;
349  }
350 
351  if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
352  (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
353  return score;
354 
355  if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
356  &s->interrupt_callback, options)) < 0)
357  return ret;
358  if (s->iformat)
359  return 0;
360  return av_probe_input_buffer2(s->pb, &s->iformat, filename,
361  s, 0, s->format_probesize);
362 }
363 
364 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
365  AVPacketList **plast_pktl)
366 {
367  AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
368  if (!pktl)
369  return NULL;
370 
371  if (*packet_buffer)
372  (*plast_pktl)->next = pktl;
373  else
374  *packet_buffer = pktl;
375 
376  /* Add the packet in the buffered packet list. */
377  *plast_pktl = pktl;
378  pktl->pkt = *pkt;
379  return &pktl->pkt;
380 }
381 
383 {
384  int i;
385  for (i = 0; i < s->nb_streams; i++)
387  s->streams[i]->discard < AVDISCARD_ALL) {
389  if (copy.size <= 0) {
391  "Attached picture on stream %d has invalid size, "
392  "ignoring\n", i);
393  continue;
394  }
395  copy.buf = av_buffer_ref(copy.buf);
396  if (!copy.buf)
397  return AVERROR(ENOMEM);
398 
401  }
402  return 0;
403 }
404 
405 int avformat_open_input(AVFormatContext **ps, const char *filename,
407 {
408  AVFormatContext *s = *ps;
409  int ret = 0;
410  AVDictionary *tmp = NULL;
411  ID3v2ExtraMeta *id3v2_extra_meta = NULL;
412 
413  if (!s && !(s = avformat_alloc_context()))
414  return AVERROR(ENOMEM);
415  if (!s->av_class) {
416  av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
417  return AVERROR(EINVAL);
418  }
419  if (fmt)
420  s->iformat = fmt;
421 
422  if (options)
423  av_dict_copy(&tmp, *options, 0);
424 
425  if (s->pb) // must be before any goto fail
427 
428  if ((ret = av_opt_set_dict(s, &tmp)) < 0)
429  goto fail;
430 
431  if ((ret = init_input(s, filename, &tmp)) < 0)
432  goto fail;
433  s->probe_score = ret;
434 
435  if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
436  av_log(s, AV_LOG_ERROR, "Format not on whitelist\n");
437  ret = AVERROR(EINVAL);
438  goto fail;
439  }
440 
442 
443  /* Check filename in case an image number is expected. */
444  if (s->iformat->flags & AVFMT_NEEDNUMBER) {
445  if (!av_filename_number_test(filename)) {
446  ret = AVERROR(EINVAL);
447  goto fail;
448  }
449  }
450 
452  av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
453 
454  /* Allocate private data. */
455  if (s->iformat->priv_data_size > 0) {
456  if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
457  ret = AVERROR(ENOMEM);
458  goto fail;
459  }
460  if (s->iformat->priv_class) {
461  *(const AVClass **) s->priv_data = s->iformat->priv_class;
463  if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
464  goto fail;
465  }
466  }
467 
468  /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
469  if (s->pb)
470  ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, 0);
471 
472  if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
473  if ((ret = s->iformat->read_header(s)) < 0)
474  goto fail;
475 
476  if (id3v2_extra_meta) {
477  if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
478  !strcmp(s->iformat->name, "tta")) {
479  if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
480  goto fail;
481  } else
482  av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
483  }
484  ff_id3v2_free_extra_meta(&id3v2_extra_meta);
485 
486  if ((ret = avformat_queue_attached_pictures(s)) < 0)
487  goto fail;
488 
489  if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
490  s->internal->data_offset = avio_tell(s->pb);
491 
493 
494  if (options) {
495  av_dict_free(options);
496  *options = tmp;
497  }
498  *ps = s;
499  return 0;
500 
501 fail:
502  ff_id3v2_free_extra_meta(&id3v2_extra_meta);
503  av_dict_free(&tmp);
504  if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
505  avio_closep(&s->pb);
507  *ps = NULL;
508  return ret;
509 }
510 
511 /*******************************************************/
512 
514 {
515  switch (st->codec->codec_type) {
516  case AVMEDIA_TYPE_VIDEO:
517  if (s->video_codec_id)
518  st->codec->codec_id = s->video_codec_id;
519  break;
520  case AVMEDIA_TYPE_AUDIO:
521  if (s->audio_codec_id)
522  st->codec->codec_id = s->audio_codec_id;
523  break;
525  if (s->subtitle_codec_id)
526  st->codec->codec_id = s->subtitle_codec_id;
527  break;
528  }
529 }
530 
532 {
533  if (st->request_probe>0) {
534  AVProbeData *pd = &st->probe_data;
535  int end;
536  av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
537  --st->probe_packets;
538 
539  if (pkt) {
540  uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
541  if (!new_buf) {
543  "Failed to reallocate probe buffer for stream %d\n",
544  st->index);
545  goto no_packet;
546  }
547  pd->buf = new_buf;
548  memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
549  pd->buf_size += pkt->size;
550  memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
551  } else {
552 no_packet:
553  st->probe_packets = 0;
554  if (!pd->buf_size) {
556  "nothing to probe for stream %d\n", st->index);
557  }
558  }
559 
561  || st->probe_packets<= 0;
562 
563  if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
564  int score = set_codec_from_probe_data(s, st, pd);
566  || end) {
567  pd->buf_size = 0;
568  av_freep(&pd->buf);
569  st->request_probe = -1;
570  if (st->codec->codec_id != AV_CODEC_ID_NONE) {
571  av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
572  } else
573  av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
574  }
575  force_codec_ids(s, st);
576  }
577  }
578  return 0;
579 }
580 
581 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
582 {
583  int64_t ref = pkt->dts;
584  int i, pts_wrap_behavior;
585  int64_t pts_wrap_reference;
586  AVProgram *first_program;
587 
588  if (ref == AV_NOPTS_VALUE)
589  ref = pkt->pts;
590  if (st->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
591  return 0;
592  ref &= (1LL << st->pts_wrap_bits)-1;
593 
594  // reference time stamp should be 60 s before first time stamp
595  pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
596  // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
597  pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
598  (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
600 
601  first_program = av_find_program_from_stream(s, NULL, stream_index);
602 
603  if (!first_program) {
604  int default_stream_index = av_find_default_stream_index(s);
605  if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {
606  for (i = 0; i < s->nb_streams; i++) {
608  continue;
609  s->streams[i]->pts_wrap_reference = pts_wrap_reference;
610  s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;
611  }
612  }
613  else {
614  st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;
615  st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;
616  }
617  }
618  else {
619  AVProgram *program = first_program;
620  while (program) {
621  if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
622  pts_wrap_reference = program->pts_wrap_reference;
623  pts_wrap_behavior = program->pts_wrap_behavior;
624  break;
625  }
626  program = av_find_program_from_stream(s, program, stream_index);
627  }
628 
629  // update every program with differing pts_wrap_reference
630  program = first_program;
631  while (program) {
632  if (program->pts_wrap_reference != pts_wrap_reference) {
633  for (i = 0; i<program->nb_stream_indexes; i++) {
634  s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;
635  s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;
636  }
637 
638  program->pts_wrap_reference = pts_wrap_reference;
639  program->pts_wrap_behavior = pts_wrap_behavior;
640  }
641  program = av_find_program_from_stream(s, program, stream_index);
642  }
643  }
644  return 1;
645 }
646 
648 {
649  int ret, i, err;
650  AVStream *st;
651 
652  for (;;) {
654 
655  if (pktl) {
656  *pkt = pktl->pkt;
657  st = s->streams[pkt->stream_index];
659  if ((err = probe_codec(s, st, NULL)) < 0)
660  return err;
661  if (st->request_probe <= 0) {
662  s->internal->raw_packet_buffer = pktl->next;
664  av_free(pktl);
665  return 0;
666  }
667  }
668 
669  pkt->data = NULL;
670  pkt->size = 0;
671  av_init_packet(pkt);
672  ret = s->iformat->read_packet(s, pkt);
673  if (ret < 0) {
674  if (!pktl || ret == AVERROR(EAGAIN))
675  return ret;
676  for (i = 0; i < s->nb_streams; i++) {
677  st = s->streams[i];
678  if (st->probe_packets || st->request_probe > 0)
679  if ((err = probe_codec(s, st, NULL)) < 0)
680  return err;
681  av_assert0(st->request_probe <= 0);
682  }
683  continue;
684  }
685 
686  if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
687  (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
689  "Dropped corrupted packet (stream = %d)\n",
690  pkt->stream_index);
691  av_free_packet(pkt);
692  continue;
693  }
694 
695  if (pkt->stream_index >= (unsigned)s->nb_streams) {
696  av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
697  continue;
698  }
699 
700  st = s->streams[pkt->stream_index];
701 
703  // correct first time stamps to negative values
704  if (!is_relative(st->first_dts))
705  st->first_dts = wrap_timestamp(st, st->first_dts);
706  if (!is_relative(st->start_time))
707  st->start_time = wrap_timestamp(st, st->start_time);
708  if (!is_relative(st->cur_dts))
709  st->cur_dts = wrap_timestamp(st, st->cur_dts);
710  }
711 
712  pkt->dts = wrap_timestamp(st, pkt->dts);
713  pkt->pts = wrap_timestamp(st, pkt->pts);
714 
715  force_codec_ids(s, st);
716 
717  /* TODO: audio: time filter; video: frame reordering (pts != dts) */
719  pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
720 
721  if (!pktl && st->request_probe <= 0)
722  return ret;
723 
727 
728  if ((err = probe_codec(s, st, pkt)) < 0)
729  return err;
730  }
731 }
732 
733 
734 /**********************************************************/
735 
737 {
738  if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
739  avctx->codec_id == AV_CODEC_ID_MP1 ||
740  avctx->codec_id == AV_CODEC_ID_MP2 ||
741  avctx->codec_id == AV_CODEC_ID_MP3/* ||
742  avctx->codec_id == AV_CODEC_ID_CELT*/)
743  return 1;
744  return 0;
745 }
746 
747 /**
748  * Return the frame duration in seconds. Return 0 if not available.
749  */
750 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
752 {
753  AVRational codec_framerate = s->iformat ? st->codec->framerate :
754  av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
755  int frame_size;
756 
757  *pnum = 0;
758  *pden = 0;
759  switch (st->codec->codec_type) {
760  case AVMEDIA_TYPE_VIDEO:
761  if (st->r_frame_rate.num && !pc && s->iformat) {
762  *pnum = st->r_frame_rate.den;
763  *pden = st->r_frame_rate.num;
764  } else if (st->time_base.num * 1000LL > st->time_base.den) {
765  *pnum = st->time_base.num;
766  *pden = st->time_base.den;
767  } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
769  av_reduce(pnum, pden,
770  codec_framerate.den,
771  codec_framerate.num * (int64_t)st->codec->ticks_per_frame,
772  INT_MAX);
773 
774  if (pc && pc->repeat_pict) {
775  av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
776  av_reduce(pnum, pden,
777  (*pnum) * (1LL + pc->repeat_pict),
778  (*pden),
779  INT_MAX);
780  }
781  /* If this codec can be interlaced or progressive then we need
782  * a parser to compute duration of a packet. Thus if we have
783  * no parser in such case leave duration undefined. */
784  if (st->codec->ticks_per_frame > 1 && !pc)
785  *pnum = *pden = 0;
786  }
787  break;
788  case AVMEDIA_TYPE_AUDIO:
789  frame_size = av_get_audio_frame_duration(st->codec, pkt->size);
790  if (frame_size <= 0 || st->codec->sample_rate <= 0)
791  break;
792  *pnum = frame_size;
793  *pden = st->codec->sample_rate;
794  break;
795  default:
796  break;
797  }
798 }
799 
800 static int is_intra_only(AVCodecContext *enc) {
801  const AVCodecDescriptor *desc;
802 
803  if (enc->codec_type != AVMEDIA_TYPE_VIDEO)
804  return 1;
805 
806  desc = av_codec_get_codec_descriptor(enc);
807  if (!desc) {
808  desc = avcodec_descriptor_get(enc->codec_id);
810  }
811  if (desc)
812  return !!(desc->props & AV_CODEC_PROP_INTRA_ONLY);
813  return 0;
814 }
815 
817 {
818  if (st->codec->codec_id != AV_CODEC_ID_H264) return 1;
819  if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
820  return 1;
821 #if CONFIG_H264_DECODER
822  if (st->codec->has_b_frames &&
824  return 1;
825 #endif
826  if (st->codec->has_b_frames<3)
827  return st->nb_decoded_frames >= 7;
828  else if (st->codec->has_b_frames<4)
829  return st->nb_decoded_frames >= 18;
830  else
831  return st->nb_decoded_frames >= 20;
832 }
833 
835 {
836  if (pktl->next)
837  return pktl->next;
838  if (pktl == s->internal->packet_buffer_end)
839  return s->internal->parse_queue;
840  return NULL;
841 }
842 
843 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
844  int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
846 
847  if(!onein_oneout) {
848  int delay = st->codec->has_b_frames;
849  int i;
850 
851  if (dts == AV_NOPTS_VALUE) {
852  int64_t best_score = INT64_MAX;
853  for (i = 0; i<delay; i++) {
854  if (st->pts_reorder_error_count[i]) {
855  int64_t score = st->pts_reorder_error[i] / st->pts_reorder_error_count[i];
856  if (score < best_score) {
857  best_score = score;
858  dts = pts_buffer[i];
859  }
860  }
861  }
862  } else {
863  for (i = 0; i<delay; i++) {
864  if (pts_buffer[i] != AV_NOPTS_VALUE) {
865  int64_t diff = FFABS(pts_buffer[i] - dts)
866  + (uint64_t)st->pts_reorder_error[i];
867  diff = FFMAX(diff, st->pts_reorder_error[i]);
868  st->pts_reorder_error[i] = diff;
869  st->pts_reorder_error_count[i]++;
870  if (st->pts_reorder_error_count[i] > 250) {
871  st->pts_reorder_error[i] >>= 1;
872  st->pts_reorder_error_count[i] >>= 1;
873  }
874  }
875  }
876  }
877  }
878 
879  if (dts == AV_NOPTS_VALUE)
880  dts = pts_buffer[0];
881 
882  return dts;
883 }
884 
885 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
886  int64_t dts, int64_t pts, AVPacket *pkt)
887 {
888  AVStream *st = s->streams[stream_index];
890  int64_t pts_buffer[MAX_REORDER_DELAY+1];
891  int64_t shift;
892  int i, delay;
893 
894  if (st->first_dts != AV_NOPTS_VALUE ||
895  dts == AV_NOPTS_VALUE ||
896  st->cur_dts == AV_NOPTS_VALUE ||
897  st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
898  is_relative(dts))
899  return;
900 
901  delay = st->codec->has_b_frames;
902  st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
903  st->cur_dts = dts;
904  shift = st->first_dts - RELATIVE_TS_BASE;
905 
906  for (i = 0; i<MAX_REORDER_DELAY+1; i++)
907  pts_buffer[i] = AV_NOPTS_VALUE;
908 
909  if (is_relative(pts))
910  pts += shift;
911 
912  for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
913  if (pktl->pkt.stream_index != stream_index)
914  continue;
915  if (is_relative(pktl->pkt.pts))
916  pktl->pkt.pts += shift;
917 
918  if (is_relative(pktl->pkt.dts))
919  pktl->pkt.dts += shift;
920 
921  if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
922  st->start_time = pktl->pkt.pts;
923 
924  if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
925  pts_buffer[0] = pktl->pkt.pts;
926  for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
927  FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
928 
929  pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);
930  }
931  }
932 
933  if (st->start_time == AV_NOPTS_VALUE)
934  st->start_time = pts;
935 }
936 
938  int stream_index, int duration)
939 {
941  int64_t cur_dts = RELATIVE_TS_BASE;
942 
943  if (st->first_dts != AV_NOPTS_VALUE) {
945  return;
947  cur_dts = st->first_dts;
948  for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
949  if (pktl->pkt.stream_index == stream_index) {
950  if (pktl->pkt.pts != pktl->pkt.dts ||
951  pktl->pkt.dts != AV_NOPTS_VALUE ||
952  pktl->pkt.duration)
953  break;
954  cur_dts -= duration;
955  }
956  }
957  if (pktl && pktl->pkt.dts != st->first_dts) {
958  av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %d) in the queue\n",
959  av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
960  return;
961  }
962  if (!pktl) {
963  av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
964  return;
965  }
967  st->first_dts = cur_dts;
968  } else if (st->cur_dts != RELATIVE_TS_BASE)
969  return;
970 
971  for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
972  if (pktl->pkt.stream_index != stream_index)
973  continue;
974  if (pktl->pkt.pts == pktl->pkt.dts &&
975  (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&
976  !pktl->pkt.duration) {
977  pktl->pkt.dts = cur_dts;
978  if (!st->codec->has_b_frames)
979  pktl->pkt.pts = cur_dts;
980 // if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
981  pktl->pkt.duration = duration;
982  } else
983  break;
984  cur_dts = pktl->pkt.dts + pktl->pkt.duration;
985  }
986  if (!pktl)
987  st->cur_dts = cur_dts;
988 }
989 
992  int64_t next_dts, int64_t next_pts)
993 {
994  int num, den, presentation_delayed, delay, i;
995  int64_t offset;
997  int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
999 
1000  if (s->flags & AVFMT_FLAG_NOFILLIN)
1001  return;
1002 
1003  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1004  if (pkt->dts == pkt->pts && st->last_dts_for_order_check != AV_NOPTS_VALUE) {
1005  if (st->last_dts_for_order_check <= pkt->dts) {
1006  st->dts_ordered++;
1007  } else {
1009  "DTS %"PRIi64" < %"PRIi64" out of order\n",
1010  pkt->dts,
1012  st->dts_misordered++;
1013  }
1014  if (st->dts_ordered + st->dts_misordered > 250) {
1015  st->dts_ordered >>= 1;
1016  st->dts_misordered >>= 1;
1017  }
1018  }
1019 
1020  st->last_dts_for_order_check = pkt->dts;
1021  if (st->dts_ordered < 8*st->dts_misordered && pkt->dts == pkt->pts)
1022  pkt->dts = AV_NOPTS_VALUE;
1023  }
1024 
1025  if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1026  pkt->dts = AV_NOPTS_VALUE;
1027 
1028  if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1029  && !st->codec->has_b_frames)
1030  //FIXME Set low_delay = 0 when has_b_frames = 1
1031  st->codec->has_b_frames = 1;
1032 
1033  /* do we have a video B-frame ? */
1034  delay = st->codec->has_b_frames;
1035  presentation_delayed = 0;
1036 
1037  /* XXX: need has_b_frame, but cannot get it if the codec is
1038  * not initialized */
1039  if (delay &&
1040  pc && pc->pict_type != AV_PICTURE_TYPE_B)
1041  presentation_delayed = 1;
1042 
1043  if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1044  st->pts_wrap_bits < 63 &&
1045  pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1046  if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1047  pkt->dts -= 1LL << st->pts_wrap_bits;
1048  } else
1049  pkt->pts += 1LL << st->pts_wrap_bits;
1050  }
1051 
1052  /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1053  * We take the conservative approach and discard both.
1054  * Note: If this is misbehaving for an H.264 file, then possibly
1055  * presentation_delayed is not set correctly. */
1056  if (delay == 1 && pkt->dts == pkt->pts &&
1057  pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1058  av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1059  if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1060  && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1061  pkt->dts = AV_NOPTS_VALUE;
1062  }
1063 
1064  duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1065  if (pkt->duration == 0) {
1066  ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1067  if (den && num) {
1068  duration = (AVRational) {num, den};
1069  pkt->duration = av_rescale_rnd(1,
1070  num * (int64_t) st->time_base.den,
1071  den * (int64_t) st->time_base.num,
1072  AV_ROUND_DOWN);
1073  }
1074  }
1075 
1076  if (pkt->duration != 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1077  update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1078 
1079  /* Correct timestamps with byte offset if demuxers only have timestamps
1080  * on packet boundaries */
1081  if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1082  /* this will estimate bitrate based on this frame's duration and size */
1083  offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1084  if (pkt->pts != AV_NOPTS_VALUE)
1085  pkt->pts += offset;
1086  if (pkt->dts != AV_NOPTS_VALUE)
1087  pkt->dts += offset;
1088  }
1089 
1090  /* This may be redundant, but it should not hurt. */
1091  if (pkt->dts != AV_NOPTS_VALUE &&
1092  pkt->pts != AV_NOPTS_VALUE &&
1093  pkt->pts > pkt->dts)
1094  presentation_delayed = 1;
1095 
1096  if (s->debug & FF_FDEBUG_TS)
1097  av_log(s, AV_LOG_TRACE,
1098  "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%d delay:%d onein_oneout:%d\n",
1099  presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1100  pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1101 
1102  /* Interpolate PTS and DTS if they are not present. We skip H264
1103  * currently because delay and has_b_frames are not reliably set. */
1104  if ((delay == 0 || (delay == 1 && pc)) &&
1105  onein_oneout) {
1106  if (presentation_delayed) {
1107  /* DTS = decompression timestamp */
1108  /* PTS = presentation timestamp */
1109  if (pkt->dts == AV_NOPTS_VALUE)
1110  pkt->dts = st->last_IP_pts;
1111  update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1112  if (pkt->dts == AV_NOPTS_VALUE)
1113  pkt->dts = st->cur_dts;
1114 
1115  /* This is tricky: the dts must be incremented by the duration
1116  * of the frame we are displaying, i.e. the last I- or P-frame. */
1117  if (st->last_IP_duration == 0)
1118  st->last_IP_duration = pkt->duration;
1119  if (pkt->dts != AV_NOPTS_VALUE)
1120  st->cur_dts = pkt->dts + st->last_IP_duration;
1121  if (pkt->dts != AV_NOPTS_VALUE &&
1122  pkt->pts == AV_NOPTS_VALUE &&
1123  st->last_IP_duration > 0 &&
1124  ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1125  next_dts != next_pts &&
1126  next_pts != AV_NOPTS_VALUE)
1127  pkt->pts = next_dts;
1128 
1129  st->last_IP_duration = pkt->duration;
1130  st->last_IP_pts = pkt->pts;
1131  /* Cannot compute PTS if not present (we can compute it only
1132  * by knowing the future. */
1133  } else if (pkt->pts != AV_NOPTS_VALUE ||
1134  pkt->dts != AV_NOPTS_VALUE ||
1135  pkt->duration ) {
1136 
1137  /* presentation is not delayed : PTS and DTS are the same */
1138  if (pkt->pts == AV_NOPTS_VALUE)
1139  pkt->pts = pkt->dts;
1141  pkt->pts, pkt);
1142  if (pkt->pts == AV_NOPTS_VALUE)
1143  pkt->pts = st->cur_dts;
1144  pkt->dts = pkt->pts;
1145  if (pkt->pts != AV_NOPTS_VALUE)
1146  st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1147  }
1148  }
1149 
1150  if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1151  st->pts_buffer[0] = pkt->pts;
1152  for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
1153  FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
1154 
1156  pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1157  }
1158  // We skipped it above so we try here.
1159  if (!onein_oneout)
1160  // This should happen on the first packet
1161  update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1162  if (pkt->dts > st->cur_dts)
1163  st->cur_dts = pkt->dts;
1164 
1165  if (s->debug & FF_FDEBUG_TS)
1166  av_log(s, AV_LOG_TRACE, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
1167  presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1168 
1169  /* update flags */
1170  if (is_intra_only(st->codec))
1171  pkt->flags |= AV_PKT_FLAG_KEY;
1172  if (pc)
1174 }
1175 
1176 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1177 {
1178  while (*pkt_buf) {
1179  AVPacketList *pktl = *pkt_buf;
1180  *pkt_buf = pktl->next;
1181  av_free_packet(&pktl->pkt);
1182  av_freep(&pktl);
1183  }
1184  *pkt_buf_end = NULL;
1185 }
1186 
1187 /**
1188  * Parse a packet, add all split parts to parse_queue.
1189  *
1190  * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1191  */
1192 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1193 {
1194  AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1195  AVStream *st = s->streams[stream_index];
1196  uint8_t *data = pkt ? pkt->data : NULL;
1197  int size = pkt ? pkt->size : 0;
1198  int ret = 0, got_output = 0;
1199 
1200  if (!pkt) {
1202  pkt = &flush_pkt;
1203  got_output = 1;
1204  } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1205  // preserve 0-size sync packets
1207  }
1208 
1209  while (size > 0 || (pkt == &flush_pkt && got_output)) {
1210  int len;
1211  int64_t next_pts = pkt->pts;
1212  int64_t next_dts = pkt->dts;
1213 
1214  av_init_packet(&out_pkt);
1215  len = av_parser_parse2(st->parser, st->codec,
1216  &out_pkt.data, &out_pkt.size, data, size,
1217  pkt->pts, pkt->dts, pkt->pos);
1218 
1219  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1220  pkt->pos = -1;
1221  /* increment read pointer */
1222  data += len;
1223  size -= len;
1224 
1225  got_output = !!out_pkt.size;
1226 
1227  if (!out_pkt.size)
1228  continue;
1229 
1230  if (pkt->side_data) {
1231  out_pkt.side_data = pkt->side_data;
1232  out_pkt.side_data_elems = pkt->side_data_elems;
1233  pkt->side_data = NULL;
1234  pkt->side_data_elems = 0;
1235  }
1236 
1237  /* set the duration */
1238  out_pkt.duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1240  if (st->codec->sample_rate > 0) {
1241  out_pkt.duration =
1243  (AVRational) { 1, st->codec->sample_rate },
1244  st->time_base,
1245  AV_ROUND_DOWN);
1246  }
1247  }
1248 
1249  out_pkt.stream_index = st->index;
1250  out_pkt.pts = st->parser->pts;
1251  out_pkt.dts = st->parser->dts;
1252  out_pkt.pos = st->parser->pos;
1253 
1255  out_pkt.pos = st->parser->frame_offset;
1256 
1257  if (st->parser->key_frame == 1 ||
1258  (st->parser->key_frame == -1 &&
1260  out_pkt.flags |= AV_PKT_FLAG_KEY;
1261 
1262  if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1263  out_pkt.flags |= AV_PKT_FLAG_KEY;
1264 
1265  compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);
1266 
1267  if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1268  out_pkt.buf = pkt->buf;
1269  pkt->buf = NULL;
1270 #if FF_API_DESTRUCT_PACKET
1272  out_pkt.destruct = pkt->destruct;
1273  pkt->destruct = NULL;
1275 #endif
1276  }
1277  if ((ret = av_dup_packet(&out_pkt)) < 0)
1278  goto fail;
1279 
1280  if (!add_to_pktbuf(&s->internal->parse_queue, &out_pkt, &s->internal->parse_queue_end)) {
1281  av_free_packet(&out_pkt);
1282  ret = AVERROR(ENOMEM);
1283  goto fail;
1284  }
1285  }
1286 
1287  /* end of the stream => close and free the parser */
1288  if (pkt == &flush_pkt) {
1289  av_parser_close(st->parser);
1290  st->parser = NULL;
1291  }
1292 
1293 fail:
1294  av_free_packet(pkt);
1295  return ret;
1296 }
1297 
1298 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1299  AVPacketList **pkt_buffer_end,
1300  AVPacket *pkt)
1301 {
1302  AVPacketList *pktl;
1303  av_assert0(*pkt_buffer);
1304  pktl = *pkt_buffer;
1305  *pkt = pktl->pkt;
1306  *pkt_buffer = pktl->next;
1307  if (!pktl->next)
1308  *pkt_buffer_end = NULL;
1309  av_freep(&pktl);
1310  return 0;
1311 }
1312 
1313 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1314 {
1315  return av_rescale(ts, st->time_base.num * st->codec->sample_rate, st->time_base.den);
1316 }
1317 
1319 {
1320  int ret = 0, i, got_packet = 0;
1321  AVDictionary *metadata = NULL;
1322 
1323  av_init_packet(pkt);
1324 
1325  while (!got_packet && !s->internal->parse_queue) {
1326  AVStream *st;
1327  AVPacket cur_pkt;
1328 
1329  /* read next packet */
1330  ret = ff_read_packet(s, &cur_pkt);
1331  if (ret < 0) {
1332  if (ret == AVERROR(EAGAIN))
1333  return ret;
1334  /* flush the parsers */
1335  for (i = 0; i < s->nb_streams; i++) {
1336  st = s->streams[i];
1337  if (st->parser && st->need_parsing)
1338  parse_packet(s, NULL, st->index);
1339  }
1340  /* all remaining packets are now in parse_queue =>
1341  * really terminate parsing */
1342  break;
1343  }
1344  ret = 0;
1345  st = s->streams[cur_pkt.stream_index];
1346 
1347  if (cur_pkt.pts != AV_NOPTS_VALUE &&
1348  cur_pkt.dts != AV_NOPTS_VALUE &&
1349  cur_pkt.pts < cur_pkt.dts) {
1351  "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1352  cur_pkt.stream_index,
1353  av_ts2str(cur_pkt.pts),
1354  av_ts2str(cur_pkt.dts),
1355  cur_pkt.size);
1356  }
1357  if (s->debug & FF_FDEBUG_TS)
1358  av_log(s, AV_LOG_DEBUG,
1359  "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
1360  cur_pkt.stream_index,
1361  av_ts2str(cur_pkt.pts),
1362  av_ts2str(cur_pkt.dts),
1363  cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1364 
1365  if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1366  st->parser = av_parser_init(st->codec->codec_id);
1367  if (!st->parser) {
1368  av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1369  "%s, packets or times may be invalid.\n",
1371  /* no parser available: just output the raw packets */
1373  } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1375  else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1376  st->parser->flags |= PARSER_FLAG_ONCE;
1377  else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1379  }
1380 
1381  if (!st->need_parsing || !st->parser) {
1382  /* no parsing needed: we just output the packet as is */
1383  *pkt = cur_pkt;
1385  if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1386  (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1387  ff_reduce_index(s, st->index);
1388  av_add_index_entry(st, pkt->pos, pkt->dts,
1389  0, 0, AVINDEX_KEYFRAME);
1390  }
1391  got_packet = 1;
1392  } else if (st->discard < AVDISCARD_ALL) {
1393  if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1394  return ret;
1395  } else {
1396  /* free packet */
1397  av_free_packet(&cur_pkt);
1398  }
1399  if (pkt->flags & AV_PKT_FLAG_KEY)
1400  st->skip_to_keyframe = 0;
1401  if (st->skip_to_keyframe) {
1402  av_free_packet(&cur_pkt);
1403  if (got_packet) {
1404  *pkt = cur_pkt;
1405  }
1406  got_packet = 0;
1407  }
1408  }
1409 
1410  if (!got_packet && s->internal->parse_queue)
1412 
1413  if (ret >= 0) {
1414  AVStream *st = s->streams[pkt->stream_index];
1415  int discard_padding = 0;
1416  if (st->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1417  int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1418  int64_t sample = ts_to_samples(st, pts);
1419  int duration = ts_to_samples(st, pkt->duration);
1420  int64_t end_sample = sample + duration;
1421  if (duration > 0 && end_sample >= st->first_discard_sample &&
1422  sample < st->last_discard_sample)
1423  discard_padding = FFMIN(end_sample - st->first_discard_sample, duration);
1424  }
1425  if (st->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1426  st->skip_samples = st->start_skip_samples;
1427  if (st->skip_samples || discard_padding) {
1429  if (p) {
1430  AV_WL32(p, st->skip_samples);
1431  AV_WL32(p + 4, discard_padding);
1432  av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->skip_samples, discard_padding);
1433  }
1434  st->skip_samples = 0;
1435  }
1436 
1437  if (st->inject_global_side_data) {
1438  for (i = 0; i < st->nb_side_data; i++) {
1439  AVPacketSideData *src_sd = &st->side_data[i];
1440  uint8_t *dst_data;
1441 
1442  if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1443  continue;
1444 
1445  dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1446  if (!dst_data) {
1447  av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1448  continue;
1449  }
1450 
1451  memcpy(dst_data, src_sd->data, src_sd->size);
1452  }
1453  st->inject_global_side_data = 0;
1454  }
1455 
1456  if (!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
1458  }
1459 
1460  av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1461  if (metadata) {
1463  av_dict_copy(&s->metadata, metadata, 0);
1464  av_dict_free(&metadata);
1466  }
1467 
1468  if (s->debug & FF_FDEBUG_TS)
1469  av_log(s, AV_LOG_DEBUG,
1470  "read_frame_internal stream=%d, pts=%s, dts=%s, "
1471  "size=%d, duration=%d, flags=%d\n",
1472  pkt->stream_index,
1473  av_ts2str(pkt->pts),
1474  av_ts2str(pkt->dts),
1475  pkt->size, pkt->duration, pkt->flags);
1476 
1477  return ret;
1478 }
1479 
1481 {
1482  const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1483  int eof = 0;
1484  int ret;
1485  AVStream *st;
1486 
1487  if (!genpts) {
1488  ret = s->internal->packet_buffer
1490  &s->internal->packet_buffer_end, pkt)
1491  : read_frame_internal(s, pkt);
1492  if (ret < 0)
1493  return ret;
1494  goto return_packet;
1495  }
1496 
1497  for (;;) {
1498  AVPacketList *pktl = s->internal->packet_buffer;
1499 
1500  if (pktl) {
1501  AVPacket *next_pkt = &pktl->pkt;
1502 
1503  if (next_pkt->dts != AV_NOPTS_VALUE) {
1504  int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1505  // last dts seen for this stream. if any of packets following
1506  // current one had no dts, we will set this to AV_NOPTS_VALUE.
1507  int64_t last_dts = next_pkt->dts;
1508  av_assert2(wrap_bits <= 64);
1509  while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1510  if (pktl->pkt.stream_index == next_pkt->stream_index &&
1511  av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1512  if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1513  // not B-frame
1514  next_pkt->pts = pktl->pkt.dts;
1515  }
1516  if (last_dts != AV_NOPTS_VALUE) {
1517  // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1518  last_dts = pktl->pkt.dts;
1519  }
1520  }
1521  pktl = pktl->next;
1522  }
1523  if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1524  // Fixing the last reference frame had none pts issue (For MXF etc).
1525  // We only do this when
1526  // 1. eof.
1527  // 2. we are not able to resolve a pts value for current packet.
1528  // 3. the packets for this stream at the end of the files had valid dts.
1529  next_pkt->pts = last_dts + next_pkt->duration;
1530  }
1531  pktl = s->internal->packet_buffer;
1532  }
1533 
1534  /* read packet from packet buffer, if there is data */
1535  st = s->streams[next_pkt->stream_index];
1536  if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1537  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1539  &s->internal->packet_buffer_end, pkt);
1540  goto return_packet;
1541  }
1542  }
1543 
1544  ret = read_frame_internal(s, pkt);
1545  if (ret < 0) {
1546  if (pktl && ret != AVERROR(EAGAIN)) {
1547  eof = 1;
1548  continue;
1549  } else
1550  return ret;
1551  }
1552 
1554  &s->internal->packet_buffer_end)) < 0)
1555  return AVERROR(ENOMEM);
1556  }
1557 
1558 return_packet:
1559 
1560  st = s->streams[pkt->stream_index];
1561  if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1562  ff_reduce_index(s, st->index);
1563  av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1564  }
1565 
1566  if (is_relative(pkt->dts))
1567  pkt->dts -= RELATIVE_TS_BASE;
1568  if (is_relative(pkt->pts))
1569  pkt->pts -= RELATIVE_TS_BASE;
1570 
1571  return ret;
1572 }
1573 
1574 /* XXX: suppress the packet queue */
1576 {
1577  if (!s->internal)
1578  return;
1582 
1584 }
1585 
1586 /*******************************************************/
1587 /* seek support */
1588 
1590 {
1591  int i;
1592  AVStream *st;
1593  int best_stream = 0;
1594  int best_score = INT_MIN;
1595 
1596  if (s->nb_streams <= 0)
1597  return -1;
1598  for (i = 0; i < s->nb_streams; i++) {
1599  int score = 0;
1600  st = s->streams[i];
1601  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1603  score -= 400;
1604  if (st->codec->width && st->codec->height)
1605  score += 50;
1606  score+= 25;
1607  }
1608  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1609  if (st->codec->sample_rate)
1610  score += 50;
1611  }
1612  if (st->codec_info_nb_frames)
1613  score += 12;
1614 
1615  if (st->discard != AVDISCARD_ALL)
1616  score += 200;
1617 
1618  if (score > best_score) {
1619  best_score = score;
1620  best_stream = i;
1621  }
1622  }
1623  return best_stream;
1624 }
1625 
1626 /** Flush the frame reader. */
1628 {
1629  AVStream *st;
1630  int i, j;
1631 
1632  flush_packet_queue(s);
1633 
1634  /* Reset read state for each stream. */
1635  for (i = 0; i < s->nb_streams; i++) {
1636  st = s->streams[i];
1637 
1638  if (st->parser) {
1639  av_parser_close(st->parser);
1640  st->parser = NULL;
1641  }
1644  if (st->first_dts == AV_NOPTS_VALUE)
1645  st->cur_dts = RELATIVE_TS_BASE;
1646  else
1647  /* We set the current DTS to an unspecified origin. */
1648  st->cur_dts = AV_NOPTS_VALUE;
1649 
1651 
1652  for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1653  st->pts_buffer[j] = AV_NOPTS_VALUE;
1654 
1656  st->inject_global_side_data = 1;
1657 
1658  st->skip_samples = 0;
1659  }
1660 }
1661 
1662 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1663 {
1664  int i;
1665 
1666  for (i = 0; i < s->nb_streams; i++) {
1667  AVStream *st = s->streams[i];
1668 
1669  st->cur_dts =
1670  av_rescale(timestamp,
1671  st->time_base.den * (int64_t) ref_st->time_base.num,
1672  st->time_base.num * (int64_t) ref_st->time_base.den);
1673  }
1674 }
1675 
1676 void ff_reduce_index(AVFormatContext *s, int stream_index)
1677 {
1678  AVStream *st = s->streams[stream_index];
1679  unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1680 
1681  if ((unsigned) st->nb_index_entries >= max_entries) {
1682  int i;
1683  for (i = 0; 2 * i < st->nb_index_entries; i++)
1684  st->index_entries[i] = st->index_entries[2 * i];
1685  st->nb_index_entries = i;
1686  }
1687 }
1688 
1689 int ff_add_index_entry(AVIndexEntry **index_entries,
1690  int *nb_index_entries,
1691  unsigned int *index_entries_allocated_size,
1692  int64_t pos, int64_t timestamp,
1693  int size, int distance, int flags)
1694 {
1695  AVIndexEntry *entries, *ie;
1696  int index;
1697 
1698  if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1699  return -1;
1700 
1701  if (timestamp == AV_NOPTS_VALUE)
1702  return AVERROR(EINVAL);
1703 
1704  if (size < 0 || size > 0x3FFFFFFF)
1705  return AVERROR(EINVAL);
1706 
1707  if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1708  timestamp -= RELATIVE_TS_BASE;
1709 
1710  entries = av_fast_realloc(*index_entries,
1711  index_entries_allocated_size,
1712  (*nb_index_entries + 1) *
1713  sizeof(AVIndexEntry));
1714  if (!entries)
1715  return -1;
1716 
1717  *index_entries = entries;
1718 
1719  index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1720  timestamp, AVSEEK_FLAG_ANY);
1721 
1722  if (index < 0) {
1723  index = (*nb_index_entries)++;
1724  ie = &entries[index];
1725  av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1726  } else {
1727  ie = &entries[index];
1728  if (ie->timestamp != timestamp) {
1729  if (ie->timestamp <= timestamp)
1730  return -1;
1731  memmove(entries + index + 1, entries + index,
1732  sizeof(AVIndexEntry) * (*nb_index_entries - index));
1733  (*nb_index_entries)++;
1734  } else if (ie->pos == pos && distance < ie->min_distance)
1735  // do not reduce the distance
1736  distance = ie->min_distance;
1737  }
1738 
1739  ie->pos = pos;
1740  ie->timestamp = timestamp;
1741  ie->min_distance = distance;
1742  ie->size = size;
1743  ie->flags = flags;
1744 
1745  return index;
1746 }
1747 
1748 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1749  int size, int distance, int flags)
1750 {
1751  timestamp = wrap_timestamp(st, timestamp);
1753  &st->index_entries_allocated_size, pos,
1754  timestamp, size, distance, flags);
1755 }
1756 
1757 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1758  int64_t wanted_timestamp, int flags)
1759 {
1760  int a, b, m;
1761  int64_t timestamp;
1762 
1763  a = -1;
1764  b = nb_entries;
1765 
1766  // Optimize appending index entries at the end.
1767  if (b && entries[b - 1].timestamp < wanted_timestamp)
1768  a = b - 1;
1769 
1770  while (b - a > 1) {
1771  m = (a + b) >> 1;
1772  timestamp = entries[m].timestamp;
1773  if (timestamp >= wanted_timestamp)
1774  b = m;
1775  if (timestamp <= wanted_timestamp)
1776  a = m;
1777  }
1778  m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1779 
1780  if (!(flags & AVSEEK_FLAG_ANY))
1781  while (m >= 0 && m < nb_entries &&
1782  !(entries[m].flags & AVINDEX_KEYFRAME))
1783  m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1784 
1785  if (m == nb_entries)
1786  return -1;
1787  return m;
1788 }
1789 
1790 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
1791 {
1792  int ist1, ist2;
1793  int64_t pos_delta = 0;
1794  int64_t skip = 0;
1795  //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
1796  const char *proto = avio_find_protocol_name(s->filename);
1797 
1798  if (!proto) {
1799  av_log(s, AV_LOG_INFO,
1800  "Protocol name not provided, cannot determine if input is local or "
1801  "a network protocol, buffers and access patterns cannot be configured "
1802  "optimally without knowing the protocol\n");
1803  }
1804 
1805  if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
1806  return;
1807 
1808  for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
1809  AVStream *st1 = s->streams[ist1];
1810  for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
1811  AVStream *st2 = s->streams[ist2];
1812  int i1, i2;
1813 
1814  if (ist1 == ist2)
1815  continue;
1816 
1817  for (i1 = i2 = 0; i1 < st1->nb_index_entries; i1++) {
1818  AVIndexEntry *e1 = &st1->index_entries[i1];
1819  int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
1820 
1821  skip = FFMAX(skip, e1->size);
1822  for (; i2 < st2->nb_index_entries; i2++) {
1823  AVIndexEntry *e2 = &st2->index_entries[i2];
1824  int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
1825  if (e2_pts - e1_pts < time_tolerance)
1826  continue;
1827  pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
1828  break;
1829  }
1830  }
1831  }
1832  }
1833 
1834  pos_delta *= 2;
1835  /* XXX This could be adjusted depending on protocol*/
1836  if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
1837  av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
1838  ffio_set_buf_size(s->pb, pos_delta);
1839  s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
1840  }
1841 
1842  if (skip < (1<<23)) {
1844  }
1845 }
1846 
1847 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1848 {
1850  wanted_timestamp, flags);
1851 }
1852 
1853 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
1854  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1855 {
1856  int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
1857  if (stream_index >= 0)
1858  ts = wrap_timestamp(s->streams[stream_index], ts);
1859  return ts;
1860 }
1861 
1862 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1863  int64_t target_ts, int flags)
1864 {
1865  AVInputFormat *avif = s->iformat;
1866  int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1867  int64_t ts_min, ts_max, ts;
1868  int index;
1869  int64_t ret;
1870  AVStream *st;
1871 
1872  if (stream_index < 0)
1873  return -1;
1874 
1875  av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1876 
1877  ts_max =
1878  ts_min = AV_NOPTS_VALUE;
1879  pos_limit = -1; // GCC falsely says it may be uninitialized.
1880 
1881  st = s->streams[stream_index];
1882  if (st->index_entries) {
1883  AVIndexEntry *e;
1884 
1885  /* FIXME: Whole function must be checked for non-keyframe entries in
1886  * index case, especially read_timestamp(). */
1887  index = av_index_search_timestamp(st, target_ts,
1888  flags | AVSEEK_FLAG_BACKWARD);
1889  index = FFMAX(index, 0);
1890  e = &st->index_entries[index];
1891 
1892  if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1893  pos_min = e->pos;
1894  ts_min = e->timestamp;
1895  av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
1896  pos_min, av_ts2str(ts_min));
1897  } else {
1898  av_assert1(index == 0);
1899  }
1900 
1901  index = av_index_search_timestamp(st, target_ts,
1902  flags & ~AVSEEK_FLAG_BACKWARD);
1903  av_assert0(index < st->nb_index_entries);
1904  if (index >= 0) {
1905  e = &st->index_entries[index];
1906  av_assert1(e->timestamp >= target_ts);
1907  pos_max = e->pos;
1908  ts_max = e->timestamp;
1909  pos_limit = pos_max - e->min_distance;
1910  av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1911  " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
1912  }
1913  }
1914 
1915  pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1916  ts_min, ts_max, flags, &ts, avif->read_timestamp);
1917  if (pos < 0)
1918  return -1;
1919 
1920  /* do the seek */
1921  if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1922  return ret;
1923 
1925  ff_update_cur_dts(s, st, ts);
1926 
1927  return 0;
1928 }
1929 
1930 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
1931  int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1932 {
1933  int64_t step = 1024;
1934  int64_t limit, ts_max;
1935  int64_t filesize = avio_size(s->pb);
1936  int64_t pos_max = filesize - 1;
1937  do {
1938  limit = pos_max;
1939  pos_max = FFMAX(0, (pos_max) - step);
1940  ts_max = ff_read_timestamp(s, stream_index,
1941  &pos_max, limit, read_timestamp);
1942  step += step;
1943  } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
1944  if (ts_max == AV_NOPTS_VALUE)
1945  return -1;
1946 
1947  for (;;) {
1948  int64_t tmp_pos = pos_max + 1;
1949  int64_t tmp_ts = ff_read_timestamp(s, stream_index,
1950  &tmp_pos, INT64_MAX, read_timestamp);
1951  if (tmp_ts == AV_NOPTS_VALUE)
1952  break;
1953  av_assert0(tmp_pos > pos_max);
1954  ts_max = tmp_ts;
1955  pos_max = tmp_pos;
1956  if (tmp_pos >= filesize)
1957  break;
1958  }
1959 
1960  if (ts)
1961  *ts = ts_max;
1962  if (pos)
1963  *pos = pos_max;
1964 
1965  return 0;
1966 }
1967 
1968 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1969  int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1970  int64_t ts_min, int64_t ts_max,
1971  int flags, int64_t *ts_ret,
1972  int64_t (*read_timestamp)(struct AVFormatContext *, int,
1973  int64_t *, int64_t))
1974 {
1975  int64_t pos, ts;
1976  int64_t start_pos;
1977  int no_change;
1978  int ret;
1979 
1980  av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1981 
1982  if (ts_min == AV_NOPTS_VALUE) {
1983  pos_min = s->internal->data_offset;
1984  ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1985  if (ts_min == AV_NOPTS_VALUE)
1986  return -1;
1987  }
1988 
1989  if (ts_min >= target_ts) {
1990  *ts_ret = ts_min;
1991  return pos_min;
1992  }
1993 
1994  if (ts_max == AV_NOPTS_VALUE) {
1995  if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
1996  return ret;
1997  pos_limit = pos_max;
1998  }
1999 
2000  if (ts_max <= target_ts) {
2001  *ts_ret = ts_max;
2002  return pos_max;
2003  }
2004 
2005  av_assert0(ts_min < ts_max);
2006 
2007  no_change = 0;
2008  while (pos_min < pos_limit) {
2009  av_log(s, AV_LOG_TRACE,
2010  "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2011  pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2012  av_assert0(pos_limit <= pos_max);
2013 
2014  if (no_change == 0) {
2015  int64_t approximate_keyframe_distance = pos_max - pos_limit;
2016  // interpolate position (better than dichotomy)
2017  pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2018  ts_max - ts_min) +
2019  pos_min - approximate_keyframe_distance;
2020  } else if (no_change == 1) {
2021  // bisection if interpolation did not change min / max pos last time
2022  pos = (pos_min + pos_limit) >> 1;
2023  } else {
2024  /* linear search if bisection failed, can only happen if there
2025  * are very few or no keyframes between min/max */
2026  pos = pos_min;
2027  }
2028  if (pos <= pos_min)
2029  pos = pos_min + 1;
2030  else if (pos > pos_limit)
2031  pos = pos_limit;
2032  start_pos = pos;
2033 
2034  // May pass pos_limit instead of -1.
2035  ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2036  if (pos == pos_max)
2037  no_change++;
2038  else
2039  no_change = 0;
2040  av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2041  " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2042  pos_min, pos, pos_max,
2043  av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2044  pos_limit, start_pos, no_change);
2045  if (ts == AV_NOPTS_VALUE) {
2046  av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2047  return -1;
2048  }
2049  if (target_ts <= ts) {
2050  pos_limit = start_pos - 1;
2051  pos_max = pos;
2052  ts_max = ts;
2053  }
2054  if (target_ts >= ts) {
2055  pos_min = pos;
2056  ts_min = ts;
2057  }
2058  }
2059 
2060  pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2061  ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2062 #if 0
2063  pos_min = pos;
2064  ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2065  pos_min++;
2066  ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2067  av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2068  pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2069 #endif
2070  *ts_ret = ts;
2071  return pos;
2072 }
2073 
2074 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2075  int64_t pos, int flags)
2076 {
2077  int64_t pos_min, pos_max;
2078 
2079  pos_min = s->internal->data_offset;
2080  pos_max = avio_size(s->pb) - 1;
2081 
2082  if (pos < pos_min)
2083  pos = pos_min;
2084  else if (pos > pos_max)
2085  pos = pos_max;
2086 
2087  avio_seek(s->pb, pos, SEEK_SET);
2088 
2089  s->io_repositioned = 1;
2090 
2091  return 0;
2092 }
2093 
2094 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2095  int64_t timestamp, int flags)
2096 {
2097  int index;
2098  int64_t ret;
2099  AVStream *st;
2100  AVIndexEntry *ie;
2101 
2102  st = s->streams[stream_index];
2103 
2104  index = av_index_search_timestamp(st, timestamp, flags);
2105 
2106  if (index < 0 && st->nb_index_entries &&
2107  timestamp < st->index_entries[0].timestamp)
2108  return -1;
2109 
2110  if (index < 0 || index == st->nb_index_entries - 1) {
2111  AVPacket pkt;
2112  int nonkey = 0;
2113 
2114  if (st->nb_index_entries) {
2116  ie = &st->index_entries[st->nb_index_entries - 1];
2117  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2118  return ret;
2119  ff_update_cur_dts(s, st, ie->timestamp);
2120  } else {
2121  if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2122  return ret;
2123  }
2124  for (;;) {
2125  int read_status;
2126  do {
2127  read_status = av_read_frame(s, &pkt);
2128  } while (read_status == AVERROR(EAGAIN));
2129  if (read_status < 0)
2130  break;
2131  av_free_packet(&pkt);
2132  if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2133  if (pkt.flags & AV_PKT_FLAG_KEY)
2134  break;
2135  if (nonkey++ > 1000 && st->codec->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2136  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);
2137  break;
2138  }
2139  }
2140  }
2141  index = av_index_search_timestamp(st, timestamp, flags);
2142  }
2143  if (index < 0)
2144  return -1;
2145 
2147  if (s->iformat->read_seek)
2148  if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2149  return 0;
2150  ie = &st->index_entries[index];
2151  if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2152  return ret;
2153  ff_update_cur_dts(s, st, ie->timestamp);
2154 
2155  return 0;
2156 }
2157 
2158 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2159  int64_t timestamp, int flags)
2160 {
2161  int ret;
2162  AVStream *st;
2163 
2164  if (flags & AVSEEK_FLAG_BYTE) {
2165  if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2166  return -1;
2168  return seek_frame_byte(s, stream_index, timestamp, flags);
2169  }
2170 
2171  if (stream_index < 0) {
2172  stream_index = av_find_default_stream_index(s);
2173  if (stream_index < 0)
2174  return -1;
2175 
2176  st = s->streams[stream_index];
2177  /* timestamp for default must be expressed in AV_TIME_BASE units */
2178  timestamp = av_rescale(timestamp, st->time_base.den,
2179  AV_TIME_BASE * (int64_t) st->time_base.num);
2180  }
2181 
2182  /* first, we try the format specific seek */
2183  if (s->iformat->read_seek) {
2185  ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2186  } else
2187  ret = -1;
2188  if (ret >= 0)
2189  return 0;
2190 
2191  if (s->iformat->read_timestamp &&
2192  !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2194  return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2195  } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2197  return seek_frame_generic(s, stream_index, timestamp, flags);
2198  } else
2199  return -1;
2200 }
2201 
2202 int av_seek_frame(AVFormatContext *s, int stream_index,
2203  int64_t timestamp, int flags)
2204 {
2205  int ret;
2206 
2207  if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2208  int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2209  if ((flags & AVSEEK_FLAG_BACKWARD))
2210  max_ts = timestamp;
2211  else
2212  min_ts = timestamp;
2213  return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2214  flags & ~AVSEEK_FLAG_BACKWARD);
2215  }
2216 
2217  ret = seek_frame_internal(s, stream_index, timestamp, flags);
2218 
2219  if (ret >= 0)
2221 
2222  return ret;
2223 }
2224 
2225 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2226  int64_t ts, int64_t max_ts, int flags)
2227 {
2228  if (min_ts > ts || max_ts < ts)
2229  return -1;
2230  if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2231  return AVERROR(EINVAL);
2232 
2233  if (s->seek2any>0)
2234  flags |= AVSEEK_FLAG_ANY;
2235  flags &= ~AVSEEK_FLAG_BACKWARD;
2236 
2237  if (s->iformat->read_seek2) {
2238  int ret;
2240 
2241  if (stream_index == -1 && s->nb_streams == 1) {
2242  AVRational time_base = s->streams[0]->time_base;
2243  ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2244  min_ts = av_rescale_rnd(min_ts, time_base.den,
2245  time_base.num * (int64_t)AV_TIME_BASE,
2247  max_ts = av_rescale_rnd(max_ts, time_base.den,
2248  time_base.num * (int64_t)AV_TIME_BASE,
2250  stream_index = 0;
2251  }
2252 
2253  ret = s->iformat->read_seek2(s, stream_index, min_ts,
2254  ts, max_ts, flags);
2255 
2256  if (ret >= 0)
2258  return ret;
2259  }
2260 
2261  if (s->iformat->read_timestamp) {
2262  // try to seek via read_timestamp()
2263  }
2264 
2265  // Fall back on old API if new is not implemented but old is.
2266  // Note the old API has somewhat different semantics.
2267  if (s->iformat->read_seek || 1) {
2268  int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2269  int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2270  if (ret<0 && ts != min_ts && max_ts != ts) {
2271  ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2272  if (ret >= 0)
2273  ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2274  }
2275  return ret;
2276  }
2277 
2278  // try some generic seek like seek_frame_generic() but with new ts semantics
2279  return -1; //unreachable
2280 }
2281 
2283 {
2285  return 0;
2286 }
2287 
2288 /*******************************************************/
2289 
2290 /**
2291  * Return TRUE if the stream has accurate duration in any stream.
2292  *
2293  * @return TRUE if the stream has accurate duration for at least one component.
2294  */
2296 {
2297  int i;
2298  AVStream *st;
2299 
2300  for (i = 0; i < ic->nb_streams; i++) {
2301  st = ic->streams[i];
2302  if (st->duration != AV_NOPTS_VALUE)
2303  return 1;
2304  }
2305  if (ic->duration != AV_NOPTS_VALUE)
2306  return 1;
2307  return 0;
2308 }
2309 
2310 /**
2311  * Estimate the stream timings from the one of each components.
2312  *
2313  * Also computes the global bitrate if possible.
2314  */
2316 {
2317  int64_t start_time, start_time1, start_time_text, end_time, end_time1;
2318  int64_t duration, duration1, filesize;
2319  int i;
2320  AVStream *st;
2321  AVProgram *p;
2322 
2323  start_time = INT64_MAX;
2324  start_time_text = INT64_MAX;
2325  end_time = INT64_MIN;
2326  duration = INT64_MIN;
2327  for (i = 0; i < ic->nb_streams; i++) {
2328  st = ic->streams[i];
2329  if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2330  start_time1 = av_rescale_q(st->start_time, st->time_base,
2331  AV_TIME_BASE_Q);
2333  if (start_time1 < start_time_text)
2334  start_time_text = start_time1;
2335  } else
2336  start_time = FFMIN(start_time, start_time1);
2337  end_time1 = AV_NOPTS_VALUE;
2338  if (st->duration != AV_NOPTS_VALUE) {
2339  end_time1 = start_time1 +
2340  av_rescale_q(st->duration, st->time_base,
2341  AV_TIME_BASE_Q);
2342  end_time = FFMAX(end_time, end_time1);
2343  }
2344  for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2345  if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2346  p->start_time = start_time1;
2347  if (p->end_time < end_time1)
2348  p->end_time = end_time1;
2349  }
2350  }
2351  if (st->duration != AV_NOPTS_VALUE) {
2352  duration1 = av_rescale_q(st->duration, st->time_base,
2353  AV_TIME_BASE_Q);
2354  duration = FFMAX(duration, duration1);
2355  }
2356  }
2357  if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
2358  start_time = start_time_text;
2359  else if (start_time > start_time_text)
2360  av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2361 
2362  if (start_time != INT64_MAX) {
2363  ic->start_time = start_time;
2364  if (end_time != INT64_MIN) {
2365  if (ic->nb_programs) {
2366  for (i = 0; i < ic->nb_programs; i++) {
2367  p = ic->programs[i];
2368  if (p->start_time != AV_NOPTS_VALUE &&
2369  p->end_time > p->start_time &&
2370  p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2371  duration = FFMAX(duration, p->end_time - p->start_time);
2372  }
2373  } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2374  duration = FFMAX(duration, end_time - start_time);
2375  }
2376  }
2377  }
2378  if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2379  ic->duration = duration;
2380  }
2381  if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2382  /* compute the bitrate */
2383  double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2384  (double) ic->duration;
2385  if (bitrate >= 0 && bitrate <= INT_MAX)
2386  ic->bit_rate = bitrate;
2387  }
2388 }
2389 
2391 {
2392  int i;
2393  AVStream *st;
2394 
2396  for (i = 0; i < ic->nb_streams; i++) {
2397  st = ic->streams[i];
2398  if (st->start_time == AV_NOPTS_VALUE) {
2399  if (ic->start_time != AV_NOPTS_VALUE)
2401  st->time_base);
2402  if (ic->duration != AV_NOPTS_VALUE)
2404  st->time_base);
2405  }
2406  }
2407 }
2408 
2410 {
2411  int64_t filesize, duration;
2412  int i, show_warning = 0;
2413  AVStream *st;
2414 
2415  /* if bit_rate is already set, we believe it */
2416  if (ic->bit_rate <= 0) {
2417  int bit_rate = 0;
2418  for (i = 0; i < ic->nb_streams; i++) {
2419  st = ic->streams[i];
2420  if (st->codec->bit_rate > 0) {
2421  if (INT_MAX - st->codec->bit_rate < bit_rate) {
2422  bit_rate = 0;
2423  break;
2424  }
2425  bit_rate += st->codec->bit_rate;
2426  } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2427  // If we have a videostream with packets but without a bitrate
2428  // then consider the sum not known
2429  bit_rate = 0;
2430  break;
2431  }
2432  }
2433  ic->bit_rate = bit_rate;
2434  }
2435 
2436  /* if duration is already set, we believe it */
2437  if (ic->duration == AV_NOPTS_VALUE &&
2438  ic->bit_rate != 0) {
2439  filesize = ic->pb ? avio_size(ic->pb) : 0;
2440  if (filesize > ic->internal->data_offset) {
2441  filesize -= ic->internal->data_offset;
2442  for (i = 0; i < ic->nb_streams; i++) {
2443  st = ic->streams[i];
2444  if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2445  && st->duration == AV_NOPTS_VALUE) {
2446  duration = av_rescale(8 * filesize, st->time_base.den,
2447  ic->bit_rate *
2448  (int64_t) st->time_base.num);
2449  st->duration = duration;
2450  show_warning = 1;
2451  }
2452  }
2453  }
2454  }
2455  if (show_warning)
2456  av_log(ic, AV_LOG_WARNING,
2457  "Estimating duration from bitrate, this may be inaccurate\n");
2458 }
2459 
2460 #define DURATION_MAX_READ_SIZE 250000LL
2461 #define DURATION_MAX_RETRY 6
2462 
2463 /* only usable for MPEG-PS streams */
2464 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2465 {
2466  AVPacket pkt1, *pkt = &pkt1;
2467  AVStream *st;
2468  int num, den, read_size, i, ret;
2469  int found_duration = 0;
2470  int is_end;
2471  int64_t filesize, offset, duration;
2472  int retry = 0;
2473 
2474  /* flush packet queue */
2475  flush_packet_queue(ic);
2476 
2477  for (i = 0; i < ic->nb_streams; i++) {
2478  st = ic->streams[i];
2479  if (st->start_time == AV_NOPTS_VALUE &&
2480  st->first_dts == AV_NOPTS_VALUE &&
2483  "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2484 
2485  if (st->parser) {
2486  av_parser_close(st->parser);
2487  st->parser = NULL;
2488  }
2489  }
2490 
2491  av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2492  /* estimate the end time (duration) */
2493  /* XXX: may need to support wrapping */
2494  filesize = ic->pb ? avio_size(ic->pb) : 0;
2495  do {
2496  is_end = found_duration;
2497  offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2498  if (offset < 0)
2499  offset = 0;
2500 
2501  avio_seek(ic->pb, offset, SEEK_SET);
2502  read_size = 0;
2503  for (;;) {
2504  if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2505  break;
2506 
2507  do {
2508  ret = ff_read_packet(ic, pkt);
2509  } while (ret == AVERROR(EAGAIN));
2510  if (ret != 0)
2511  break;
2512  read_size += pkt->size;
2513  st = ic->streams[pkt->stream_index];
2514  if (pkt->pts != AV_NOPTS_VALUE &&
2515  (st->start_time != AV_NOPTS_VALUE ||
2516  st->first_dts != AV_NOPTS_VALUE)) {
2517  if (pkt->duration == 0) {
2518  ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2519  if (den && num) {
2520  pkt->duration = av_rescale_rnd(1,
2521  num * (int64_t) st->time_base.den,
2522  den * (int64_t) st->time_base.num,
2523  AV_ROUND_DOWN);
2524  }
2525  }
2526  duration = pkt->pts + pkt->duration;
2527  found_duration = 1;
2528  if (st->start_time != AV_NOPTS_VALUE)
2529  duration -= st->start_time;
2530  else
2531  duration -= st->first_dts;
2532  if (duration > 0) {
2533  if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2534  (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2535  st->duration = duration;
2536  st->info->last_duration = duration;
2537  }
2538  }
2539  av_free_packet(pkt);
2540  }
2541 
2542  /* check if all audio/video streams have valid duration */
2543  if (!is_end) {
2544  is_end = 1;
2545  for (i = 0; i < ic->nb_streams; i++) {
2546  st = ic->streams[i];
2547  switch (st->codec->codec_type) {
2548  case AVMEDIA_TYPE_VIDEO:
2549  case AVMEDIA_TYPE_AUDIO:
2550  if (st->duration == AV_NOPTS_VALUE)
2551  is_end = 0;
2552  }
2553  }
2554  }
2555  } while (!is_end &&
2556  offset &&
2557  ++retry <= DURATION_MAX_RETRY);
2558 
2559  av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2560 
2561  /* warn about audio/video streams which duration could not be estimated */
2562  for (i = 0; i < ic->nb_streams; i++) {
2563  st = ic->streams[i];
2564  if (st->duration == AV_NOPTS_VALUE) {
2565  switch (st->codec->codec_type) {
2566  case AVMEDIA_TYPE_VIDEO:
2567  case AVMEDIA_TYPE_AUDIO:
2568  if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2569  av_log(ic, AV_LOG_DEBUG, "stream %d : no PTS found at end of file, duration not set\n", i);
2570  } else
2571  av_log(ic, AV_LOG_DEBUG, "stream %d : no TS found at start of file, duration not set\n", i);
2572  }
2573  }
2574  }
2576 
2577  avio_seek(ic->pb, old_offset, SEEK_SET);
2578  for (i = 0; i < ic->nb_streams; i++) {
2579  int j;
2580 
2581  st = ic->streams[i];
2582  st->cur_dts = st->first_dts;
2585  for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2586  st->pts_buffer[j] = AV_NOPTS_VALUE;
2587  }
2588 }
2589 
2590 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2591 {
2592  int64_t file_size;
2593 
2594  /* get the file size, if possible */
2595  if (ic->iformat->flags & AVFMT_NOFILE) {
2596  file_size = 0;
2597  } else {
2598  file_size = avio_size(ic->pb);
2599  file_size = FFMAX(0, file_size);
2600  }
2601 
2602  if ((!strcmp(ic->iformat->name, "mpeg") ||
2603  !strcmp(ic->iformat->name, "mpegts")) &&
2604  file_size && ic->pb->seekable) {
2605  /* get accurate estimate from the PTSes */
2606  estimate_timings_from_pts(ic, old_offset);
2608  } else if (has_duration(ic)) {
2609  /* at least one component has timings - we use them for all
2610  * the components */
2613  } else {
2614  /* less precise: use bitrate info */
2617  }
2619 
2620  {
2621  int i;
2622  AVStream av_unused *st;
2623  for (i = 0; i < ic->nb_streams; i++) {
2624  st = ic->streams[i];
2625  av_log(ic, AV_LOG_TRACE, "%d: start_time: %0.3f duration: %0.3f\n", i,
2626  (double) st->start_time / AV_TIME_BASE,
2627  (double) st->duration / AV_TIME_BASE);
2628  }
2629  av_log(ic, AV_LOG_TRACE,
2630  "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2631  (double) ic->start_time / AV_TIME_BASE,
2632  (double) ic->duration / AV_TIME_BASE,
2633  ic->bit_rate / 1000);
2634  }
2635 }
2636 
2637 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2638 {
2639  AVCodecContext *avctx = st->codec;
2640 
2641 #define FAIL(errmsg) do { \
2642  if (errmsg_ptr) \
2643  *errmsg_ptr = errmsg; \
2644  return 0; \
2645  } while (0)
2646 
2647  if ( avctx->codec_id == AV_CODEC_ID_NONE
2648  && avctx->codec_type != AVMEDIA_TYPE_DATA)
2649  FAIL("unknown codec");
2650  switch (avctx->codec_type) {
2651  case AVMEDIA_TYPE_AUDIO:
2652  if (!avctx->frame_size && determinable_frame_size(avctx))
2653  FAIL("unspecified frame size");
2654  if (st->info->found_decoder >= 0 &&
2655  avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2656  FAIL("unspecified sample format");
2657  if (!avctx->sample_rate)
2658  FAIL("unspecified sample rate");
2659  if (!avctx->channels)
2660  FAIL("unspecified number of channels");
2661  if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2662  FAIL("no decodable DTS frames");
2663  break;
2664  case AVMEDIA_TYPE_VIDEO:
2665  if (!avctx->width)
2666  FAIL("unspecified size");
2667  if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2668  FAIL("unspecified pixel format");
2671  FAIL("no frame in rv30/40 and no sar");
2672  break;
2673  case AVMEDIA_TYPE_SUBTITLE:
2674  if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2675  FAIL("unspecified size");
2676  break;
2677  case AVMEDIA_TYPE_DATA:
2678  if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2679  }
2680 
2681  return 1;
2682 }
2683 
2684 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2687 {
2688  const AVCodec *codec;
2689  int got_picture = 1, ret = 0;
2691  AVSubtitle subtitle;
2692  AVPacket pkt = *avpkt;
2693 
2694  if (!frame)
2695  return AVERROR(ENOMEM);
2696 
2697  if (!avcodec_is_open(st->codec) &&
2698  st->info->found_decoder <= 0 &&
2699  (st->codec->codec_id != -st->info->found_decoder || !st->codec->codec_id)) {
2700  AVDictionary *thread_opt = NULL;
2701 
2702  codec = find_decoder(s, st, st->codec->codec_id);
2703 
2704  if (!codec) {
2705  st->info->found_decoder = -st->codec->codec_id;
2706  ret = -1;
2707  goto fail;
2708  }
2709 
2710  /* Force thread count to 1 since the H.264 decoder will not extract
2711  * SPS and PPS to extradata during multi-threaded decoding. */
2712  av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2713  if (s->codec_whitelist)
2714  av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
2715  ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2716  if (!options)
2717  av_dict_free(&thread_opt);
2718  if (ret < 0) {
2719  st->info->found_decoder = -st->codec->codec_id;
2720  goto fail;
2721  }
2722  st->info->found_decoder = 1;
2723  } else if (!st->info->found_decoder)
2724  st->info->found_decoder = 1;
2725 
2726  if (st->info->found_decoder < 0) {
2727  ret = -1;
2728  goto fail;
2729  }
2730 
2731  while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2732  ret >= 0 &&
2734  (!st->codec_info_nb_frames &&
2736  got_picture = 0;
2737  switch (st->codec->codec_type) {
2738  case AVMEDIA_TYPE_VIDEO:
2739  ret = avcodec_decode_video2(st->codec, frame,
2740  &got_picture, &pkt);
2741  break;
2742  case AVMEDIA_TYPE_AUDIO:
2743  ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2744  break;
2745  case AVMEDIA_TYPE_SUBTITLE:
2746  ret = avcodec_decode_subtitle2(st->codec, &subtitle,
2747  &got_picture, &pkt);
2748  ret = pkt.size;
2749  break;
2750  default:
2751  break;
2752  }
2753  if (ret >= 0) {
2754  if (got_picture)
2755  st->nb_decoded_frames++;
2756  pkt.data += ret;
2757  pkt.size -= ret;
2758  ret = got_picture;
2759  }
2760  }
2761 
2762  if (!pkt.data && !got_picture)
2763  ret = -1;
2764 
2765 fail:
2766  av_frame_free(&frame);
2767  return ret;
2768 }
2769 
2770 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2771 {
2772  while (tags->id != AV_CODEC_ID_NONE) {
2773  if (tags->id == id)
2774  return tags->tag;
2775  tags++;
2776  }
2777  return 0;
2778 }
2779 
2780 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2781 {
2782  int i;
2783  for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2784  if (tag == tags[i].tag)
2785  return tags[i].id;
2786  for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2787  if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2788  return tags[i].id;
2789  return AV_CODEC_ID_NONE;
2790 }
2791 
2792 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2793 {
2794  if (bps <= 0 || bps > 64)
2795  return AV_CODEC_ID_NONE;
2796 
2797  if (flt) {
2798  switch (bps) {
2799  case 32:
2801  case 64:
2803  default:
2804  return AV_CODEC_ID_NONE;
2805  }
2806  } else {
2807  bps += 7;
2808  bps >>= 3;
2809  if (sflags & (1 << (bps - 1))) {
2810  switch (bps) {
2811  case 1:
2812  return AV_CODEC_ID_PCM_S8;
2813  case 2:
2815  case 3:
2817  case 4:
2819  default:
2820  return AV_CODEC_ID_NONE;
2821  }
2822  } else {
2823  switch (bps) {
2824  case 1:
2825  return AV_CODEC_ID_PCM_U8;
2826  case 2:
2828  case 3:
2830  case 4:
2832  default:
2833  return AV_CODEC_ID_NONE;
2834  }
2835  }
2836  }
2837 }
2838 
2839 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2840 {
2841  unsigned int tag;
2842  if (!av_codec_get_tag2(tags, id, &tag))
2843  return 0;
2844  return tag;
2845 }
2846 
2847 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
2848  unsigned int *tag)
2849 {
2850  int i;
2851  for (i = 0; tags && tags[i]; i++) {
2852  const AVCodecTag *codec_tags = tags[i];
2853  while (codec_tags->id != AV_CODEC_ID_NONE) {
2854  if (codec_tags->id == id) {
2855  *tag = codec_tags->tag;
2856  return 1;
2857  }
2858  codec_tags++;
2859  }
2860  }
2861  return 0;
2862 }
2863 
2864 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2865 {
2866  int i;
2867  for (i = 0; tags && tags[i]; i++) {
2868  enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2869  if (id != AV_CODEC_ID_NONE)
2870  return id;
2871  }
2872  return AV_CODEC_ID_NONE;
2873 }
2874 
2876 {
2877  unsigned int i, j;
2878  int64_t max_time = s->duration +
2879  ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2880 
2881  for (i = 0; i < s->nb_chapters; i++)
2882  if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2883  AVChapter *ch = s->chapters[i];
2884  int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2885  ch->time_base)
2886  : INT64_MAX;
2887 
2888  for (j = 0; j < s->nb_chapters; j++) {
2889  AVChapter *ch1 = s->chapters[j];
2890  int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2891  ch->time_base);
2892  if (j != i && next_start > ch->start && next_start < end)
2893  end = next_start;
2894  }
2895  ch->end = (end == INT64_MAX) ? ch->start : end;
2896  }
2897 }
2898 
2899 static int get_std_framerate(int i)
2900 {
2901  if (i < 30*12)
2902  return (i + 1) * 1001;
2903  i -= 30*12;
2904 
2905  if (i < 30)
2906  return (i + 31) * 1001 * 12;
2907  i -= 30;
2908 
2909  if (i < 3)
2910  return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
2911 
2912  i -= 3;
2913 
2914  return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
2915 }
2916 
2917 /* Is the time base unreliable?
2918  * This is a heuristic to balance between quick acceptance of the values in
2919  * the headers vs. some extra checks.
2920  * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2921  * MPEG-2 commonly misuses field repeat flags to store different framerates.
2922  * And there are "variable" fps files this needs to detect as well. */
2924 {
2925  if (c->time_base.den >= 101LL * c->time_base.num ||
2926  c->time_base.den < 5LL * c->time_base.num ||
2927  // c->codec_tag == AV_RL32("DIVX") ||
2928  // c->codec_tag == AV_RL32("XVID") ||
2929  c->codec_tag == AV_RL32("mp4v") ||
2931  c->codec_id == AV_CODEC_ID_GIF ||
2932  c->codec_id == AV_CODEC_ID_HEVC ||
2933  c->codec_id == AV_CODEC_ID_H264)
2934  return 1;
2935  return 0;
2936 }
2937 
2939 {
2940  int ret;
2941 
2943  avctx->extradata = NULL;
2944  avctx->extradata_size = 0;
2945  return AVERROR(EINVAL);
2946  }
2948  if (avctx->extradata) {
2949  memset(avctx->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2950  avctx->extradata_size = size;
2951  ret = 0;
2952  } else {
2953  avctx->extradata_size = 0;
2954  ret = AVERROR(ENOMEM);
2955  }
2956  return ret;
2957 }
2958 
2960 {
2961  int ret = ff_alloc_extradata(avctx, size);
2962  if (ret < 0)
2963  return ret;
2964  ret = avio_read(pb, avctx->extradata, size);
2965  if (ret != size) {
2966  av_freep(&avctx->extradata);
2967  avctx->extradata_size = 0;
2968  av_log(avctx, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
2969  return ret < 0 ? ret : AVERROR_INVALIDDATA;
2970  }
2971 
2972  return ret;
2973 }
2974 
2975 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
2976 {
2977  int i, j;
2978  int64_t last = st->info->last_dts;
2979 
2980  if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
2981  && ts - (uint64_t)last < INT64_MAX) {
2982  double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
2983  int64_t duration = ts - last;
2984 
2985  if (!st->info->duration_error)
2986  st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);
2987  if (!st->info->duration_error)
2988  return AVERROR(ENOMEM);
2989 
2990 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2991 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2992  for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2993  if (st->info->duration_error[0][1][i] < 1e10) {
2994  int framerate = get_std_framerate(i);
2995  double sdts = dts*framerate/(1001*12);
2996  for (j= 0; j<2; j++) {
2997  int64_t ticks = llrint(sdts+j*0.5);
2998  double error= sdts - ticks + j*0.5;
2999  st->info->duration_error[j][0][i] += error;
3000  st->info->duration_error[j][1][i] += error*error;
3001  }
3002  }
3003  }
3004  st->info->duration_count++;
3006 
3007  if (st->info->duration_count % 10 == 0) {
3008  int n = st->info->duration_count;
3009  for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3010  if (st->info->duration_error[0][1][i] < 1e10) {
3011  double a0 = st->info->duration_error[0][0][i] / n;
3012  double error0 = st->info->duration_error[0][1][i] / n - a0*a0;
3013  double a1 = st->info->duration_error[1][0][i] / n;
3014  double error1 = st->info->duration_error[1][1][i] / n - a1*a1;
3015  if (error0 > 0.04 && error1 > 0.04) {
3016  st->info->duration_error[0][1][i] = 2e10;
3017  st->info->duration_error[1][1][i] = 2e10;
3018  }
3019  }
3020  }
3021  }
3022 
3023  // ignore the first 4 values, they might have some random jitter
3024  if (st->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3025  st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
3026  }
3027  if (ts != AV_NOPTS_VALUE)
3028  st->info->last_dts = ts;
3029 
3030  return 0;
3031 }
3032 
3034 {
3035  int i, j;
3036 
3037  for (i = 0; i < ic->nb_streams; i++) {
3038  AVStream *st = ic->streams[i];
3039 
3040  if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
3041  continue;
3042  // the check for tb_unreliable() is not completely correct, since this is not about handling
3043  // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3044  // ipmovie.c produces.
3045  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)
3046  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);
3047  if (st->info->duration_count>1 && !st->r_frame_rate.num
3048  && tb_unreliable(st->codec)) {
3049  int num = 0;
3050  double best_error= 0.01;
3051  AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3052 
3053  for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3054  int k;
3055 
3056  if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
3057  continue;
3058  if (!st->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3059  continue;
3060 
3061  if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3062  continue;
3063 
3064  for (k= 0; k<2; k++) {
3065  int n = st->info->duration_count;
3066  double a= st->info->duration_error[k][0][j] / n;
3067  double error= st->info->duration_error[k][1][j]/n - a*a;
3068 
3069  if (error < best_error && best_error> 0.000000001) {
3070  best_error= error;
3071  num = get_std_framerate(j);
3072  }
3073  if (error < 0.02)
3074  av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3075  }
3076  }
3077  // do not increase frame rate by more than 1 % in order to match a standard rate.
3078  if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3079  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3080  }
3081  if ( !st->avg_frame_rate.num
3082  && st->r_frame_rate.num && st->info->rfps_duration_sum
3083  && st->info->codec_info_duration <= 0
3084  && st->info->duration_count > 2
3085  && 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
3086  ) {
3087  av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3088  st->avg_frame_rate = st->r_frame_rate;
3089  }
3090 
3091  av_freep(&st->info->duration_error);
3092  st->info->last_dts = AV_NOPTS_VALUE;
3093  st->info->duration_count = 0;
3094  st->info->rfps_duration_sum = 0;
3095  }
3096 }
3097 
3099 {
3100  int i, count, ret = 0, j;
3101  int64_t read_size;
3102  AVStream *st;
3103  AVPacket pkt1, *pkt;
3104  int64_t old_offset = avio_tell(ic->pb);
3105  // new streams might appear, no options for those
3106  int orig_nb_streams = ic->nb_streams;
3107  int flush_codecs;
3108 #if FF_API_PROBESIZE_32
3109  int64_t max_analyze_duration = ic->max_analyze_duration2;
3110 #else
3111  int64_t max_analyze_duration = ic->max_analyze_duration;
3112 #endif
3113  int64_t max_stream_analyze_duration;
3114  int64_t max_subtitle_analyze_duration;
3115 #if FF_API_PROBESIZE_32
3116  int64_t probesize = ic->probesize2;
3117 #else
3118  int64_t probesize = ic->probesize;
3119 #endif
3120 
3121  if (!max_analyze_duration)
3122  max_analyze_duration = ic->max_analyze_duration;
3123  if (ic->probesize)
3124  probesize = ic->probesize;
3125  flush_codecs = probesize > 0;
3126 
3127  av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3128 
3129  max_stream_analyze_duration = max_analyze_duration;
3130  max_subtitle_analyze_duration = max_analyze_duration;
3131  if (!max_analyze_duration) {
3132  max_stream_analyze_duration =
3133  max_analyze_duration = 5*AV_TIME_BASE;
3134  max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3135  if (!strcmp(ic->iformat->name, "flv"))
3136  max_stream_analyze_duration = 30*AV_TIME_BASE;
3137  }
3138 
3139  if (ic->pb)
3140  av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d\n",
3141  avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count);
3142 
3143  for (i = 0; i < ic->nb_streams; i++) {
3144  const AVCodec *codec;
3145  AVDictionary *thread_opt = NULL;
3146  st = ic->streams[i];
3147 
3148  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3150 /* if (!st->time_base.num)
3151  st->time_base = */
3152  if (!st->codec->time_base.num)
3153  st->codec->time_base = st->time_base;
3154  }
3155  // only for the split stuff
3156  if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->request_probe <= 0) {
3157  st->parser = av_parser_init(st->codec->codec_id);
3158  if (st->parser) {
3159  if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3161  } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3163  }
3164  } else if (st->need_parsing) {
3165  av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3166  "%s, packets or times may be invalid.\n",
3168  }
3169  }
3170  codec = find_decoder(ic, st, st->codec->codec_id);
3171 
3172  /* Force thread count to 1 since the H.264 decoder will not extract
3173  * SPS and PPS to extradata during multi-threaded decoding. */
3174  av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3175 
3176  if (ic->codec_whitelist)
3177  av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3178 
3179  /* Ensure that subtitle_header is properly set. */
3181  && codec && !st->codec->codec) {
3182  if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3183  av_log(ic, AV_LOG_WARNING,
3184  "Failed to open codec in av_find_stream_info\n");
3185  }
3186 
3187  // Try to just open decoders, in case this is enough to get parameters.
3188  if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3189  if (codec && !st->codec->codec)
3190  if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3191  av_log(ic, AV_LOG_WARNING,
3192  "Failed to open codec in av_find_stream_info\n");
3193  }
3194  if (!options)
3195  av_dict_free(&thread_opt);
3196  }
3197 
3198  for (i = 0; i < ic->nb_streams; i++) {
3199 #if FF_API_R_FRAME_RATE
3200  ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3201 #endif
3204  }
3205 
3206  count = 0;
3207  read_size = 0;
3208  for (;;) {
3209  int analyzed_all_streams;
3211  ret = AVERROR_EXIT;
3212  av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3213  break;
3214  }
3215 
3216  /* check if one codec still needs to be handled */
3217  for (i = 0; i < ic->nb_streams; i++) {
3218  int fps_analyze_framecount = 20;
3219 
3220  st = ic->streams[i];
3221  if (!has_codec_parameters(st, NULL))
3222  break;
3223  /* If the timebase is coarse (like the usual millisecond precision
3224  * of mkv), we need to analyze more frames to reliably arrive at
3225  * the correct fps. */
3226  if (av_q2d(st->time_base) > 0.0005)
3227  fps_analyze_framecount *= 2;
3228  if (!tb_unreliable(st->codec))
3229  fps_analyze_framecount = 0;
3230  if (ic->fps_probe_size >= 0)
3231  fps_analyze_framecount = ic->fps_probe_size;
3233  fps_analyze_framecount = 0;
3234  /* variable fps and no guess at the real fps */
3235  if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3237  int count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3239  st->info->duration_count;
3240  if (count < fps_analyze_framecount)
3241  break;
3242  }
3243  if (st->parser && st->parser->parser->split &&
3244  !st->codec->extradata)
3245  break;
3246  if (st->first_dts == AV_NOPTS_VALUE &&
3247  !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3248  st->codec_info_nb_frames < ic->max_ts_probe &&
3249  (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3251  break;
3252  }
3253  analyzed_all_streams = 0;
3254  if (i == ic->nb_streams) {
3255  analyzed_all_streams = 1;
3256  /* NOTE: If the format has no header, then we need to read some
3257  * packets to get most of the streams, so we cannot stop here. */
3258  if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3259  /* If we found the info for all the codecs, we can stop. */
3260  ret = count;
3261  av_log(ic, AV_LOG_DEBUG, "All info found\n");
3262  flush_codecs = 0;
3263  break;
3264  }
3265  }
3266  /* We did not get all the codec info, but we read too much data. */
3267  if (read_size >= probesize) {
3268  ret = count;
3269  av_log(ic, AV_LOG_DEBUG,
3270  "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3271  for (i = 0; i < ic->nb_streams; i++)
3272  if (!ic->streams[i]->r_frame_rate.num &&
3273  ic->streams[i]->info->duration_count <= 1 &&
3275  strcmp(ic->iformat->name, "image2"))
3276  av_log(ic, AV_LOG_WARNING,
3277  "Stream #%d: not enough frames to estimate rate; "
3278  "consider increasing probesize\n", i);
3279  break;
3280  }
3281 
3282  /* NOTE: A new stream can be added there if no header in file
3283  * (AVFMTCTX_NOHEADER). */
3284  ret = read_frame_internal(ic, &pkt1);
3285  if (ret == AVERROR(EAGAIN))
3286  continue;
3287 
3288  if (ret < 0) {
3289  /* EOF or error*/
3290  break;
3291  }
3292 
3293  if (ic->flags & AVFMT_FLAG_NOBUFFER)
3295  &ic->internal->packet_buffer_end);
3296  {
3297  pkt = add_to_pktbuf(&ic->internal->packet_buffer, &pkt1,
3298  &ic->internal->packet_buffer_end);
3299  if (!pkt) {
3300  ret = AVERROR(ENOMEM);
3301  goto find_stream_info_err;
3302  }
3303  if ((ret = av_dup_packet(pkt)) < 0)
3304  goto find_stream_info_err;
3305  }
3306 
3307  st = ic->streams[pkt->stream_index];
3309  read_size += pkt->size;
3310 
3311  if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3312  /* check for non-increasing dts */
3313  if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3314  st->info->fps_last_dts >= pkt->dts) {
3315  av_log(ic, AV_LOG_DEBUG,
3316  "Non-increasing DTS in stream %d: packet %d with DTS "
3317  "%"PRId64", packet %d with DTS %"PRId64"\n",
3318  st->index, st->info->fps_last_dts_idx,
3320  pkt->dts);
3321  st->info->fps_first_dts =
3323  }
3324  /* Check for a discontinuity in dts. If the difference in dts
3325  * is more than 1000 times the average packet duration in the
3326  * sequence, we treat it as a discontinuity. */
3327  if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3329  (pkt->dts - st->info->fps_last_dts) / 1000 >
3330  (st->info->fps_last_dts - (uint64_t)st->info->fps_first_dts) /
3331  (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
3332  av_log(ic, AV_LOG_WARNING,
3333  "DTS discontinuity in stream %d: packet %d with DTS "
3334  "%"PRId64", packet %d with DTS %"PRId64"\n",
3335  st->index, st->info->fps_last_dts_idx,
3337  pkt->dts);
3338  st->info->fps_first_dts =
3340  }
3341 
3342  /* update stored dts values */
3343  if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
3344  st->info->fps_first_dts = pkt->dts;
3346  }
3347  st->info->fps_last_dts = pkt->dts;
3349  }
3350  if (st->codec_info_nb_frames>1) {
3351  int64_t t = 0;
3352  int64_t limit;
3353 
3354  if (st->time_base.den > 0)
3356  if (st->avg_frame_rate.num > 0)
3358 
3359  if ( t == 0
3360  && st->codec_info_nb_frames>30
3361  && st->info->fps_first_dts != AV_NOPTS_VALUE
3362  && st->info->fps_last_dts != AV_NOPTS_VALUE)
3364 
3365  if (analyzed_all_streams) limit = max_analyze_duration;
3366  else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3367  else limit = max_stream_analyze_duration;
3368 
3369  if (t >= limit) {
3370  av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3371  max_analyze_duration,
3372  t, pkt->stream_index);
3373  if (ic->flags & AVFMT_FLAG_NOBUFFER)
3374  av_packet_unref(pkt);
3375  break;
3376  }
3377  if (pkt->duration) {
3378  st->info->codec_info_duration += pkt->duration;
3379  st->info->codec_info_duration_fields += st->parser && st->need_parsing && st->codec->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3380  }
3381  }
3382 #if FF_API_R_FRAME_RATE
3383  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3384  ff_rfps_add_frame(ic, st, pkt->dts);
3385 #endif
3386  if (st->parser && st->parser->parser->split && !st->codec->extradata) {
3387  int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
3388  if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
3389  if (ff_alloc_extradata(st->codec, i))
3390  return AVERROR(ENOMEM);
3391  memcpy(st->codec->extradata, pkt->data,
3392  st->codec->extradata_size);
3393  }
3394  }
3395 
3396  /* If still no information, we try to open the codec and to
3397  * decompress the frame. We try to avoid that in most cases as
3398  * it takes longer and uses more memory. For MPEG-4, we need to
3399  * decompress for QuickTime.
3400  *
3401  * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3402  * least one frame of codec data, this makes sure the codec initializes
3403  * the channel configuration and does not only trust the values from
3404  * the container. */
3405  try_decode_frame(ic, st, pkt,
3406  (options && i < orig_nb_streams) ? &options[i] : NULL);
3407 
3408  if (ic->flags & AVFMT_FLAG_NOBUFFER)
3409  av_packet_unref(pkt);
3410 
3411  st->codec_info_nb_frames++;
3412  count++;
3413  }
3414 
3415  if (flush_codecs) {
3416  AVPacket empty_pkt = { 0 };
3417  int err = 0;
3418  av_init_packet(&empty_pkt);
3419 
3420  for (i = 0; i < ic->nb_streams; i++) {
3421 
3422  st = ic->streams[i];
3423 
3424  /* flush the decoders */
3425  if (st->info->found_decoder == 1) {
3426  do {
3427  err = try_decode_frame(ic, st, &empty_pkt,
3428  (options && i < orig_nb_streams)
3429  ? &options[i] : NULL);
3430  } while (err > 0 && !has_codec_parameters(st, NULL));
3431 
3432  if (err < 0) {
3433  av_log(ic, AV_LOG_INFO,
3434  "decoding for stream %d failed\n", st->index);
3435  }
3436  }
3437  }
3438  }
3439 
3440  ff_rfps_calculate(ic);
3441 
3442  for (i = 0; i < ic->nb_streams; i++) {
3443  st = ic->streams[i];
3444  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3448  st->codec->codec_tag= tag;
3449  }
3450 
3451  /* estimate average framerate if not set by demuxer */
3452  if (st->info->codec_info_duration_fields &&
3453  !st->avg_frame_rate.num &&
3454  st->info->codec_info_duration) {
3455  int best_fps = 0;
3456  double best_error = 0.01;
3457 
3458  if (st->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3459  st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3460  st->info->codec_info_duration < 0)
3461  continue;
3463  st->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3464  st->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3465 
3466  /* Round guessed framerate to a "standard" framerate if it's
3467  * within 1% of the original estimate. */
3468  for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3469  AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3470  double error = fabs(av_q2d(st->avg_frame_rate) /
3471  av_q2d(std_fps) - 1);
3472 
3473  if (error < best_error) {
3474  best_error = error;
3475  best_fps = std_fps.num;
3476  }
3477  }
3478  if (best_fps)
3480  best_fps, 12 * 1001, INT_MAX);
3481  }
3482 
3483  if (!st->r_frame_rate.num) {
3484  if ( st->codec->time_base.den * (int64_t) st->time_base.num
3485  <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t) st->time_base.den) {
3486  st->r_frame_rate.num = st->codec->time_base.den;
3488  } else {
3489  st->r_frame_rate.num = st->time_base.den;
3490  st->r_frame_rate.den = st->time_base.num;
3491  }
3492  }
3494  AVRational hw_ratio = { st->codec->height, st->codec->width };
3496  hw_ratio);
3497  }
3498  } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3499  if (!st->codec->bits_per_coded_sample)
3502  // set stream disposition based on audio service type
3503  switch (st->codec->audio_service_type) {
3506  break;
3509  break;
3512  break;
3515  break;
3518  break;
3519  }
3520  }
3521  }
3522 
3523  if (probesize)
3524  estimate_timings(ic, old_offset);
3525 
3526  av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
3527 
3528  if (ret >= 0 && ic->nb_streams)
3529  /* We could not have all the codec parameters before EOF. */
3530  ret = -1;
3531  for (i = 0; i < ic->nb_streams; i++) {
3532  const char *errmsg;
3533  st = ic->streams[i];
3534  if (!has_codec_parameters(st, &errmsg)) {
3535  char buf[256];
3536  avcodec_string(buf, sizeof(buf), st->codec, 0);
3537  av_log(ic, AV_LOG_WARNING,
3538  "Could not find codec parameters for stream %d (%s): %s\n"
3539  "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",
3540  i, buf, errmsg);
3541  } else {
3542  ret = 0;
3543  }
3544  }
3545 
3547 
3548 find_stream_info_err:
3549  for (i = 0; i < ic->nb_streams; i++) {
3550  st = ic->streams[i];
3551  if (ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3552  ic->streams[i]->codec->thread_count = 0;
3553  if (st->info)
3554  av_freep(&st->info->duration_error);
3555  avcodec_close(st->codec);
3556  av_freep(&ic->streams[i]->info);
3557  }
3558  if (ic->pb)
3559  av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
3560  avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
3561  return ret;
3562 }
3563 
3565 {
3566  int i, j;
3567 
3568  for (i = 0; i < ic->nb_programs; i++) {
3569  if (ic->programs[i] == last) {
3570  last = NULL;
3571  } else {
3572  if (!last)
3573  for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
3574  if (ic->programs[i]->stream_index[j] == s)
3575  return ic->programs[i];
3576  }
3577  }
3578  return NULL;
3579 }
3580 
3582  int wanted_stream_nb, int related_stream,
3583  AVCodec **decoder_ret, int flags)
3584 {
3585  int i, nb_streams = ic->nb_streams;
3586  int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
3587  unsigned *program = NULL;
3588  const AVCodec *decoder = NULL, *best_decoder = NULL;
3589 
3590  if (related_stream >= 0 && wanted_stream_nb < 0) {
3591  AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
3592  if (p) {
3593  program = p->stream_index;
3594  nb_streams = p->nb_stream_indexes;
3595  }
3596  }
3597  for (i = 0; i < nb_streams; i++) {
3598  int real_stream_index = program ? program[i] : i;
3599  AVStream *st = ic->streams[real_stream_index];
3600  AVCodecContext *avctx = st->codec;
3601  if (avctx->codec_type != type)
3602  continue;
3603  if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
3604  continue;
3605  if (wanted_stream_nb != real_stream_index &&
3608  continue;
3609  if (type == AVMEDIA_TYPE_AUDIO && !(avctx->channels && avctx->sample_rate))
3610  continue;
3611  if (decoder_ret) {
3612  decoder = find_decoder(ic, st, st->codec->codec_id);
3613  if (!decoder) {
3614  if (ret < 0)
3616  continue;
3617  }
3618  }
3620  bitrate = avctx->bit_rate;
3621  if (!bitrate)
3622  bitrate = avctx->rc_max_rate;
3623  multiframe = FFMIN(5, count);
3624  if ((best_multiframe > multiframe) ||
3625  (best_multiframe == multiframe && best_bitrate > bitrate) ||
3626  (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
3627  continue;
3628  best_count = count;
3629  best_bitrate = bitrate;
3630  best_multiframe = multiframe;
3631  ret = real_stream_index;
3632  best_decoder = decoder;
3633  if (program && i == nb_streams - 1 && ret < 0) {
3634  program = NULL;
3635  nb_streams = ic->nb_streams;
3636  /* no related stream found, try again with everything */
3637  i = 0;
3638  }
3639  }
3640  if (decoder_ret)
3641  *decoder_ret = (AVCodec*)best_decoder;
3642  return ret;
3643 }
3644 
3645 /*******************************************************/
3646 
3648 {
3649  if (s->iformat->read_play)
3650  return s->iformat->read_play(s);
3651  if (s->pb)
3652  return avio_pause(s->pb, 0);
3653  return AVERROR(ENOSYS);
3654 }
3655 
3657 {
3658  if (s->iformat->read_pause)
3659  return s->iformat->read_pause(s);
3660  if (s->pb)
3661  return avio_pause(s->pb, 1);
3662  return AVERROR(ENOSYS);
3663 }
3664 
3666  int j;
3667  av_assert0(s->nb_streams>0);
3668  av_assert0(s->streams[ s->nb_streams - 1 ] == st);
3669 
3670  for (j = 0; j < st->nb_side_data; j++)
3671  av_freep(&st->side_data[j].data);
3672  av_freep(&st->side_data);
3673  st->nb_side_data = 0;
3674 
3675  if (st->parser) {
3676  av_parser_close(st->parser);
3677  }
3678  if (st->attached_pic.data)
3680  av_dict_free(&st->metadata);
3681  av_freep(&st->probe_data.buf);
3682  av_freep(&st->index_entries);
3684  av_freep(&st->priv_data);
3685  if (st->info)
3686  av_freep(&st->info->duration_error);
3687  av_freep(&st->info);
3689  av_freep(&st->priv_pts);
3690  av_freep(&s->streams[ --s->nb_streams ]);
3691 }
3692 
3694 {
3695  int i;
3696 
3697  if (!s)
3698  return;
3699 
3700  av_opt_free(s);
3701  if (s->iformat && s->iformat->priv_class && s->priv_data)
3702  av_opt_free(s->priv_data);
3703  if (s->oformat && s->oformat->priv_class && s->priv_data)
3704  av_opt_free(s->priv_data);
3705 
3706  for (i = s->nb_streams - 1; i >= 0; i--) {
3707  ff_free_stream(s, s->streams[i]);
3708  }
3709  for (i = s->nb_programs - 1; i >= 0; i--) {
3710  av_dict_free(&s->programs[i]->metadata);
3711  av_freep(&s->programs[i]->stream_index);
3712  av_freep(&s->programs[i]);
3713  }
3714  av_freep(&s->programs);
3715  av_freep(&s->priv_data);
3716  while (s->nb_chapters--) {
3718  av_freep(&s->chapters[s->nb_chapters]);
3719  }
3720  av_freep(&s->chapters);
3721  av_dict_free(&s->metadata);
3722  av_freep(&s->streams);
3723  flush_packet_queue(s);
3724  av_freep(&s->internal);
3725  av_free(s);
3726 }
3727 
3729 {
3730  AVFormatContext *s;
3731  AVIOContext *pb;
3732 
3733  if (!ps || !*ps)
3734  return;
3735 
3736  s = *ps;
3737  pb = s->pb;
3738 
3739  if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
3740  (s->flags & AVFMT_FLAG_CUSTOM_IO))
3741  pb = NULL;
3742 
3743  flush_packet_queue(s);
3744 
3745  if (s->iformat)
3746  if (s->iformat->read_close)
3747  s->iformat->read_close(s);
3748 
3750 
3751  *ps = NULL;
3752 
3753  avio_close(pb);
3754 }
3755 
3757 {
3758  AVStream *st;
3759  int i;
3760  AVStream **streams;
3761 
3762  if (s->nb_streams >= FFMIN(s->max_streams, INT_MAX/sizeof(*streams))) {
3763  if (s->max_streams < INT_MAX/sizeof(*streams))
3764  av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter (%d), see the documentation if you wish to increase it\n", s->max_streams);
3765  return NULL;
3766  }
3767  streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
3768  if (!streams)
3769  return NULL;
3770  s->streams = streams;
3771 
3772  st = av_mallocz(sizeof(AVStream));
3773  if (!st)
3774  return NULL;
3775  if (!(st->info = av_mallocz(sizeof(*st->info)))) {
3776  av_free(st);
3777  return NULL;
3778  }
3779  st->info->last_dts = AV_NOPTS_VALUE;
3780 
3781  st->codec = avcodec_alloc_context3(c);
3782  if (!st->codec) {
3783  av_free(st->info);
3784  av_free(st);
3785  return NULL;
3786  }
3787  if (s->iformat) {
3788  /* no default bitrate if decoding */
3789  st->codec->bit_rate = 0;
3790 
3791  /* default pts setting is MPEG-like */
3792  avpriv_set_pts_info(st, 33, 1, 90000);
3793  }
3794 
3795  st->index = s->nb_streams;
3796  st->start_time = AV_NOPTS_VALUE;
3797  st->duration = AV_NOPTS_VALUE;
3798  /* we set the current DTS to 0 so that formats without any timestamps
3799  * but durations get some timestamps, formats with some unknown
3800  * timestamps have their first few packets buffered and the
3801  * timestamps corrected before they are returned to the user */
3802  st->cur_dts = s->iformat ? RELATIVE_TS_BASE : 0;
3803  st->first_dts = AV_NOPTS_VALUE;
3807 
3810  for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
3811  st->pts_buffer[i] = AV_NOPTS_VALUE;
3812 
3813  st->sample_aspect_ratio = (AVRational) { 0, 1 };
3814 
3815 #if FF_API_R_FRAME_RATE
3816  st->info->last_dts = AV_NOPTS_VALUE;
3817 #endif
3820 
3822 
3823  s->streams[s->nb_streams++] = st;
3824  return st;
3825 }
3826 
3828 {
3829  AVProgram *program = NULL;
3830  int i;
3831 
3832  av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
3833 
3834  for (i = 0; i < ac->nb_programs; i++)
3835  if (ac->programs[i]->id == id)
3836  program = ac->programs[i];
3837 
3838  if (!program) {
3839  program = av_mallocz(sizeof(AVProgram));
3840  if (!program)
3841  return NULL;
3842  dynarray_add(&ac->programs, &ac->nb_programs, program);
3843  program->discard = AVDISCARD_NONE;
3844  }
3845  program->id = id;
3848 
3849  program->start_time =
3850  program->end_time = AV_NOPTS_VALUE;
3851 
3852  return program;
3853 }
3854 
3856  int64_t start, int64_t end, const char *title)
3857 {
3858  AVChapter *chapter = NULL;
3859  int i;
3860 
3861  if (end != AV_NOPTS_VALUE && start > end) {
3862  av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
3863  return NULL;
3864  }
3865 
3866  for (i = 0; i < s->nb_chapters; i++)
3867  if (s->chapters[i]->id == id)
3868  chapter = s->chapters[i];
3869 
3870  if (!chapter) {
3871  chapter = av_mallocz(sizeof(AVChapter));
3872  if (!chapter)
3873  return NULL;
3874  dynarray_add(&s->chapters, &s->nb_chapters, chapter);
3875  }
3876  av_dict_set(&chapter->metadata, "title", title, 0);
3877  chapter->id = id;
3878  chapter->time_base = time_base;
3879  chapter->start = start;
3880  chapter->end = end;
3881 
3882  return chapter;
3883 }
3884 
3885 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
3886 {
3887  int i, j;
3888  AVProgram *program = NULL;
3889  void *tmp;
3890 
3891  if (idx >= ac->nb_streams) {
3892  av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3893  return;
3894  }
3895 
3896  for (i = 0; i < ac->nb_programs; i++) {
3897  if (ac->programs[i]->id != progid)
3898  continue;
3899  program = ac->programs[i];
3900  for (j = 0; j < program->nb_stream_indexes; j++)
3901  if (program->stream_index[j] == idx)
3902  return;
3903 
3904  tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
3905  if (!tmp)
3906  return;
3907  program->stream_index = tmp;
3908  program->stream_index[program->nb_stream_indexes++] = idx;
3909  return;
3910  }
3911 }
3912 
3913 uint64_t ff_ntp_time(void)
3914 {
3915  return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3916 }
3917 
3918 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
3919 {
3920  const char *p;
3921  char *q, buf1[20], c;
3922  int nd, len, percentd_found;
3923 
3924  q = buf;
3925  p = path;
3926  percentd_found = 0;
3927  for (;;) {
3928  c = *p++;
3929  if (c == '\0')
3930  break;
3931  if (c == '%') {
3932  do {
3933  nd = 0;
3934  while (av_isdigit(*p))
3935  nd = nd * 10 + *p++ - '0';
3936  c = *p++;
3937  } while (av_isdigit(c));
3938 
3939  switch (c) {
3940  case '%':
3941  goto addchar;
3942  case 'd':
3943  if (percentd_found)
3944  goto fail;
3945  percentd_found = 1;
3946  if (number < 0)
3947  nd += 1;
3948  snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3949  len = strlen(buf1);
3950  if ((q - buf + len) > buf_size - 1)
3951  goto fail;
3952  memcpy(q, buf1, len);
3953  q += len;
3954  break;
3955  default:
3956  goto fail;
3957  }
3958  } else {
3959 addchar:
3960  if ((q - buf) < buf_size - 1)
3961  *q++ = c;
3962  }
3963  }
3964  if (!percentd_found)
3965  goto fail;
3966  *q = '\0';
3967  return 0;
3968 fail:
3969  *q = '\0';
3970  return -1;
3971 }
3972 
3973 void av_url_split(char *proto, int proto_size,
3974  char *authorization, int authorization_size,
3975  char *hostname, int hostname_size,
3976  int *port_ptr, char *path, int path_size, const char *url)
3977 {
3978  const char *p, *ls, *ls2, *at, *at2, *col, *brk;
3979 
3980  if (port_ptr)
3981  *port_ptr = -1;
3982  if (proto_size > 0)
3983  proto[0] = 0;
3984  if (authorization_size > 0)
3985  authorization[0] = 0;
3986  if (hostname_size > 0)
3987  hostname[0] = 0;
3988  if (path_size > 0)
3989  path[0] = 0;
3990 
3991  /* parse protocol */
3992  if ((p = strchr(url, ':'))) {
3993  av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3994  p++; /* skip ':' */
3995  if (*p == '/')
3996  p++;
3997  if (*p == '/')
3998  p++;
3999  } else {
4000  /* no protocol means plain filename */
4001  av_strlcpy(path, url, path_size);
4002  return;
4003  }
4004 
4005  /* separate path from hostname */
4006  ls = strchr(p, '/');
4007  ls2 = strchr(p, '?');
4008  if (!ls)
4009  ls = ls2;
4010  else if (ls && ls2)
4011  ls = FFMIN(ls, ls2);
4012  if (ls)
4013  av_strlcpy(path, ls, path_size);
4014  else
4015  ls = &p[strlen(p)]; // XXX
4016 
4017  /* the rest is hostname, use that to parse auth/port */
4018  if (ls != p) {
4019  /* authorization (user[:pass]@hostname) */
4020  at2 = p;
4021  while ((at = strchr(p, '@')) && at < ls) {
4022  av_strlcpy(authorization, at2,
4023  FFMIN(authorization_size, at + 1 - at2));
4024  p = at + 1; /* skip '@' */
4025  }
4026 
4027  if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4028  /* [host]:port */
4029  av_strlcpy(hostname, p + 1,
4030  FFMIN(hostname_size, brk - p));
4031  if (brk[1] == ':' && port_ptr)
4032  *port_ptr = atoi(brk + 2);
4033  } else if ((col = strchr(p, ':')) && col < ls) {
4034  av_strlcpy(hostname, p,
4035  FFMIN(col + 1 - p, hostname_size));
4036  if (port_ptr)
4037  *port_ptr = atoi(col + 1);
4038  } else
4039  av_strlcpy(hostname, p,
4040  FFMIN(ls + 1 - p, hostname_size));
4041  }
4042 }
4043 
4044 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4045 {
4046  int i;
4047  static const char hex_table_uc[16] = { '0', '1', '2', '3',
4048  '4', '5', '6', '7',
4049  '8', '9', 'A', 'B',
4050  'C', 'D', 'E', 'F' };
4051  static const char hex_table_lc[16] = { '0', '1', '2', '3',
4052  '4', '5', '6', '7',
4053  '8', '9', 'a', 'b',
4054  'c', 'd', 'e', 'f' };
4055  const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4056 
4057  for (i = 0; i < s; i++) {
4058  buff[i * 2] = hex_table[src[i] >> 4];
4059  buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4060  }
4061 
4062  return buff;
4063 }
4064 
4065 int ff_hex_to_data(uint8_t *data, const char *p)
4066 {
4067  int c, len, v;
4068 
4069  len = 0;
4070  v = 1;
4071  for (;;) {
4072  p += strspn(p, SPACE_CHARS);
4073  if (*p == '\0')
4074  break;
4075  c = av_toupper((unsigned char) *p++);
4076  if (c >= '0' && c <= '9')
4077  c = c - '0';
4078  else if (c >= 'A' && c <= 'F')
4079  c = c - 'A' + 10;
4080  else
4081  break;
4082  v = (v << 4) | c;
4083  if (v & 0x100) {
4084  if (data)
4085  data[len] = v;
4086  len++;
4087  v = 1;
4088  }
4089  }
4090  return len;
4091 }
4092 
4093 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4094  unsigned int pts_num, unsigned int pts_den)
4095 {
4096  AVRational new_tb;
4097  if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4098  if (new_tb.num != pts_num)
4100  "st:%d removing common factor %d from timebase\n",
4101  s->index, pts_num / new_tb.num);
4102  } else
4104  "st:%d has too large timebase, reducing\n", s->index);
4105 
4106  if (new_tb.num <= 0 || new_tb.den <= 0) {
4108  "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4109  new_tb.num, new_tb.den,
4110  s->index);
4111  return;
4112  }
4113  s->time_base = new_tb;
4114  av_codec_set_pkt_timebase(s->codec, new_tb);
4115  s->pts_wrap_bits = pts_wrap_bits;
4116 }
4117 
4118 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4119  void *context)
4120 {
4121  const char *ptr = str;
4122 
4123  /* Parse key=value pairs. */
4124  for (;;) {
4125  const char *key;
4126  char *dest = NULL, *dest_end;
4127  int key_len, dest_len = 0;
4128 
4129  /* Skip whitespace and potential commas. */
4130  while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4131  ptr++;
4132  if (!*ptr)
4133  break;
4134 
4135  key = ptr;
4136 
4137  if (!(ptr = strchr(key, '=')))
4138  break;
4139  ptr++;
4140  key_len = ptr - key;
4141 
4142  callback_get_buf(context, key, key_len, &dest, &dest_len);
4143  dest_end = dest + dest_len - 1;
4144 
4145  if (*ptr == '\"') {
4146  ptr++;
4147  while (*ptr && *ptr != '\"') {
4148  if (*ptr == '\\') {
4149  if (!ptr[1])
4150  break;
4151  if (dest && dest < dest_end)
4152  *dest++ = ptr[1];
4153  ptr += 2;
4154  } else {
4155  if (dest && dest < dest_end)
4156  *dest++ = *ptr;
4157  ptr++;
4158  }
4159  }
4160  if (*ptr == '\"')
4161  ptr++;
4162  } else {
4163  for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4164  if (dest && dest < dest_end)
4165  *dest++ = *ptr;
4166  }
4167  if (dest)
4168  *dest = 0;
4169  }
4170 }
4171 
4173 {
4174  int i;
4175  for (i = 0; i < s->nb_streams; i++)
4176  if (s->streams[i]->id == id)
4177  return i;
4178  return -1;
4179 }
4180 
4181 int64_t ff_iso8601_to_unix_time(const char *datestr)
4182 {
4183  struct tm time1 = { 0 }, time2 = { 0 };
4184  const char *ret1, *ret2;
4185  ret1 = av_small_strptime(datestr, "%Y - %m - %d %T", &time1);
4186  ret2 = av_small_strptime(datestr, "%Y - %m - %dT%T", &time2);
4187  if (ret2 && !ret1)
4188  return av_timegm(&time2);
4189  else
4190  return av_timegm(&time1);
4191 }
4192 
4194  int std_compliance)
4195 {
4196  if (ofmt) {
4197  unsigned int codec_tag;
4198  if (ofmt->query_codec)
4199  return ofmt->query_codec(codec_id, std_compliance);
4200  else if (ofmt->codec_tag)
4201  return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
4202  else if (codec_id == ofmt->video_codec ||
4203  codec_id == ofmt->audio_codec ||
4204  codec_id == ofmt->subtitle_codec)
4205  return 1;
4206  }
4207  return AVERROR_PATCHWELCOME;
4208 }
4209 
4211 {
4212 #if CONFIG_NETWORK
4213  int ret;
4215  if ((ret = ff_network_init()) < 0)
4216  return ret;
4217  if ((ret = ff_tls_init()) < 0)
4218  return ret;
4219 #endif
4220  return 0;
4221 }
4222 
4224 {
4225 #if CONFIG_NETWORK
4226  ff_network_close();
4227  ff_tls_deinit();
4229 #endif
4230  return 0;
4231 }
4232 
4234  uint64_t channel_layout, int32_t sample_rate,
4236 {
4237  uint32_t flags = 0;
4238  int size = 4;
4239  uint8_t *data;
4240  if (!pkt)
4241  return AVERROR(EINVAL);
4242  if (channels) {
4243  size += 4;
4245  }
4246  if (channel_layout) {
4247  size += 8;
4249  }
4250  if (sample_rate) {
4251  size += 4;
4253  }
4254  if (width || height) {
4255  size += 8;
4257  }
4259  if (!data)
4260  return AVERROR(ENOMEM);
4261  bytestream_put_le32(&data, flags);
4262  if (channels)
4263  bytestream_put_le32(&data, channels);
4264  if (channel_layout)
4265  bytestream_put_le64(&data, channel_layout);
4266  if (sample_rate)
4267  bytestream_put_le32(&data, sample_rate);
4268  if (width || height) {
4269  bytestream_put_le32(&data, width);
4270  bytestream_put_le32(&data, height);
4271  }
4272  return 0;
4273 }
4274 
4276 {
4277  AVRational undef = {0, 1};
4278  AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
4279  AVRational codec_sample_aspect_ratio = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
4280  AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
4281 
4282  av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
4283  stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
4284  if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
4285  stream_sample_aspect_ratio = undef;
4286 
4287  av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
4288  frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
4289  if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
4290  frame_sample_aspect_ratio = undef;
4291 
4292  if (stream_sample_aspect_ratio.num)
4293  return stream_sample_aspect_ratio;
4294  else
4295  return frame_sample_aspect_ratio;
4296 }
4297 
4299 {
4300  AVRational fr = st->r_frame_rate;
4301  AVRational codec_fr = st->codec->framerate;
4302  AVRational avg_fr = st->avg_frame_rate;
4303 
4304  if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
4305  av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
4306  fr = avg_fr;
4307  }
4308 
4309 
4310  if (st->codec->ticks_per_frame > 1) {
4311  if ( codec_fr.num > 0 && codec_fr.den > 0 &&
4312  (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
4313  fr = codec_fr;
4314  }
4315 
4316  return fr;
4317 }
4318 
4320  const char *spec)
4321 {
4322  if (*spec <= '9' && *spec >= '0') /* opt:index */
4323  return strtol(spec, NULL, 0) == st->index;
4324  else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
4325  *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
4326  enum AVMediaType type;
4327  int nopic = 0;
4328 
4329  switch (*spec++) {
4330  case 'v': type = AVMEDIA_TYPE_VIDEO; break;
4331  case 'a': type = AVMEDIA_TYPE_AUDIO; break;
4332  case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
4333  case 'd': type = AVMEDIA_TYPE_DATA; break;
4334  case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
4335  case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
4336  default: av_assert0(0);
4337  }
4338  if (type != st->codec->codec_type)
4339  return 0;
4340  if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
4341  return 0;
4342  if (*spec++ == ':') { /* possibly followed by :index */
4343  int i, index = strtol(spec, NULL, 0);
4344  for (i = 0; i < s->nb_streams; i++)
4345  if (s->streams[i]->codec->codec_type == type &&
4346  !(nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC)) &&
4347  index-- == 0)
4348  return i == st->index;
4349  return 0;
4350  }
4351  return 1;
4352  } else if (*spec == 'p' && *(spec + 1) == ':') {
4353  int prog_id, i, j;
4354  char *endptr;
4355  spec += 2;
4356  prog_id = strtol(spec, &endptr, 0);
4357  for (i = 0; i < s->nb_programs; i++) {
4358  if (s->programs[i]->id != prog_id)
4359  continue;
4360 
4361  if (*endptr++ == ':') {
4362  int stream_idx = strtol(endptr, NULL, 0);
4363  return stream_idx >= 0 &&
4364  stream_idx < s->programs[i]->nb_stream_indexes &&
4365  st->index == s->programs[i]->stream_index[stream_idx];
4366  }
4367 
4368  for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
4369  if (st->index == s->programs[i]->stream_index[j])
4370  return 1;
4371  }
4372  return 0;
4373  } else if (*spec == '#' ||
4374  (*spec == 'i' && *(spec + 1) == ':')) {
4375  int stream_id;
4376  char *endptr;
4377  spec += 1 + (*spec == 'i');
4378  stream_id = strtol(spec, &endptr, 0);
4379  if (!*endptr)
4380  return stream_id == st->id;
4381  } else if (*spec == 'm' && *(spec + 1) == ':') {
4383  char *key, *val;
4384  int ret;
4385 
4386  spec += 2;
4387  val = strchr(spec, ':');
4388 
4389  key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
4390  if (!key)
4391  return AVERROR(ENOMEM);
4392 
4393  tag = av_dict_get(st->metadata, key, NULL, 0);
4394  if (tag) {
4395  if (!val || !strcmp(tag->value, val + 1))
4396  ret = 1;
4397  else
4398  ret = 0;
4399  } else
4400  ret = 0;
4401 
4402  av_freep(&key);
4403  return ret;
4404  } else if (*spec == 'u') {
4405  AVCodecContext *avctx = st->codec;
4406  int val;
4407  switch (avctx->codec_type) {
4408  case AVMEDIA_TYPE_AUDIO:
4409  val = avctx->sample_rate && avctx->channels;
4410  if (avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
4411  return 0;
4412  break;
4413  case AVMEDIA_TYPE_VIDEO:
4414  val = avctx->width && avctx->height;
4415  if (avctx->pix_fmt == AV_PIX_FMT_NONE)
4416  return 0;
4417  break;
4418  case AVMEDIA_TYPE_UNKNOWN:
4419  val = 0;
4420  break;
4421  default:
4422  val = 1;
4423  break;
4424  }
4425  return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
4426  } else if (!*spec) /* empty specifier, matches everything */
4427  return 1;
4428 
4429  av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
4430  return AVERROR(EINVAL);
4431 }
4432 
4434 {
4435  static const uint8_t avci100_1080p_extradata[] = {
4436  // SPS
4437  0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4438  0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4439  0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4440  0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
4441  0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
4442  0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
4443  0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
4444  0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
4445  0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4446  // PPS
4447  0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4448  0xd0
4449  };
4450  static const uint8_t avci100_1080i_extradata[] = {
4451  // SPS
4452  0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4453  0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4454  0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4455  0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
4456  0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
4457  0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
4458  0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
4459  0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
4460  0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
4461  0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
4462  0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
4463  // PPS
4464  0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4465  0xd0
4466  };
4467  static const uint8_t avci50_1080p_extradata[] = {
4468  // SPS
4469  0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4470  0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4471  0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4472  0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4473  0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4474  0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
4475  0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
4476  0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
4477  0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
4478  // PPS
4479  0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4480  0x11
4481  };
4482  static const uint8_t avci50_1080i_extradata[] = {
4483  // SPS
4484  0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4485  0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4486  0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4487  0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
4488  0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
4489  0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
4490  0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
4491  0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
4492  0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
4493  0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
4494  0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
4495  // PPS
4496  0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4497  0x11
4498  };
4499  static const uint8_t avci100_720p_extradata[] = {
4500  // SPS
4501  0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4502  0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
4503  0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
4504  0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
4505  0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
4506  0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
4507  0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
4508  0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
4509  0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
4510  0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
4511  // PPS
4512  0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
4513  0x11
4514  };
4515  static const uint8_t avci50_720p_extradata[] = {
4516  // SPS
4517  0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
4518  0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4519  0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4520  0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4521  0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4522  0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
4523  0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
4524  0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
4525  0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
4526  // PPS
4527  0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4528  0x11
4529  };
4530 
4531  const uint8_t *data = NULL;
4532  int size = 0;
4533 
4534  if (st->codec->width == 1920) {
4535  if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4536  data = avci100_1080p_extradata;
4537  size = sizeof(avci100_1080p_extradata);
4538  } else {
4539  data = avci100_1080i_extradata;
4540  size = sizeof(avci100_1080i_extradata);
4541  }
4542  } else if (st->codec->width == 1440) {
4543  if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4544  data = avci50_1080p_extradata;
4545  size = sizeof(avci50_1080p_extradata);
4546  } else {
4547  data = avci50_1080i_extradata;
4548  size = sizeof(avci50_1080i_extradata);
4549  }
4550  } else if (st->codec->width == 1280) {
4551  data = avci100_720p_extradata;
4552  size = sizeof(avci100_720p_extradata);
4553  } else if (st->codec->width == 960) {
4554  data = avci50_720p_extradata;
4555  size = sizeof(avci50_720p_extradata);
4556  }
4557 
4558  if (!size)
4559  return 0;
4560 
4561  av_freep(&st->codec->extradata);
4562  if (ff_alloc_extradata(st->codec, size))
4563  return AVERROR(ENOMEM);
4564  memcpy(st->codec->extradata, data, size);
4565 
4566  return 0;
4567 }
4568 
4570  int *size)
4571 {
4572  int i;
4573 
4574  for (i = 0; i < st->nb_side_data; i++) {
4575  if (st->side_data[i].type == type) {
4576  if (size)
4577  *size = st->side_data[i].size;
4578  return st->side_data[i].data;
4579  }
4580  }
4581  return NULL;
4582 }
4583 
4585  int size)
4586 {
4587  AVPacketSideData *sd, *tmp;
4588  int i;
4589  uint8_t *data = av_malloc(size);
4590 
4591  if (!data)
4592  return NULL;
4593 
4594  for (i = 0; i < st->nb_side_data; i++) {
4595  sd = &st->side_data[i];
4596 
4597  if (sd->type == type) {
4598  av_freep(&sd->data);
4599  sd->data = data;
4600  sd->size = size;
4601  return sd->data;
4602  }
4603  }
4604 
4605  tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));
4606  if (!tmp) {
4607  av_freep(&data);
4608  return NULL;
4609  }
4610 
4611  st->side_data = tmp;
4612  st->nb_side_data++;
4613 
4614  sd = &st->side_data[st->nb_side_data - 1];
4615  sd->type = type;
4616  sd->data = data;
4617  sd->size = size;
4618  return data;
4619 }
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1486
time_t av_timegm(struct tm *tm)
Convert the decomposed UTC time in tm to a time_t value.
Definition: parseutils.c:539
unsigned int max_index_size
Maximum amount of memory in bytes to use for the index of each stream.
Definition: avformat.h:1467
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:3973
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:2296
int64_t probesize
Maximum size of the data read from input for determining the input container format.
Definition: avformat.h:1799
int av_opt_get_dict_val(void *obj, const char *name, int search_flags, AVDictionary **out_val)
Definition: opt.c:942
int64_t first_dts
Timestamp corresponding to the last dts sync point.
Definition: avformat.h:1030
#define NULL
Definition: coverity.c:32
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:3855
int av_isdigit(int c)
Locale-independent conversion of ASCII isdigit.
Definition: avstring.c:320
const struct AVCodec * codec
Definition: avcodec.h:1521
full parsing and interpolation of timestamps for frames not starting on a packet boundary ...
Definition: avformat.h:788
AVRational framerate
Definition: avcodec.h:3312
const char const char void * val
Definition: avisynth_c.h:634
#define AV_CODEC_PROP_INTRA_ONLY
Codec uses only intra compression.
Definition: avcodec.h:596
static void fill_all_stream_timings(AVFormatContext *ic)
Definition: utils.c:2390
#define AVFMT_NOBINSEARCH
Format does not allow to fall back on binary search via read_timestamp.
Definition: avformat.h:490
int64_t duration_gcd
Definition: avformat.h:994
float v
const char * s
Definition: avisynth_c.h:631
Bytestream IO Context.
Definition: avio.h:111
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
static void update_initial_durations(AVFormatContext *s, AVStream *st, int stream_index, int duration)
Definition: utils.c:937
AVProbeData probe_data
Definition: avformat.h:1053
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:284
#define AV_PTS_WRAP_ADD_OFFSET
add the format specific offset on wrap detection
Definition: avformat.h:844
static int shift(int a, int b)
Definition: sonic.c:82
AVPacketSideDataType
Definition: avcodec.h:1224
enum AVCodecID id
Definition: internal.h:43
int av_demuxer_open(AVFormatContext *ic)
Definition: utils.c:312
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:284
char * recommended_encoder_configuration
String containing paris of key and values describing recommended encoder configuration.
Definition: avformat.h:1185
struct AVPacketList * raw_packet_buffer
Raw packets from the demuxer, prior to parsing and decoding.
Definition: internal.h:88
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
int64_t(* read_timestamp)(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit)
Get the next timestamp in stream[stream_index].time_base units.
Definition: avformat.h:739
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1535
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
void(* ff_parse_key_val_cb)(void *context, const char *key, int key_len, char **dest, int *dest_len)
Callback function type for ff_parse_key_value.
Definition: internal.h:237
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1748
static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit, int64_t(*read_timestamp)(struct AVFormatContext *, int, int64_t *, int64_t))
Definition: utils.c:1853
static void update_stream_timings(AVFormatContext *ic)
Estimate the stream timings from the one of each components.
Definition: utils.c:2315
struct AVPacketList * parse_queue_end
Definition: internal.h:94
enum AVCodecID id
Definition: mxfenc.c:102
static int get_std_framerate(int i)
Definition: utils.c:2899
const char * fmt
Definition: avisynth_c.h:632
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
Rescale a 64-bit integer with specified rounding.
Definition: mathematics.c:63
enum AVDurationEstimationMethod duration_estimation_method
The duration field can be estimated through various ways, and this field can be used to know how the ...
Definition: avformat.h:1644
int64_t start_skip_samples
If not 0, the number of samples that should be skipped from the start of the stream (the samples are ...
Definition: avformat.h:1111
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
uint8_t * ff_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type, int size)
Add new side data to a stream.
Definition: utils.c:4584
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1458
void av_shrink_packet(AVPacket *pkt, int size)
Reduce packet size, correctly zeroing padding.
Definition: avpacket.c:104
int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
Perform a binary search using av_index_search_timestamp() and AVInputFormat.read_timestamp().
Definition: utils.c:1862
int64_t pts_buffer[MAX_REORDER_DELAY+1]
Definition: avformat.h:1055
int64_t pos
Definition: avformat.h:796
int probe_packets
Number of packets to buffer for codec probing.
Definition: avformat.h:1038
#define NTP_OFFSET_US
Definition: internal.h:160
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2298
int64_t data_offset
offset of the first packet
Definition: internal.h:80
struct FFFrac * priv_pts
Definition: avformat.h:1194
#define a0
Definition: regdef.h:46
AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
Guess the sample aspect ratio of a frame, based on both the stream and the frame aspect ratio...
Definition: utils.c:4275
enum AVCodecID video_codec
default video codec
Definition: avformat.h:536
void av_opt_set_defaults(void *s)
Set the values of all AVOption fields to their default values.
Definition: opt.c:1178
int64_t first_discard_sample
If not 0, the first audio sample that should be discarded from the stream.
Definition: avformat.h:1119
static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
Wrap a given time stamp, if there is an indication for an overflow.
Definition: utils.c:92
int64_t pts_wrap_reference
Internal data to check for wrapping of the time stamp.
Definition: avformat.h:1143
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:926
void av_codec_set_pkt_timebase(AVCodecContext *avctx, AVRational val)
int num
numerator
Definition: rational.h:44
int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries, int64_t wanted_timestamp, int flags)
Internal version of av_index_search_timestamp.
Definition: utils.c:1757
int index
stream index in AVFormatContext
Definition: avformat.h:855
int size
Definition: avcodec.h:1434
const char * b
Definition: vf_curves.c:109
static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
Definition: utils.c:2464
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
Definition: id3v2.h:35
int avio_flags
avio flags, used to force AVIO_FLAG_DIRECT.
Definition: avformat.h:1636
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:204
#define AVIO_FLAG_READ
read-only
Definition: avio.h:485
#define AVPROBE_PADDING_SIZE
extra allocated bytes at the end of the probe buffer
Definition: avformat.h:474
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1057
AVFormatInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1710
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel...
Definition: avcodec.h:1912
int ff_find_stream_index(AVFormatContext *s, int id)
Find stream index based on format-specific stream ID.
Definition: utils.c:4172
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1732
uint8_t * av_stream_get_side_data(AVStream *st, enum AVPacketSideDataType type, int *size)
Get side information from stream.
Definition: utils.c:4569
#define AV_PTS_WRAP_SUB_OFFSET
subtract the format specific offset on wrap detection
Definition: avformat.h:845
void ff_network_close(void)
Definition: network.c:102
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1572
#define AV_DISPOSITION_HEARING_IMPAIRED
stream for hearing impaired audiences
Definition: avformat.h:822
#define a1
Definition: regdef.h:47
static void estimate_timings_from_bit_rate(AVFormatContext *ic)
Definition: utils.c:2409
int ff_tls_init(void)
Definition: network.c:30
void * priv_data
Definition: avformat.h:874
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:279
#define AV_CODEC_CAP_CHANNEL_CONF
Codec should fill in channel configuration and samplerate instead of container.
Definition: avcodec.h:916
#define AV_DISPOSITION_CLEAN_EFFECTS
stream without voice
Definition: avformat.h:824
AVInputFormat * av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
Guess the file format.
Definition: format.c:173
int duration
Duration of the current frame.
Definition: avcodec.h:4682
discard all
Definition: avcodec.h:689
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:966
static AVPacket pkt
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf, void *context)
Parse a string with comma-separated key=value pairs.
Definition: utils.c:4118
int priv_data_size
Size of private data so that it can be allocated in the wrapper.
Definition: avformat.h:691
int ctx_flags
Flags signalling stream properties.
Definition: avformat.h:1334
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt)
Decode a subtitle message.
Definition: utils.c:2801
AVDictionary * metadata
Definition: avformat.h:1252
int av_opt_set_dict_val(void *obj, const char *name, const AVDictionary *val, int search_flags)
Definition: opt.c:671
int64_t maxsize
max filesize, used to limit allocations This field is internal to libavformat and access from outside...
Definition: avio.h:166
int av_dup_packet(AVPacket *pkt)
Definition: avpacket.c:252
static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
Definition: utils.c:1318
int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta **extra_meta)
Create a stream for each APIC (attached picture) extracted from the ID3v2 header. ...
Definition: id3v2.c:1078
#define sample
enum AVCodecID subtitle_codec_id
Forced subtitle codec_id.
Definition: avformat.h:1455
AVCodec.
Definition: avcodec.h:3482
static void force_codec_ids(AVFormatContext *s, AVStream *st)
Definition: utils.c:513
static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
Definition: utils.c:2637
static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
Definition: utils.c:2590
#define FFMPEG_LICENSE
Definition: config.h:5
static int has_decode_delay_been_guessed(AVStream *st)
Definition: utils.c:816
int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
Definition: h264.c:56
int64_t last_dts_for_order_check
Internal data to analyze DTS and detect faulty mpeg streams.
Definition: avformat.h:1171
#define AV_DISPOSITION_KARAOKE
Definition: avformat.h:814
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1641
Undefined.
Definition: avutil.h:265
enum AVAudioServiceType audio_service_type
Type of service that the audio stream conveys.
Definition: avcodec.h:2347
Format I/O context.
Definition: avformat.h:1285
AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
Guess the frame rate, based on both the container and codec information.
Definition: utils.c:4298
unsigned int nb_stream_indexes
Definition: avformat.h:1223
int ff_network_inited_globally
Definition: network.c:53
#define AVFMT_FLAG_NOPARSE
Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no...
Definition: avformat.h:1402
int64_t cur_dts
Definition: avformat.h:1031
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
internal metadata API header see avformat.h or the public API!
Public dictionary API.
#define DURATION_MAX_READ_SIZE
Definition: utils.c:2460
#define AVFMT_FLAG_DISCARD_CORRUPT
Discard frames marked corrupted.
Definition: avformat.h:1405
int(* read_close)(struct AVFormatContext *)
Close the stream.
Definition: avformat.h:722
static int64_t start_time
Definition: ffplay.c:325
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:2280
uint8_t
Round toward +infinity.
Definition: mathematics.h:74
static int nb_streams
Definition: ffprobe.c:226
#define av_malloc(s)
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:135
Opaque data information usually continuous.
Definition: avutil.h:195
#define AVFMT_FLAG_KEEP_SIDE_DATA
Don't merge side data but keep it separate.
Definition: avformat.h:1417
#define av_assert2(cond)
assert() equivalent, that does lie in speed critical code.
Definition: avassert.h:63
int ff_network_init(void)
Definition: network.c:55
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition: avformat.h:1244
AVOptions.
static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
Definition: utils.c:531
int flags
Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS, AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH, AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS.
Definition: avformat.h:654
int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition: avstring.c:330
timestamp utils, mostly useful for debugging/logging purposes
unsigned avformat_version(void)
Return the LIBAVFORMAT_VERSION_INT constant.
Definition: utils.c:62
const char * avformat_license(void)
Return the libavformat license.
Definition: utils.c:73
attribute_deprecated void(* destruct)(struct AVPacket *)
Definition: avcodec.h:1454
unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt)
Return a value representing the fourCC code associated to the pixel format pix_fmt, or 0 if no associated fourCC code can be found.
Definition: raw.c:233
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
AVPacket pkt
Definition: avformat.h:1875
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int id
unique ID to identify the chapter
Definition: avformat.h:1249
int id
Format-specific stream ID.
Definition: avformat.h:861
enum AVStreamParseType need_parsing
Definition: avformat.h:1046
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2780
int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
Check if the stream st contained in s is matched by the stream specifier spec.
Definition: utils.c:4319
int duration_count
Definition: avformat.h:995
#define AVFMT_FLAG_GENPTS
Generate missing pts even if it requires parsing future frames.
Definition: avformat.h:1397
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:970
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1627
int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0 and f...
Definition: utils.c:2959
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3756
static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
Definition: utils.c:268
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1353
char * av_small_strptime(const char *p, const char *fmt, struct tm *dt)
Simplified version of strptime.
Definition: parseutils.c:468
static AVFrame * frame
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:111
int inject_global_side_data
Internal data to inject global side data.
Definition: avformat.h:1178
const char * avformat_configuration(void)
Return the libavformat build-time configuration.
Definition: utils.c:68
int64_t bytes_read
Bytes read statistic This field is internal to libavformat and access from outside is not allowed...
Definition: avio.h:179
#define MAX_REORDER_DELAY
Definition: avformat.h:1054
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:665
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:80
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:39
int64_t last_duration
Definition: avformat.h:1008
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1396
#define DURATION_MAX_RETRY
Definition: utils.c:2461
uint8_t * data
Definition: avcodec.h:1433
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition: utils.c:3827
int(* read_header)(struct AVFormatContext *)
Read the format header and initialize the AVFormatContext structure.
Definition: avformat.h:705
void ff_rfps_calculate(AVFormatContext *ic)
Definition: utils.c:3033
uint32_t tag
Definition: movenc.c:1339
int avformat_network_init(void)
Do global initialization of network components.
Definition: utils.c:4210
char * av_strndup(const char *s, size_t len)
Duplicate a substring of the string s.
Definition: mem.c:279
int fps_probe_size
The number of frames used for determining the framerate in avformat_find_stream_info().
Definition: avformat.h:1517
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
uint8_t * data
Definition: avcodec.h:1383
static void copy(LZOContext *c, int cnt)
Copies bytes from input to output buffer with checking.
Definition: lzo.c:85
const AVCodecDescriptor * av_codec_get_codec_descriptor(const AVCodecContext *avctx)
ptrdiff_t size
Definition: opengl_enc.c:101
int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt, const char *url, void *logctx, unsigned int offset, unsigned int max_probe_size)
Probe a bytestream to determine the input format.
Definition: format.c:245
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:390
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:3006
struct AVPacketList * packet_buffer
This buffer is only needed when packets were already buffered but not decoded, for example to get the...
Definition: internal.h:76
static int64_t duration
Definition: ffplay.c:326
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition: avformat.h:1221
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1451
int raw_packet_buffer_remaining_size
Definition: internal.h:99
enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
Select a PCM codec based on the given parameters.
Definition: utils.c:2792
const OptionDef options[]
Definition: ffserver.c:3810
void av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:213
unsigned int * stream_index
Definition: avformat.h:1222
enum AVCodecID video_codec_id
Forced video codec_id.
Definition: avformat.h:1443
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition: avformat.h:790
#define av_log(a,...)
int64_t rfps_duration_sum
Definition: avformat.h:996
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:542
unsigned m
Definition: audioconvert.c:187
Duration estimated from bitrate (less accurate)
Definition: avformat.h:1272
unsigned int correct_ts_overflow
Correct single timestamp overflows.
Definition: avformat.h:1658
struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1304
static const AVCodec * find_decoder(AVFormatContext *s, AVStream *st, enum AVCodecID codec_id)
Definition: utils.c:153
int64_t start_time
Definition: avformat.h:1237
static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
Definition: utils.c:1176
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1479
static int determinable_frame_size(AVCodecContext *avctx)
Definition: utils.c:736
void av_format_inject_global_side_data(AVFormatContext *s)
This function will cause global side data to be injected in the next packet of each stream as well as...
Definition: utils.c:130
int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos, int64_t(*read_timestamp)(struct AVFormatContext *, int, int64_t *, int64_t))
Definition: utils.c:1930
int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
Read a transport packet from a media file.
Definition: utils.c:647
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:147
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags)
Find the "best" stream in the file.
Definition: utils.c:3581
av_cold int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
Definition: utils.c:2914
#define AVINDEX_KEYFRAME
Definition: avformat.h:803
#define AVPROBE_SCORE_STREAM_RETRY
Definition: avformat.h:468
AVProgram * av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
Find the programs which belong to a given stream.
Definition: utils.c:3564
int max_ts_probe
Maximum number of packets to read while waiting for the first timestamp.
Definition: avformat.h:1579
void ff_read_frame_flush(AVFormatContext *s)
Flush the frame reader.
Definition: utils.c:1627
int format_probesize
number of bytes to read maximally to identify format.
Definition: avformat.h:1688
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:102
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:3404
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1497
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:1822
int nb_decoded_frames
Number of internally decoded frames, used internally in libavformat, do not access its lifetime diffe...
Definition: avformat.h:1132
int64_t pos
Byte position of currently parsed frame in stream.
Definition: avcodec.h:4670
int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt)
Decode the video frame of size avpkt->size from avpkt->data into picture.
Definition: utils.c:2420
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1847
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given block if it is not large enough, otherwise do nothing.
Definition: mem.c:480
char * ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
Definition: utils.c:4044
void ff_reduce_index(AVFormatContext *s, int stream_index)
Ensure the index uses less memory than the maximum specified in AVFormatContext.max_index_size by dis...
Definition: utils.c:1676
int av_codec_get_tag2(const AVCodecTag *const *tags, enum AVCodecID id, unsigned int *tag)
Definition: utils.c:2847
struct AVCodecParser * parser
Definition: avcodec.h:4551
#define MAKE_ACCESSORS(str, name, type, field)
Definition: internal.h:89
int64_t pts_wrap_reference
reference dts for wrap detection
Definition: avformat.h:1240
An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows:
Definition: avcodec.h:1243
#define AVERROR(e)
Definition: error.h:43
int ffio_set_buf_size(AVIOContext *s, int buf_size)
Definition: aviobuf.c:843
#define SANE_CHUNK_SIZE
Definition: utils.c:179
#define AVFMT_FLAG_IGNDTS
Ignore DTS on frames that contain both DTS & PTS.
Definition: avformat.h:1400
unsigned int avpriv_toupper4(unsigned int x)
Definition: utils.c:3766
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:148
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:797
int(* query_codec)(enum AVCodecID id, int std_compliance)
Test if the given codec can be stored in this container.
Definition: avformat.h:590
#define PARSER_FLAG_COMPLETE_FRAMES
Definition: avcodec.h:4583
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:945
int avcodec_is_open(AVCodecContext *s)
Definition: utils.c:3870
AVRational av_div_q(AVRational b, AVRational c)
Divide one rational by another.
Definition: rational.c:88
int av_match_list(const char *name, const char *list, char separator)
Check if a name is in a list.
Definition: avstring.c:436
int64_t convergence_duration
Time difference in AVStream->time_base units from the pts of this packet to the point at which the ou...
Definition: avcodec.h:1477
int capabilities
Codec capabilities.
Definition: avcodec.h:3501
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
unsigned int nb_programs
Definition: avformat.h:1436
int last_IP_duration
Definition: avformat.h:1033
int av_read_play(AVFormatContext *s)
Start playing a network-based stream (e.g.
Definition: utils.c:3647
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:199
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:425
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1416
void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
Free memory allocated parsing special (non-text) metadata.
Definition: id3v2.c:1062
AVChapter ** chapters
Definition: avformat.h:1487
int rc_max_rate
maximum bitrate
Definition: avcodec.h:2614
simple assert() macros that are a bit more flexible than ISO C assert().
#define PARSER_FLAG_USE_CODEC_TS
Definition: avcodec.h:4587
int64_t av_gcd(int64_t a, int64_t b)
Return the greatest common divisor of a and b.
Definition: mathematics.c:55
enum AVPacketSideDataType type
Definition: avcodec.h:1385
int side_data_elems
Definition: avcodec.h:1445
int skip_samples
Number of samples to skip at the start of the frame decoded from the next packet. ...
Definition: avformat.h:1102
static int is_intra_only(AVCodecContext *enc)
Definition: utils.c:800
enum AVCodecID codec_id
Definition: mov_chan.c:433
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
GLsizei count
Definition: opengl_enc.c:109
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:937
#define PARSER_FLAG_ONCE
Definition: avcodec.h:4584
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1218
#define FFMAX(a, b)
Definition: common.h:90
struct AVCodecParserContext * av_stream_get_parser(const AVStream *st)
Definition: utils.c:125
AVInputFormat * av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
Guess the file format.
Definition: format.c:228
int min_distance
Minimum distance between this and the previous keyframe, used to avoid unneeded searching.
Definition: avformat.h:806
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
#define fail()
Definition: checkasm.h:57
const char av_format_ffversion[]
Definition: utils.c:55
AVCodec * audio_codec
Forced audio codec.
Definition: avformat.h:1734
#define AVFMT_FLAG_PRIV_OPT
Enable use of private options by delaying codec open (this could be made default once all code is con...
Definition: avformat.h:1416
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1439
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:2935
int seek_count
seek statistic This field is internal to libavformat and access from outside is not allowed...
Definition: avio.h:185
Only parse headers, do not repack.
Definition: avformat.h:787
char * format_whitelist
',' separated list of allowed demuxers.
Definition: avformat.h:1704
static int genpts
Definition: ffplay.c:328
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:873
static AVPacket flush_pkt
Definition: ffplay.c:355
int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
Test if the given container can store a codec.
Definition: utils.c:4193
int av_packet_merge_side_data(AVPacket *pkt)
Definition: avpacket.c:371
#define AVFMT_FLAG_NOBUFFER
Do not buffer frames when possible.
Definition: avformat.h:1403
int ff_add_index_entry(AVIndexEntry **index_entries, int *nb_index_entries, unsigned int *index_entries_allocated_size, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Internal version of av_add_index_entry.
Definition: utils.c:1689
static float distance(float x, float y, int band)
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
Definition: avcodec.h:582
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:463
struct AVStream::@152 * info
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4093
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:462
static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
Definition: utils.c:333
static AVPacketList * get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
Definition: utils.c:834
common internal API header
#define FF_MAX_EXTRADATA_SIZE
Maximum size in bytes of extradata.
Definition: internal.h:197
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1341
int64_t fps_first_dts
Those are used for average framerate estimation.
Definition: avformat.h:1013
int av_read_pause(AVFormatContext *s)
Pause a network-based stream (e.g.
Definition: utils.c:3656
int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
Definition: mathematics.c:139
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:160
int bit_rate
the average bitrate
Definition: avcodec.h:1577
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:119
char filename[1024]
input or output filename
Definition: avformat.h:1361
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:134
int update_initial_durations_done
Internal data to prevent doing update_initial_durations() twice.
Definition: avformat.h:1160
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:246
#define FFMIN(a, b)
Definition: common.h:92
enum AVCodecID audio_codec_id
Forced audio codec_id.
Definition: avformat.h:1449
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
Definition: utils.c:1790
Raw Video Codec.
static void compute_pkt_fields(AVFormatContext *s, AVStream *st, AVCodecParserContext *pc, AVPacket *pkt, int64_t next_dts, int64_t next_pts)
Definition: utils.c:990
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:149
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:611
int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos)
Parse a packet.
Definition: parser.c:131
#define LIBAVFORMAT_VERSION_MICRO
Definition: version.h:34
static const chunk_decoder decoder[8]
Definition: dfa.c:328
int max_streams
The maximum number of streams.
Definition: avformat.h:1840
int width
picture width / height.
Definition: avcodec.h:1691
#define RELATIVE_TS_BASE
Definition: utils.c:79
int64_t offset
byte offset from starting packet start
Definition: avcodec.h:4589
int av_find_default_stream_index(AVFormatContext *s)
Definition: utils.c:1589
#define FAIL(errmsg)
int64_t convergence_duration
Time difference in stream time base units from the pts of this packet to the point at which the outpu...
Definition: avcodec.h:4617
Duration estimated from a stream with a known duration.
Definition: avformat.h:1271
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
int32_t
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:221
uint8_t dts_ordered
Definition: avformat.h:1172
static int seek_frame_generic(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: utils.c:2094
int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t(*read_timestamp)(struct AVFormatContext *, int, int64_t *, int64_t))
Perform a binary search using read_timestamp().
Definition: utils.c:1968
static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts)
Definition: utils.c:843
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1573
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:68
void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st, AVCodecParserContext *pc, AVPacket *pkt)
Return the frame duration in seconds.
Definition: utils.c:750
static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
Definition: utils.c:581
int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt)
Decode the audio frame of size avpkt->size from avpkt->data into frame.
Definition: utils.c:2570
#define AV_RL32
Definition: intreadwrite.h:146
static AVPacket * add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt, AVPacketList **plast_pktl)
Definition: utils.c:364
int n
Definition: avisynth_c.h:547
AVDictionary * metadata
Definition: avformat.h:928
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1650
#define AVPROBE_SCORE_RETRY
Definition: avformat.h:467
int probe_score
format probing score.
Definition: avformat.h:1681
#define AVFMT_FLAG_CUSTOM_IO
The caller has supplied a custom AVIOContext, don't avio_close() it.
Definition: avformat.h:1404
int av_format_get_probe_score(const AVFormatContext *s)
Definition: utils.c:173
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:192
Opaque data information usually sparse.
Definition: avutil.h:197
int64_t skip_initial_bytes
Skip initial bytes when opening stream.
Definition: avformat.h:1651
int(* read_pause)(struct AVFormatContext *)
Pause playing - only meaningful if using a network-based format (RTSP).
Definition: avformat.h:752
const AVClass * priv_class
AVClass for the private context.
Definition: avformat.h:553
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc)
Definition: utils.c:1146
int buffer_size
Maximum buffer size.
Definition: avio.h:126
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:107
int64_t max_analyze_duration
Maximum duration (in AV_TIME_BASE units) of the data read from input in avformat_find_stream_info().
Definition: avformat.h:1787
void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
Update cur_dts of all streams based on the given timestamp and AVStream.
Definition: utils.c:1662
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:831
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:3047
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:3043
int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
Return in 'buf' the path with 'd' replaced by a number.
Definition: utils.c:3918
#define av_log2
Definition: intmath.h:100
int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
Read data and append it to the current content of the AVPacket.
Definition: utils.c:254
uint8_t pts_reorder_error_count[MAX_REORDER_DELAY+1]
Definition: avformat.h:1166
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:823
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
Stream structure.
Definition: avformat.h:854
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition: avformat.h:484
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1251
int avformat_queue_attached_pictures(AVFormatContext *s)
Definition: utils.c:382
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
Definition: utils.c:4223
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:2292
uint8_t dts_misordered
Definition: avformat.h:1173
#define FF_FDEBUG_TS
Definition: avformat.h:1541
static int width
Definition: utils.c:158
#define LIBAVFORMAT_VERSION_INT
Definition: version.h:36
sample_rate
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
int64_t pts_reorder_error[MAX_REORDER_DELAY+1]
Internal data to generate dts from pts.
Definition: avformat.h:1165
int frame_size
Definition: mxfenc.c:1819
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:50
AVS_Value src
Definition: avisynth_c.h:482
int64_t end_time
Definition: avformat.h:1238
enum AVMediaType codec_type
Definition: avcodec.h:1520
unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
Definition: utils.c:2770
int(* read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags)
Seek to a given timestamp relative to the frames in stream component stream_index.
Definition: avformat.h:732
static int64_t ts_to_samples(AVStream *st, int64_t ts)
Definition: utils.c:1313
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrup a blocking function associated with cb.
Definition: avio.c:607
int debug
Flags to enable debugging.
Definition: avformat.h:1540
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer...
Definition: options.c:164
enum AVCodecID codec_id
Definition: avcodec.h:1529
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:252
static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
Definition: utils.c:203
int av_opt_set_dict(void *obj, AVDictionary **options)
Set all the options from a given dictionary on an object.
Definition: opt.c:1477
char * av_strdup(const char *s)
Duplicate the string s.
Definition: mem.c:267
int sample_rate
samples per second
Definition: avcodec.h:2272
AVIOContext * pb
I/O context.
Definition: avformat.h:1327
unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
Definition: utils.c:2839
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:550
main external API structure.
Definition: avcodec.h:1512
AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
Definition: utils.c:3028
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:562
int io_repositioned
IO repositioned flag.
Definition: avformat.h:1718
int av_filename_number_test(const char *filename)
Check whether filename actually is a numbered sequence generator.
Definition: utils.c:261
AVRational sample_aspect_ratio
Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
Definition: frame.h:252
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1544
#define AVFMT_NOGENSEARCH
Format does not allow to fall back on generic search.
Definition: avformat.h:491
int(* read_packet)(struct AVFormatContext *, AVPacket *pkt)
Read one packet and put it in 'pkt'.
Definition: avformat.h:716
int pts_wrap_behavior
behavior on wrap detection
Definition: avformat.h:1241
void * buf
Definition: avisynth_c.h:553
double(* duration_error)[2][MAX_STD_TIMEBASES]
Definition: avformat.h:997
GLint GLenum type
Definition: opengl_enc.c:105
int extradata_size
Definition: avcodec.h:1628
#define llrint(x)
Definition: libm.h:112
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:69
int nb_index_entries
Definition: avformat.h:1059
enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
Definition: utils.c:2864
Describe the class of an AVClass context structure.
Definition: log.h:67
int ff_hex_to_data(uint8_t *data, const char *p)
Parse a string of hexadecimal strings.
Definition: utils.c:4065
static av_const int av_toupper(int c)
Locale-independent conversion of ASCII characters to uppercase.
Definition: avstring.h:221
int index
Definition: gxfenc.c:89
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:485
enum AVCodecID subtitle_codec
default subtitle codec
Definition: avformat.h:537
#define SPACE_CHARS
Definition: internal.h:225
rational number numerator/denominator
Definition: rational.h:43
int64_t last_dts
Definition: avformat.h:993
AVRational display_aspect_ratio
display aspect ratio (0 if unknown)
Definition: avformat.h:1192
Recommmends skipping the specified number of samples.
Definition: avcodec.h:1314
uint64_t ff_ntp_time(void)
Get the current time since NTP epoch in microseconds.
Definition: utils.c:3913
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition: avformat.h:2297
const AVClass * av_class
A class for logging and AVOptions.
Definition: avformat.h:1290
AVMediaType
Definition: avutil.h:191
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:922
int ff_generate_avci_extradata(AVStream *st)
Generate standard extradata for AVC-Intra based on width/height and field order.
Definition: utils.c:4433
int short_seek_threshold
Threshold to favor readahead over seek.
Definition: avio.h:204
int64_t fps_last_dts
Definition: avformat.h:1015
#define RAW_PACKET_BUFFER_SIZE
Remaining size available for raw_packet_buffer, in bytes.
Definition: internal.h:98
static int seek_frame_internal(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: utils.c:2158
int64_t ff_iso8601_to_unix_time(const char *datestr)
Convert a date string in ISO8601 format to Unix timestamp.
Definition: utils.c:4181
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:1361
#define snprintf
Definition: snprintf.h:34
int found_decoder
0 -> decoder has not been searched for yet.
Definition: avformat.h:1006
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:3693
int inject_global_side_data
Definition: internal.h:113
This structure contains the data a format has to probe a file.
Definition: avformat.h:460
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
Return audio frame duration.
Definition: utils.c:3422
misc parsing utilities
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1480
static int has_duration(AVFormatContext *ic)
Return TRUE if the stream has accurate duration in any stream.
Definition: utils.c:2295
int avio_pause(AVIOContext *h, int pause)
Pause and resume playing - only meaningful if using a network streaming protocol (e.g.
Definition: aviobuf.c:983
Round toward -infinity.
Definition: mathematics.h:73
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
Definition: utils.c:2225
static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt, AVDictionary **options)
Definition: utils.c:2685
This struct describes the properties of a single codec described by an AVCodecID. ...
Definition: avcodec.h:566
int ff_copy_whitelists(AVFormatContext *dst, AVFormatContext *src)
Copies the whilelists from one context to the other.
Definition: utils.c:140
int seek2any
Force seeking to any (also non key) frames.
Definition: avformat.h:1665
full parsing and repack of the first frame only, only implemented for H.264 currently ...
Definition: avformat.h:789
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition: avio.c:425
AVDictionary * metadata
Definition: avformat.h:1224
int64_t codec_info_duration
Definition: avformat.h:998
static int64_t pts
Global timestamp for the audio frames.
int fps_first_dts_idx
Definition: avformat.h:1014
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:133
static int flags
Definition: cpu.c:47
int64_t start_time
Position of the first frame of the component, in AV_TIME_BASE fractional seconds. ...
Definition: avformat.h:1370
Duration accurately estimated from PTSes.
Definition: avformat.h:1270
#define LICENSE_PREFIX
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Seek to the keyframe at timestamp.
Definition: utils.c:2202
unsigned int tag
Definition: internal.h:44
struct AVPacketList * parse_queue
Packets split by the parser get queued here.
Definition: internal.h:93
int64_t start
Definition: avformat.h:1251
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:913
static int is_relative(int64_t ts)
Definition: utils.c:81
static int tb_unreliable(AVCodecContext *c)
Definition: utils.c:2923
Main libavformat public API header.
AVPacketSideData * side_data
Additional packet data that can be provided by the container.
Definition: avcodec.h:1444
int(* split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
Definition: avcodec.h:4738
void av_opt_free(void *obj)
Free all allocated objects in obj.
Definition: opt.c:1432
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:82
common internal api header.
struct AVPacketList * next
Definition: avformat.h:1876
if(ret< 0)
Definition: vf_mcdeint.c:280
void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
Definition: utils.c:3885
int pts_wrap_behavior
Options for behavior, when a wrap is detected.
Definition: avformat.h:1155
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:477
int(* read_play)(struct AVFormatContext *)
Start/resume playing - only meaningful if using a network-based format (RTSP).
Definition: avformat.h:746
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:145
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3098
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:906
int64_t av_add_stable(AVRational ts_tb, int64_t ts, AVRational inc_tb, int64_t inc)
Add a value to a timestamp.
Definition: mathematics.c:196
AVCodec * video_codec
Forced video codec.
Definition: avformat.h:1726
static double c[64]
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:917
int(* av_format_control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size)
Callback used by devices to communicate with application.
Definition: avformat.h:1259
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:92
void av_codec_set_codec_descriptor(AVCodecContext *avctx, const AVCodecDescriptor *desc)
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:1020
Bi-dir predicted.
Definition: avutil.h:268
void ff_free_stream(AVFormatContext *s, AVStream *st)
Definition: utils.c:3665
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
add frame for rfps calculation.
Definition: utils.c:2975
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1250
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:208
int av_grow_packet(AVPacket *pkt, int grow_by)
Increase packet size, correctly zeroing padding.
Definition: avpacket.c:112
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:49
void ff_id3v2_read(AVFormatContext *s, const char *magic, ID3v2ExtraMeta **extra_meta, unsigned int max_search_size)
Read an ID3v2 tag, including supported extra metadata and chapters.
Definition: id3v2.c:1056
int den
denominator
Definition: rational.h:45
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
Definition: avcodec.h:1480
unsigned bps
Definition: movenc.c:1340
struct AVInputFormat * iformat
The input container format.
Definition: avformat.h:1297
void avformat_close_input(AVFormatContext **ps)
Close an opened input AVFormatContext.
Definition: utils.c:3728
#define FFMPEG_CONFIGURATION
Definition: config.h:4
#define AV_PTS_WRAP_IGNORE
Options for behavior on timestamp wrap detection.
Definition: avformat.h:843
int64_t codec_info_duration_fields
Definition: avformat.h:999
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:636
void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
Definition: utils.c:3087
Flag to pass INT64_MIN/MAX through instead of rescaling, this avoids special cases for AV_NOPTS_VALUE...
Definition: mathematics.h:76
unsigned int index_entries_allocated_size
Definition: avformat.h:1060
#define AVERROR_DECODER_NOT_FOUND
Decoder not found.
Definition: error.h:52
int skip_to_keyframe
Indicates that everything up to the next keyframe should be discarded.
Definition: avformat.h:1097
int64_t frame_offset
Definition: avcodec.h:4552
static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
Parse a packet, add all split parts to parse_queue.
Definition: utils.c:1192
static int read_from_packet_buffer(AVPacketList **pkt_buffer, AVPacketList **pkt_buffer_end, AVPacket *pkt)
Definition: utils.c:1298
static av_always_inline int diff(const uint32_t a, const uint32_t b)
struct AVPacketList * packet_buffer_end
Definition: internal.h:77
#define av_free(p)
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition: avformat.h:492
char * value
Definition: dict.h:88
int ff_alloc_extradata(AVCodecContext *avctx, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:2938
AVCodec * subtitle_codec
Forced subtitle codec.
Definition: avformat.h:1742
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:83
int(* AVOpenCallback)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Definition: avformat.h:1262
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:54
#define FFMPEG_VERSION
Definition: ffversion.h:3
int len
int channels
number of audio channels
Definition: avcodec.h:2273
enum AVCodecID audio_codec
default audio codec
Definition: avformat.h:535
char * codec_whitelist
',' separated list of allowed decoders.
Definition: avformat.h:1696
struct AVCodecParserContext * parser
Definition: avformat.h:1047
void * priv_data
Format private data.
Definition: avformat.h:1313
int codec_info_nb_frames
Number of frames that have been demuxed during av_find_stream_info()
Definition: avformat.h:1043
const struct PixelFormatTag * avpriv_get_raw_pix_fmt_tags(void)
Definition: raw.c:228
#define AVERROR_STREAM_NOT_FOUND
Stream not found.
Definition: error.h:65
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:405
static void flush_packet_queue(AVFormatContext *s)
Definition: utils.c:1575
#define AV_DISPOSITION_COMMENT
Definition: avformat.h:812
static int height
Definition: utils.c:158
#define av_uninit(x)
Definition: attributes.h:141
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1432
static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags)
Definition: utils.c:2074
int bit_rate
Total stream bitrate in bit/s, 0 if not available.
Definition: avformat.h:1387
int repeat_pict
This field is used for proper frame duration computation in lavf.
Definition: avcodec.h:4567
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1380
int avformat_flush(AVFormatContext *s)
Discard all internally buffered data.
Definition: utils.c:2282
int64_t last_IP_pts
Definition: avformat.h:1032
void ff_tls_deinit(void)
Definition: network.c:43
int(* read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
Definition: avformat.h:760
#define av_freep(p)
enum AVFieldOrder field_order
Field order.
Definition: avcodec.h:2269
void INT64 start
Definition: avisynth_c.h:553
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:640
uint8_t * av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:329
unbuffered private I/O API
static void compute_chapters_end(AVFormatContext *s)
Definition: utils.c:2875
#define FFSWAP(type, a, b)
Definition: common.h:95
static void update_initial_timestamps(AVFormatContext *s, int stream_index, int64_t dts, int64_t pts, AVPacket *pkt)
Definition: utils.c:885
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:303
int fps_last_dts_idx
Definition: avformat.h:1016
int stream_index
Definition: avcodec.h:1435
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:896
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:919
int ff_add_param_change(AVPacket *pkt, int32_t channels, uint64_t channel_layout, int32_t sample_rate, int32_t width, int32_t height)
Add side data to a packet for changing parameters to the given values.
Definition: utils.c:4233
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1073
int ffio_limit(AVIOContext *s, int size)
Definition: utils.c:181
int request_probe
stream probing state -1 -> probing finished 0 -> no probing requested rest -> perform probing with re...
Definition: avformat.h:1092
#define MAX_PROBE_PACKETS
Definition: internal.h:34
int use_wallclock_as_timestamps
forces the use of wallclock timestamps as pts/dts of packets This has undefined results in the presen...
Definition: avformat.h:1629
This structure stores compressed data.
Definition: avcodec.h:1410
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:963
int key_frame
Set by parser to 1 for key frames and 0 for non-key frames.
Definition: avcodec.h:4598
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:369
#define AVFMT_FLAG_NOFILLIN
Do not infer any values from other values, just return what is stored in the container.
Definition: avformat.h:1401
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:252
#define MAX_STD_TIMEBASES
Stream information used internally by av_find_stream_info()
Definition: avformat.h:991
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1426
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition: avformat.h:946
int64_t av_stream_get_end_pts(const AVStream *st)
Returns the pts of the last muxed packet + its duration.
Definition: utils.c:117
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:244
#define av_unused
Definition: attributes.h:118
AVProgram ** programs
Definition: avformat.h:1437
#define AVFMT_NEEDNUMBER
Needs 'd' in filename.
Definition: avformat.h:478
discard nothing
Definition: avcodec.h:683
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
struct AVPacketList * raw_packet_buffer_end
Definition: internal.h:89
int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod)
Compare 2 integers modulo mod.
Definition: mathematics.c:165
const char * name
Definition: opengl_enc.c:103