2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
26 #include "libavutil/avassert.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/internal.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/parseutils.h"
33 #include "libavutil/pixfmt.h"
34 #include "libavutil/thread.h"
35 #include "libavutil/time.h"
36 #include "libavutil/timestamp.h"
38 #include "libavcodec/bytestream.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/packet_internal.h"
41 #include "libavcodec/raw.h"
44 #include "avio_internal.h"
52 #include "libavutil/ffversion.h"
53 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
55 static AVMutex avformat_mutex = AV_MUTEX_INITIALIZER;
59 * various utility functions for use within FFmpeg
62 unsigned avformat_version(void)
64 av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
65 return LIBAVFORMAT_VERSION_INT;
68 const char *avformat_configuration(void)
70 return FFMPEG_CONFIGURATION;
73 const char *avformat_license(void)
75 #define LICENSE_PREFIX "libavformat license: "
76 return &LICENSE_PREFIX FFMPEG_LICENSE[sizeof(LICENSE_PREFIX) - 1];
79 int ff_lock_avformat(void)
81 return ff_mutex_lock(&avformat_mutex) ? -1 : 0;
84 int ff_unlock_avformat(void)
86 return ff_mutex_unlock(&avformat_mutex) ? -1 : 0;
89 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
91 static int is_relative(int64_t ts) {
92 return ts > (RELATIVE_TS_BASE - (1LL<<48));
96 * Wrap a given time stamp, if there is an indication for an overflow
99 * @param timestamp the time stamp to wrap
100 * @return resulting time stamp
102 static int64_t wrap_timestamp(const AVStream *st, int64_t timestamp)
104 if (st->internal->pts_wrap_behavior != AV_PTS_WRAP_IGNORE && st->pts_wrap_bits < 64 &&
105 st->internal->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
106 if (st->internal->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
107 timestamp < st->internal->pts_wrap_reference)
108 return timestamp + (1ULL << st->pts_wrap_bits);
109 else if (st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
110 timestamp >= st->internal->pts_wrap_reference)
111 return timestamp - (1ULL << st->pts_wrap_bits);
116 #if FF_API_FORMAT_GET_SET
117 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
118 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
119 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
120 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
121 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
122 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
123 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
124 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
125 #if FF_API_OLD_OPEN_CALLBACKS
126 FF_DISABLE_DEPRECATION_WARNINGS
127 MAKE_ACCESSORS(AVFormatContext, format, AVOpenCallback, open_cb)
128 FF_ENABLE_DEPRECATION_WARNINGS
132 int64_t av_stream_get_end_pts(const AVStream *st)
134 if (st->internal->priv_pts) {
135 return st->internal->priv_pts->val;
137 return AV_NOPTS_VALUE;
140 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
145 void av_format_inject_global_side_data(AVFormatContext *s)
148 s->internal->inject_global_side_data = 1;
149 for (i = 0; i < s->nb_streams; i++) {
150 AVStream *st = s->streams[i];
151 st->internal->inject_global_side_data = 1;
155 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
157 av_assert0(!dst->codec_whitelist &&
158 !dst->format_whitelist &&
159 !dst->protocol_whitelist &&
160 !dst->protocol_blacklist);
161 dst-> codec_whitelist = av_strdup(src->codec_whitelist);
162 dst->format_whitelist = av_strdup(src->format_whitelist);
163 dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
164 dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
165 if ( (src-> codec_whitelist && !dst-> codec_whitelist)
166 || (src-> format_whitelist && !dst-> format_whitelist)
167 || (src->protocol_whitelist && !dst->protocol_whitelist)
168 || (src->protocol_blacklist && !dst->protocol_blacklist)) {
169 av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
170 return AVERROR(ENOMEM);
175 static const AVCodec *find_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
177 #if FF_API_LAVF_AVCTX
178 FF_DISABLE_DEPRECATION_WARNINGS
179 if (st->codec->codec)
180 return st->codec->codec;
181 FF_ENABLE_DEPRECATION_WARNINGS
184 switch (st->codecpar->codec_type) {
185 case AVMEDIA_TYPE_VIDEO:
186 if (s->video_codec) return s->video_codec;
188 case AVMEDIA_TYPE_AUDIO:
189 if (s->audio_codec) return s->audio_codec;
191 case AVMEDIA_TYPE_SUBTITLE:
192 if (s->subtitle_codec) return s->subtitle_codec;
196 return avcodec_find_decoder(codec_id);
199 static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
201 const AVCodec *codec;
203 #if CONFIG_H264_DECODER
204 /* Other parts of the code assume this decoder to be used for h264,
205 * so force it if possible. */
206 if (codec_id == AV_CODEC_ID_H264)
207 return avcodec_find_decoder_by_name("h264");
210 codec = find_decoder(s, st, codec_id);
214 if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
215 const AVCodec *probe_codec = NULL;
217 while ((probe_codec = av_codec_iterate(&iter))) {
218 if (probe_codec->id == codec->id &&
219 av_codec_is_decoder(probe_codec) &&
220 !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
229 #if FF_API_FORMAT_GET_SET
230 int av_format_get_probe_score(const AVFormatContext *s)
232 return s->probe_score;
236 /* an arbitrarily chosen "sane" max packet size -- 50M */
237 #define SANE_CHUNK_SIZE (50000000)
239 int ffio_limit(AVIOContext *s, int size)
241 if (s->maxsize>= 0) {
242 int64_t pos = avio_tell(s);
243 int64_t remaining= s->maxsize - pos;
244 if (remaining < size) {
245 int64_t newsize = avio_size(s);
246 if (!s->maxsize || s->maxsize<newsize)
247 s->maxsize = newsize - !newsize;
248 if (pos > s->maxsize && s->maxsize >= 0)
249 s->maxsize = AVERROR(EIO);
251 remaining = s->maxsize - pos;
254 if (s->maxsize >= 0 && remaining < size && size > 1) {
255 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG,
256 "Truncating packet of size %d to %"PRId64"\n",
257 size, remaining + !remaining);
258 size = remaining + !remaining;
264 /* Read the data in sane-sized chunks and append to pkt.
265 * Return the number of bytes read or an error. */
266 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
268 int orig_size = pkt->size;
272 int prev_size = pkt->size;
275 /* When the caller requests a lot of data, limit it to the amount
276 * left in file or SANE_CHUNK_SIZE when it is not known. */
278 if (read_size > SANE_CHUNK_SIZE/10) {
279 read_size = ffio_limit(s, read_size);
280 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
282 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
285 ret = av_grow_packet(pkt, read_size);
289 ret = avio_read(s, pkt->data + prev_size, read_size);
290 if (ret != read_size) {
291 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
298 pkt->flags |= AV_PKT_FLAG_CORRUPT;
301 av_packet_unref(pkt);
302 return pkt->size > orig_size ? pkt->size - orig_size : ret;
305 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
307 #if FF_API_INIT_PACKET
308 FF_DISABLE_DEPRECATION_WARNINGS
312 FF_ENABLE_DEPRECATION_WARNINGS
314 av_packet_unref(pkt);
316 pkt->pos = avio_tell(s);
318 return append_packet_chunked(s, pkt, size);
321 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
324 return av_get_packet(s, pkt, size);
325 return append_packet_chunked(s, pkt, size);
328 int av_filename_number_test(const char *filename)
332 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
335 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
338 static const struct {
341 enum AVMediaType type;
343 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
344 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
345 { "aptx", AV_CODEC_ID_APTX, AVMEDIA_TYPE_AUDIO },
346 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
347 { "dvbsub", AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
348 { "dvbtxt", AV_CODEC_ID_DVB_TELETEXT,AVMEDIA_TYPE_SUBTITLE },
349 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
350 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
351 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
352 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
353 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
354 { "mjpeg_2000",AV_CODEC_ID_JPEG2000, AVMEDIA_TYPE_VIDEO },
355 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
356 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
357 { "truehd", AV_CODEC_ID_TRUEHD, AVMEDIA_TYPE_AUDIO },
361 const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
365 av_log(s, AV_LOG_DEBUG,
366 "Probe with size=%d, packets=%d detected %s with score=%d\n",
367 pd->buf_size, s->max_probe_packets - st->probe_packets,
369 for (i = 0; fmt_id_type[i].name; i++) {
370 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
371 if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
372 st->codecpar->sample_rate)
374 if (st->internal->request_probe > score &&
375 st->codecpar->codec_id != fmt_id_type[i].id)
377 st->codecpar->codec_id = fmt_id_type[i].id;
378 st->codecpar->codec_type = fmt_id_type[i].type;
379 st->internal->need_context_update = 1;
380 #if FF_API_LAVF_AVCTX
381 FF_DISABLE_DEPRECATION_WARNINGS
382 st->codec->codec_type = st->codecpar->codec_type;
383 st->codec->codec_id = st->codecpar->codec_id;
384 FF_ENABLE_DEPRECATION_WARNINGS
393 /************************************************************/
394 /* input media file */
396 #if FF_API_DEMUXER_OPEN
397 int av_demuxer_open(AVFormatContext *ic) {
400 if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
401 av_log(ic, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", ic->format_whitelist);
402 return AVERROR(EINVAL);
405 if (ic->iformat->read_header) {
406 err = ic->iformat->read_header(ic);
411 if (ic->pb && !ic->internal->data_offset)
412 ic->internal->data_offset = avio_tell(ic->pb);
417 /* Open input file and probe the format if necessary. */
418 static int init_input(AVFormatContext *s, const char *filename,
419 AVDictionary **options)
422 AVProbeData pd = { filename, NULL, 0 };
423 int score = AVPROBE_SCORE_RETRY;
426 s->flags |= AVFMT_FLAG_CUSTOM_IO;
428 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
429 s, 0, s->format_probesize);
430 else if (s->iformat->flags & AVFMT_NOFILE)
431 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
432 "will be ignored with AVFMT_NOFILE format.\n");
436 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
437 (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
440 if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
445 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
446 s, 0, s->format_probesize);
449 int avformat_queue_attached_pictures(AVFormatContext *s)
452 for (i = 0; i < s->nb_streams; i++)
453 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
454 s->streams[i]->discard < AVDISCARD_ALL) {
455 if (s->streams[i]->attached_pic.size <= 0) {
456 av_log(s, AV_LOG_WARNING,
457 "Attached picture on stream %d has invalid size, "
462 ret = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
463 &s->internal->raw_packet_buffer_end,
464 &s->streams[i]->attached_pic,
472 int ff_add_attached_pic(AVFormatContext *s, AVStream *st0, AVIOContext *pb,
473 AVBufferRef **buf, int size)
479 if (!st && !(st = avformat_new_stream(s, NULL)))
480 return AVERROR(ENOMEM);
481 pkt = &st->attached_pic;
484 av_packet_unref(pkt);
486 pkt->data = (*buf)->data;
487 pkt->size = (*buf)->size - AV_INPUT_BUFFER_PADDING_SIZE;
490 ret = av_get_packet(pb, pkt, size);
494 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
495 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
497 pkt->stream_index = st->index;
498 pkt->flags |= AV_PKT_FLAG_KEY;
503 ff_free_stream(s, st);
507 static int update_stream_avctx(AVFormatContext *s)
510 for (i = 0; i < s->nb_streams; i++) {
511 AVStream *st = s->streams[i];
513 if (!st->internal->need_context_update)
516 /* close parser, because it depends on the codec */
517 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
518 av_parser_close(st->parser);
522 /* update internal codec context, for the parser */
523 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
527 #if FF_API_LAVF_AVCTX
528 FF_DISABLE_DEPRECATION_WARNINGS
529 /* update deprecated public codec context */
530 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
533 FF_ENABLE_DEPRECATION_WARNINGS
536 st->internal->need_context_update = 0;
542 int avformat_open_input(AVFormatContext **ps, const char *filename,
543 const AVInputFormat *fmt, AVDictionary **options)
545 AVFormatContext *s = *ps;
547 AVDictionary *tmp = NULL;
548 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
550 if (!s && !(s = avformat_alloc_context()))
551 return AVERROR(ENOMEM);
553 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
554 return AVERROR(EINVAL);
560 av_dict_copy(&tmp, *options, 0);
562 if (s->pb) // must be before any goto fail
563 s->flags |= AVFMT_FLAG_CUSTOM_IO;
565 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
568 if (!(s->url = av_strdup(filename ? filename : ""))) {
569 ret = AVERROR(ENOMEM);
573 #if FF_API_FORMAT_FILENAME
574 FF_DISABLE_DEPRECATION_WARNINGS
575 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
576 FF_ENABLE_DEPRECATION_WARNINGS
578 if ((ret = init_input(s, filename, &tmp)) < 0)
580 s->probe_score = ret;
582 if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
583 s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
584 if (!s->protocol_whitelist) {
585 ret = AVERROR(ENOMEM);
590 if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
591 s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
592 if (!s->protocol_blacklist) {
593 ret = AVERROR(ENOMEM);
598 if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
599 av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
600 ret = AVERROR(EINVAL);
604 avio_skip(s->pb, s->skip_initial_bytes);
606 /* Check filename in case an image number is expected. */
607 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
608 if (!av_filename_number_test(filename)) {
609 ret = AVERROR(EINVAL);
614 s->duration = s->start_time = AV_NOPTS_VALUE;
616 /* Allocate private data. */
617 if (s->iformat->priv_data_size > 0) {
618 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
619 ret = AVERROR(ENOMEM);
622 if (s->iformat->priv_class) {
623 *(const AVClass **) s->priv_data = s->iformat->priv_class;
624 av_opt_set_defaults(s->priv_data);
625 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
630 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
632 ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
634 #if FF_API_DEMUXER_OPEN
635 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
637 if (s->iformat->read_header)
639 if ((ret = s->iformat->read_header(s)) < 0)
643 s->metadata = s->internal->id3v2_meta;
644 s->internal->id3v2_meta = NULL;
645 } else if (s->internal->id3v2_meta) {
646 av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
647 av_dict_free(&s->internal->id3v2_meta);
650 if (id3v2_extra_meta) {
651 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
652 !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
653 if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
655 if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
657 if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
660 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
662 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
664 if ((ret = avformat_queue_attached_pictures(s)) < 0)
667 #if FF_API_DEMUXER_OPEN
668 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
670 if (s->pb && !s->internal->data_offset)
672 s->internal->data_offset = avio_tell(s->pb);
674 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
676 update_stream_avctx(s);
678 for (i = 0; i < s->nb_streams; i++)
679 s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
682 av_dict_free(options);
689 if (s->iformat->read_close)
690 s->iformat->read_close(s);
692 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
694 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
696 avformat_free_context(s);
701 /*******************************************************/
703 static void force_codec_ids(AVFormatContext *s, AVStream *st)
705 switch (st->codecpar->codec_type) {
706 case AVMEDIA_TYPE_VIDEO:
707 if (s->video_codec_id)
708 st->codecpar->codec_id = s->video_codec_id;
710 case AVMEDIA_TYPE_AUDIO:
711 if (s->audio_codec_id)
712 st->codecpar->codec_id = s->audio_codec_id;
714 case AVMEDIA_TYPE_SUBTITLE:
715 if (s->subtitle_codec_id)
716 st->codecpar->codec_id = s->subtitle_codec_id;
718 case AVMEDIA_TYPE_DATA:
719 if (s->data_codec_id)
720 st->codecpar->codec_id = s->data_codec_id;
725 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
727 if (st->internal->request_probe>0) {
728 AVProbeData *pd = &st->internal->probe_data;
730 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
734 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
736 av_log(s, AV_LOG_WARNING,
737 "Failed to reallocate probe buffer for stream %d\n",
742 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
743 pd->buf_size += pkt->size;
744 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
747 st->probe_packets = 0;
749 av_log(s, AV_LOG_WARNING,
750 "nothing to probe for stream %d\n", st->index);
754 end= s->internal->raw_packet_buffer_remaining_size <= 0
755 || st->probe_packets<= 0;
757 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
758 int score = set_codec_from_probe_data(s, st, pd);
759 if ( (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
763 st->internal->request_probe = -1;
764 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
765 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
767 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
769 force_codec_ids(s, st);
775 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
777 int64_t ref = pkt->dts;
778 int i, pts_wrap_behavior;
779 int64_t pts_wrap_reference;
780 AVProgram *first_program;
782 if (ref == AV_NOPTS_VALUE)
784 if (st->internal->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
786 ref &= (1LL << st->pts_wrap_bits)-1;
788 // reference time stamp should be 60 s before first time stamp
789 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
790 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
791 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
792 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
793 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
795 first_program = av_find_program_from_stream(s, NULL, stream_index);
797 if (!first_program) {
798 int default_stream_index = av_find_default_stream_index(s);
799 if (s->streams[default_stream_index]->internal->pts_wrap_reference == AV_NOPTS_VALUE) {
800 for (i = 0; i < s->nb_streams; i++) {
801 if (av_find_program_from_stream(s, NULL, i))
803 s->streams[i]->internal->pts_wrap_reference = pts_wrap_reference;
804 s->streams[i]->internal->pts_wrap_behavior = pts_wrap_behavior;
808 st->internal->pts_wrap_reference = s->streams[default_stream_index]->internal->pts_wrap_reference;
809 st->internal->pts_wrap_behavior = s->streams[default_stream_index]->internal->pts_wrap_behavior;
813 AVProgram *program = first_program;
815 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
816 pts_wrap_reference = program->pts_wrap_reference;
817 pts_wrap_behavior = program->pts_wrap_behavior;
820 program = av_find_program_from_stream(s, program, stream_index);
823 // update every program with differing pts_wrap_reference
824 program = first_program;
826 if (program->pts_wrap_reference != pts_wrap_reference) {
827 for (i = 0; i<program->nb_stream_indexes; i++) {
828 s->streams[program->stream_index[i]]->internal->pts_wrap_reference = pts_wrap_reference;
829 s->streams[program->stream_index[i]]->internal->pts_wrap_behavior = pts_wrap_behavior;
832 program->pts_wrap_reference = pts_wrap_reference;
833 program->pts_wrap_behavior = pts_wrap_behavior;
835 program = av_find_program_from_stream(s, program, stream_index);
841 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
846 #if FF_API_INIT_PACKET
847 FF_DISABLE_DEPRECATION_WARNINGS
851 FF_ENABLE_DEPRECATION_WARNINGS
853 av_packet_unref(pkt);
857 PacketList *pktl = s->internal->raw_packet_buffer;
858 const AVPacket *pkt1;
861 st = s->streams[pktl->pkt.stream_index];
862 if (s->internal->raw_packet_buffer_remaining_size <= 0)
863 if ((err = probe_codec(s, st, NULL)) < 0)
865 if (st->internal->request_probe <= 0) {
866 avpriv_packet_list_get(&s->internal->raw_packet_buffer,
867 &s->internal->raw_packet_buffer_end, pkt);
868 s->internal->raw_packet_buffer_remaining_size += pkt->size;
873 err = s->iformat->read_packet(s, pkt);
875 av_packet_unref(pkt);
877 /* Some demuxers return FFERROR_REDO when they consume
878 data and discard it (ignored streams, junk, extradata).
879 We must re-call the demuxer to get the real packet. */
880 if (err == FFERROR_REDO)
882 if (!pktl || err == AVERROR(EAGAIN))
884 for (i = 0; i < s->nb_streams; i++) {
886 if (st->probe_packets || st->internal->request_probe > 0)
887 if ((err = probe_codec(s, st, NULL)) < 0)
889 av_assert0(st->internal->request_probe <= 0);
894 err = av_packet_make_refcounted(pkt);
896 av_packet_unref(pkt);
900 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
901 av_log(s, AV_LOG_WARNING,
902 "Packet corrupt (stream = %d, dts = %s)",
903 pkt->stream_index, av_ts2str(pkt->dts));
904 if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
905 av_log(s, AV_LOG_WARNING, ", dropping it.\n");
906 av_packet_unref(pkt);
909 av_log(s, AV_LOG_WARNING, ".\n");
912 av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
913 "Invalid stream index.\n");
915 st = s->streams[pkt->stream_index];
917 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
918 // correct first time stamps to negative values
919 if (!is_relative(st->first_dts))
920 st->first_dts = wrap_timestamp(st, st->first_dts);
921 if (!is_relative(st->start_time))
922 st->start_time = wrap_timestamp(st, st->start_time);
923 if (!is_relative(st->cur_dts))
924 st->cur_dts = wrap_timestamp(st, st->cur_dts);
927 pkt->dts = wrap_timestamp(st, pkt->dts);
928 pkt->pts = wrap_timestamp(st, pkt->pts);
930 force_codec_ids(s, st);
932 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
933 if (s->use_wallclock_as_timestamps)
934 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
936 if (!pktl && st->internal->request_probe <= 0)
939 err = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
940 &s->internal->raw_packet_buffer_end,
943 av_packet_unref(pkt);
946 pkt1 = &s->internal->raw_packet_buffer_end->pkt;
947 s->internal->raw_packet_buffer_remaining_size -= pkt1->size;
949 if ((err = probe_codec(s, st, pkt1)) < 0)
955 /**********************************************************/
957 static int determinable_frame_size(AVCodecContext *avctx)
959 switch(avctx->codec_id) {
960 case AV_CODEC_ID_MP1:
961 case AV_CODEC_ID_MP2:
962 case AV_CODEC_ID_MP3:
963 case AV_CODEC_ID_CODEC2:
971 * Return the frame duration in seconds. Return 0 if not available.
973 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
974 AVCodecParserContext *pc, AVPacket *pkt)
976 AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
977 av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
978 int frame_size, sample_rate;
980 #if FF_API_LAVF_AVCTX
981 FF_DISABLE_DEPRECATION_WARNINGS
982 if ((!codec_framerate.den || !codec_framerate.num) && st->codec->time_base.den && st->codec->time_base.num)
983 codec_framerate = av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
984 FF_ENABLE_DEPRECATION_WARNINGS
989 switch (st->codecpar->codec_type) {
990 case AVMEDIA_TYPE_VIDEO:
991 if (st->r_frame_rate.num && !pc && s->iformat) {
992 *pnum = st->r_frame_rate.den;
993 *pden = st->r_frame_rate.num;
994 } else if (st->time_base.num * 1000LL > st->time_base.den) {
995 *pnum = st->time_base.num;
996 *pden = st->time_base.den;
997 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
998 av_assert0(st->internal->avctx->ticks_per_frame);
999 av_reduce(pnum, pden,
1000 codec_framerate.den,
1001 codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
1004 if (pc && pc->repeat_pict) {
1005 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
1006 av_reduce(pnum, pden,
1007 (*pnum) * (1LL + pc->repeat_pict),
1011 /* If this codec can be interlaced or progressive then we need
1012 * a parser to compute duration of a packet. Thus if we have
1013 * no parser in such case leave duration undefined. */
1014 if (st->internal->avctx->ticks_per_frame > 1 && !pc)
1018 case AVMEDIA_TYPE_AUDIO:
1019 if (st->internal->avctx_inited) {
1020 frame_size = av_get_audio_frame_duration(st->internal->avctx, pkt->size);
1021 sample_rate = st->internal->avctx->sample_rate;
1023 frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
1024 sample_rate = st->codecpar->sample_rate;
1026 if (frame_size <= 0 || sample_rate <= 0)
1029 *pden = sample_rate;
1036 int ff_is_intra_only(enum AVCodecID id)
1038 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
1041 if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
1042 !(d->props & AV_CODEC_PROP_INTRA_ONLY))
1047 static int has_decode_delay_been_guessed(AVStream *st)
1049 if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
1050 if (!st->internal->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
1052 #if CONFIG_H264_DECODER
1053 if (st->internal->avctx->has_b_frames &&
1054 avpriv_h264_has_num_reorder_frames(st->internal->avctx) == st->internal->avctx->has_b_frames)
1057 if (st->internal->avctx->has_b_frames<3)
1058 return st->internal->nb_decoded_frames >= 7;
1059 else if (st->internal->avctx->has_b_frames<4)
1060 return st->internal->nb_decoded_frames >= 18;
1062 return st->internal->nb_decoded_frames >= 20;
1065 static PacketList *get_next_pkt(AVFormatContext *s, AVStream *st, PacketList *pktl)
1069 if (pktl == s->internal->packet_buffer_end)
1070 return s->internal->parse_queue;
1074 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
1075 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1076 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1079 int delay = st->internal->avctx->has_b_frames;
1082 if (dts == AV_NOPTS_VALUE) {
1083 int64_t best_score = INT64_MAX;
1084 for (i = 0; i<delay; i++) {
1085 if (st->internal->pts_reorder_error_count[i]) {
1086 int64_t score = st->internal->pts_reorder_error[i] / st->internal->pts_reorder_error_count[i];
1087 if (score < best_score) {
1089 dts = pts_buffer[i];
1094 for (i = 0; i<delay; i++) {
1095 if (pts_buffer[i] != AV_NOPTS_VALUE) {
1096 int64_t diff = FFABS(pts_buffer[i] - dts)
1097 + (uint64_t)st->internal->pts_reorder_error[i];
1098 diff = FFMAX(diff, st->internal->pts_reorder_error[i]);
1099 st->internal->pts_reorder_error[i] = diff;
1100 st->internal->pts_reorder_error_count[i]++;
1101 if (st->internal->pts_reorder_error_count[i] > 250) {
1102 st->internal->pts_reorder_error[i] >>= 1;
1103 st->internal->pts_reorder_error_count[i] >>= 1;
1110 if (dts == AV_NOPTS_VALUE)
1111 dts = pts_buffer[0];
1117 * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
1118 * of the packets in a window.
1120 static void update_dts_from_pts(AVFormatContext *s, int stream_index,
1121 PacketList *pkt_buffer)
1123 AVStream *st = s->streams[stream_index];
1124 int delay = st->internal->avctx->has_b_frames;
1127 int64_t pts_buffer[MAX_REORDER_DELAY+1];
1129 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1130 pts_buffer[i] = AV_NOPTS_VALUE;
1132 for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
1133 if (pkt_buffer->pkt.stream_index != stream_index)
1136 if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1137 pts_buffer[0] = pkt_buffer->pkt.pts;
1138 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1139 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1141 pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
1146 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1147 int64_t dts, int64_t pts, AVPacket *pkt)
1149 AVStream *st = s->streams[stream_index];
1150 PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1151 PacketList *pktl_it;
1155 if (st->first_dts != AV_NOPTS_VALUE ||
1156 dts == AV_NOPTS_VALUE ||
1157 st->cur_dts == AV_NOPTS_VALUE ||
1158 st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1159 dts < INT_MIN + (st->cur_dts - RELATIVE_TS_BASE) ||
1163 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1165 shift = (uint64_t)st->first_dts - RELATIVE_TS_BASE;
1167 if (is_relative(pts))
1170 for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
1171 if (pktl_it->pkt.stream_index != stream_index)
1173 if (is_relative(pktl_it->pkt.pts))
1174 pktl_it->pkt.pts += shift;
1176 if (is_relative(pktl_it->pkt.dts))
1177 pktl_it->pkt.dts += shift;
1179 if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1180 st->start_time = pktl_it->pkt.pts;
1181 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1182 st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1186 if (has_decode_delay_been_guessed(st)) {
1187 update_dts_from_pts(s, stream_index, pktl);
1190 if (st->start_time == AV_NOPTS_VALUE) {
1191 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
1192 st->start_time = pts;
1194 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1195 st->start_time = av_sat_add64(st->start_time, av_rescale_q(st->internal->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base));
1199 static void update_initial_durations(AVFormatContext *s, AVStream *st,
1200 int stream_index, int64_t duration)
1202 PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1203 int64_t cur_dts = RELATIVE_TS_BASE;
1205 if (st->first_dts != AV_NOPTS_VALUE) {
1206 if (st->internal->update_initial_durations_done)
1208 st->internal->update_initial_durations_done = 1;
1209 cur_dts = st->first_dts;
1210 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1211 if (pktl->pkt.stream_index == stream_index) {
1212 if (pktl->pkt.pts != pktl->pkt.dts ||
1213 pktl->pkt.dts != AV_NOPTS_VALUE ||
1216 cur_dts -= duration;
1219 if (pktl && pktl->pkt.dts != st->first_dts) {
1220 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1221 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1225 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1228 pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1229 st->first_dts = cur_dts;
1230 } else if (st->cur_dts != RELATIVE_TS_BASE)
1233 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1234 if (pktl->pkt.stream_index != stream_index)
1236 if ((pktl->pkt.pts == pktl->pkt.dts ||
1237 pktl->pkt.pts == AV_NOPTS_VALUE) &&
1238 (pktl->pkt.dts == AV_NOPTS_VALUE ||
1239 pktl->pkt.dts == st->first_dts ||
1240 pktl->pkt.dts == RELATIVE_TS_BASE) &&
1241 !pktl->pkt.duration) {
1242 pktl->pkt.dts = cur_dts;
1243 if (!st->internal->avctx->has_b_frames)
1244 pktl->pkt.pts = cur_dts;
1245 pktl->pkt.duration = duration;
1248 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1251 st->cur_dts = cur_dts;
1254 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1255 AVCodecParserContext *pc, AVPacket *pkt,
1256 int64_t next_dts, int64_t next_pts)
1258 int num, den, presentation_delayed, delay, i;
1260 AVRational duration;
1261 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1262 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1264 if (s->flags & AVFMT_FLAG_NOFILLIN)
1267 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1268 if (pkt->dts == pkt->pts && st->internal->last_dts_for_order_check != AV_NOPTS_VALUE) {
1269 if (st->internal->last_dts_for_order_check <= pkt->dts) {
1270 st->internal->dts_ordered++;
1272 av_log(s, st->internal->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1273 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1275 st->internal->last_dts_for_order_check);
1276 st->internal->dts_misordered++;
1278 if (st->internal->dts_ordered + st->internal->dts_misordered > 250) {
1279 st->internal->dts_ordered >>= 1;
1280 st->internal->dts_misordered >>= 1;
1284 st->internal->last_dts_for_order_check = pkt->dts;
1285 if (st->internal->dts_ordered < 8*st->internal->dts_misordered && pkt->dts == pkt->pts)
1286 pkt->dts = AV_NOPTS_VALUE;
1289 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1290 pkt->dts = AV_NOPTS_VALUE;
1292 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1293 && !st->internal->avctx->has_b_frames)
1294 //FIXME Set low_delay = 0 when has_b_frames = 1
1295 st->internal->avctx->has_b_frames = 1;
1297 /* do we have a video B-frame ? */
1298 delay = st->internal->avctx->has_b_frames;
1299 presentation_delayed = 0;
1301 /* XXX: need has_b_frame, but cannot get it if the codec is
1302 * not initialized */
1304 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1305 presentation_delayed = 1;
1307 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1308 st->pts_wrap_bits < 63 && pkt->dts > INT64_MIN + (1LL << st->pts_wrap_bits) &&
1309 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1310 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1311 pkt->dts -= 1LL << st->pts_wrap_bits;
1313 pkt->pts += 1LL << st->pts_wrap_bits;
1316 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1317 * We take the conservative approach and discard both.
1318 * Note: If this is misbehaving for an H.264 file, then possibly
1319 * presentation_delayed is not set correctly. */
1320 if (delay == 1 && pkt->dts == pkt->pts &&
1321 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1322 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1323 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1324 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1325 pkt->dts = AV_NOPTS_VALUE;
1328 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1329 if (pkt->duration <= 0) {
1330 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1332 duration = (AVRational) {num, den};
1333 pkt->duration = av_rescale_rnd(1,
1334 num * (int64_t) st->time_base.den,
1335 den * (int64_t) st->time_base.num,
1340 if (pkt->duration > 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1341 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1343 /* Correct timestamps with byte offset if demuxers only have timestamps
1344 * on packet boundaries */
1345 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1346 /* this will estimate bitrate based on this frame's duration and size */
1347 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1348 if (pkt->pts != AV_NOPTS_VALUE)
1350 if (pkt->dts != AV_NOPTS_VALUE)
1354 /* This may be redundant, but it should not hurt. */
1355 if (pkt->dts != AV_NOPTS_VALUE &&
1356 pkt->pts != AV_NOPTS_VALUE &&
1357 pkt->pts > pkt->dts)
1358 presentation_delayed = 1;
1360 if (s->debug & FF_FDEBUG_TS)
1361 av_log(s, AV_LOG_DEBUG,
1362 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1363 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1364 pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1366 /* Interpolate PTS and DTS if they are not present. We skip H264
1367 * currently because delay and has_b_frames are not reliably set. */
1368 if ((delay == 0 || (delay == 1 && pc)) &&
1370 if (presentation_delayed) {
1371 /* DTS = decompression timestamp */
1372 /* PTS = presentation timestamp */
1373 if (pkt->dts == AV_NOPTS_VALUE)
1374 pkt->dts = st->last_IP_pts;
1375 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1376 if (pkt->dts == AV_NOPTS_VALUE)
1377 pkt->dts = st->cur_dts;
1379 /* This is tricky: the dts must be incremented by the duration
1380 * of the frame we are displaying, i.e. the last I- or P-frame. */
1381 if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1382 st->last_IP_duration = pkt->duration;
1383 if (pkt->dts != AV_NOPTS_VALUE)
1384 st->cur_dts = av_sat_add64(pkt->dts, st->last_IP_duration);
1385 if (pkt->dts != AV_NOPTS_VALUE &&
1386 pkt->pts == AV_NOPTS_VALUE &&
1387 st->last_IP_duration > 0 &&
1388 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1389 next_dts != next_pts &&
1390 next_pts != AV_NOPTS_VALUE)
1391 pkt->pts = next_dts;
1393 if ((uint64_t)pkt->duration <= INT32_MAX)
1394 st->last_IP_duration = pkt->duration;
1395 st->last_IP_pts = pkt->pts;
1396 /* Cannot compute PTS if not present (we can compute it only
1397 * by knowing the future. */
1398 } else if (pkt->pts != AV_NOPTS_VALUE ||
1399 pkt->dts != AV_NOPTS_VALUE ||
1400 pkt->duration > 0 ) {
1402 /* presentation is not delayed : PTS and DTS are the same */
1403 if (pkt->pts == AV_NOPTS_VALUE)
1404 pkt->pts = pkt->dts;
1405 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1407 if (pkt->pts == AV_NOPTS_VALUE)
1408 pkt->pts = st->cur_dts;
1409 pkt->dts = pkt->pts;
1410 if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1411 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1415 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1416 st->internal->pts_buffer[0] = pkt->pts;
1417 for (i = 0; i<delay && st->internal->pts_buffer[i] > st->internal->pts_buffer[i + 1]; i++)
1418 FFSWAP(int64_t, st->internal->pts_buffer[i], st->internal->pts_buffer[i + 1]);
1420 if(has_decode_delay_been_guessed(st))
1421 pkt->dts = select_from_pts_buffer(st, st->internal->pts_buffer, pkt->dts);
1423 // We skipped it above so we try here.
1425 // This should happen on the first packet
1426 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1427 if (pkt->dts > st->cur_dts)
1428 st->cur_dts = pkt->dts;
1430 if (s->debug & FF_FDEBUG_TS)
1431 av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1432 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), st->index, st->id);
1435 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || ff_is_intra_only(st->codecpar->codec_id))
1436 pkt->flags |= AV_PKT_FLAG_KEY;
1440 * Parse a packet, add all split parts to parse_queue.
1442 * @param pkt Packet to parse; must not be NULL.
1443 * @param flush Indicates whether to flush. If set, pkt must be blank.
1445 static int parse_packet(AVFormatContext *s, AVPacket *pkt,
1446 int stream_index, int flush)
1448 AVPacket *out_pkt = s->internal->parse_pkt;
1449 AVStream *st = s->streams[stream_index];
1450 uint8_t *data = pkt->data;
1451 int size = pkt->size;
1452 int ret = 0, got_output = flush;
1454 if (!size && !flush && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1455 // preserve 0-size sync packets
1456 compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1459 while (size > 0 || (flush && got_output)) {
1461 int64_t next_pts = pkt->pts;
1462 int64_t next_dts = pkt->dts;
1464 len = av_parser_parse2(st->parser, st->internal->avctx,
1465 &out_pkt->data, &out_pkt->size, data, size,
1466 pkt->pts, pkt->dts, pkt->pos);
1468 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1470 /* increment read pointer */
1471 av_assert1(data || !len);
1472 data = len ? data + len : data;
1475 got_output = !!out_pkt->size;
1480 if (pkt->buf && out_pkt->data == pkt->data) {
1481 /* reference pkt->buf only when out_pkt->data is guaranteed to point
1482 * to data in it and not in the parser's internal buffer. */
1483 /* XXX: Ensure this is the case with all parsers when st->parser->flags
1484 * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1485 out_pkt->buf = av_buffer_ref(pkt->buf);
1486 if (!out_pkt->buf) {
1487 ret = AVERROR(ENOMEM);
1491 ret = av_packet_make_refcounted(out_pkt);
1496 if (pkt->side_data) {
1497 out_pkt->side_data = pkt->side_data;
1498 out_pkt->side_data_elems = pkt->side_data_elems;
1499 pkt->side_data = NULL;
1500 pkt->side_data_elems = 0;
1503 /* set the duration */
1504 out_pkt->duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1505 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1506 if (st->internal->avctx->sample_rate > 0) {
1508 av_rescale_q_rnd(st->parser->duration,
1509 (AVRational) { 1, st->internal->avctx->sample_rate },
1515 out_pkt->stream_index = st->index;
1516 out_pkt->pts = st->parser->pts;
1517 out_pkt->dts = st->parser->dts;
1518 out_pkt->pos = st->parser->pos;
1519 out_pkt->flags |= pkt->flags & AV_PKT_FLAG_DISCARD;
1521 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1522 out_pkt->pos = st->parser->frame_offset;
1524 if (st->parser->key_frame == 1 ||
1525 (st->parser->key_frame == -1 &&
1526 st->parser->pict_type == AV_PICTURE_TYPE_I))
1527 out_pkt->flags |= AV_PKT_FLAG_KEY;
1529 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1530 out_pkt->flags |= AV_PKT_FLAG_KEY;
1532 compute_pkt_fields(s, st, st->parser, out_pkt, next_dts, next_pts);
1534 ret = avpriv_packet_list_put(&s->internal->parse_queue,
1535 &s->internal->parse_queue_end,
1541 /* end of the stream => close and free the parser */
1543 av_parser_close(st->parser);
1549 av_packet_unref(out_pkt);
1550 av_packet_unref(pkt);
1554 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1556 return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1559 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1561 int ret, i, got_packet = 0;
1562 AVDictionary *metadata = NULL;
1564 while (!got_packet && !s->internal->parse_queue) {
1567 /* read next packet */
1568 ret = ff_read_packet(s, pkt);
1570 if (ret == AVERROR(EAGAIN))
1572 /* flush the parsers */
1573 for (i = 0; i < s->nb_streams; i++) {
1575 if (st->parser && st->need_parsing)
1576 parse_packet(s, pkt, st->index, 1);
1578 /* all remaining packets are now in parse_queue =>
1579 * really terminate parsing */
1583 st = s->streams[pkt->stream_index];
1585 st->event_flags |= AVSTREAM_EVENT_FLAG_NEW_PACKETS;
1587 /* update context if required */
1588 if (st->internal->need_context_update) {
1589 if (avcodec_is_open(st->internal->avctx)) {
1590 av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1591 avcodec_close(st->internal->avctx);
1592 st->internal->info->found_decoder = 0;
1595 /* close parser, because it depends on the codec */
1596 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
1597 av_parser_close(st->parser);
1601 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
1603 av_packet_unref(pkt);
1607 #if FF_API_LAVF_AVCTX
1608 FF_DISABLE_DEPRECATION_WARNINGS
1609 /* update deprecated public codec context */
1610 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
1612 av_packet_unref(pkt);
1615 FF_ENABLE_DEPRECATION_WARNINGS
1618 st->internal->need_context_update = 0;
1621 if (pkt->pts != AV_NOPTS_VALUE &&
1622 pkt->dts != AV_NOPTS_VALUE &&
1623 pkt->pts < pkt->dts) {
1624 av_log(s, AV_LOG_WARNING,
1625 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1627 av_ts2str(pkt->pts),
1628 av_ts2str(pkt->dts),
1631 if (s->debug & FF_FDEBUG_TS)
1632 av_log(s, AV_LOG_DEBUG,
1633 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1635 av_ts2str(pkt->pts),
1636 av_ts2str(pkt->dts),
1637 pkt->size, pkt->duration, pkt->flags);
1639 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1640 st->parser = av_parser_init(st->codecpar->codec_id);
1642 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1643 "%s, packets or times may be invalid.\n",
1644 avcodec_get_name(st->codecpar->codec_id));
1645 /* no parser available: just output the raw packets */
1646 st->need_parsing = AVSTREAM_PARSE_NONE;
1647 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1648 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1649 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1650 st->parser->flags |= PARSER_FLAG_ONCE;
1651 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1652 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1655 if (!st->need_parsing || !st->parser) {
1656 /* no parsing needed: we just output the packet as is */
1657 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1658 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1659 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1660 ff_reduce_index(s, st->index);
1661 av_add_index_entry(st, pkt->pos, pkt->dts,
1662 0, 0, AVINDEX_KEYFRAME);
1665 } else if (st->discard < AVDISCARD_ALL) {
1666 if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1668 st->codecpar->sample_rate = st->internal->avctx->sample_rate;
1669 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
1670 st->codecpar->channels = st->internal->avctx->channels;
1671 st->codecpar->channel_layout = st->internal->avctx->channel_layout;
1672 st->codecpar->codec_id = st->internal->avctx->codec_id;
1675 av_packet_unref(pkt);
1677 if (pkt->flags & AV_PKT_FLAG_KEY)
1678 st->internal->skip_to_keyframe = 0;
1679 if (st->internal->skip_to_keyframe) {
1680 av_packet_unref(pkt);
1685 if (!got_packet && s->internal->parse_queue)
1686 ret = avpriv_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1689 AVStream *st = s->streams[pkt->stream_index];
1690 int discard_padding = 0;
1691 if (st->internal->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1692 int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1693 int64_t sample = ts_to_samples(st, pts);
1694 int duration = ts_to_samples(st, pkt->duration);
1695 int64_t end_sample = sample + duration;
1696 if (duration > 0 && end_sample >= st->internal->first_discard_sample &&
1697 sample < st->internal->last_discard_sample)
1698 discard_padding = FFMIN(end_sample - st->internal->first_discard_sample, duration);
1700 if (st->internal->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1701 st->internal->skip_samples = st->internal->start_skip_samples;
1702 if (st->internal->skip_samples || discard_padding) {
1703 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1705 AV_WL32(p, st->internal->skip_samples);
1706 AV_WL32(p + 4, discard_padding);
1707 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->internal->skip_samples, discard_padding);
1709 st->internal->skip_samples = 0;
1712 if (st->internal->inject_global_side_data) {
1713 for (i = 0; i < st->nb_side_data; i++) {
1714 AVPacketSideData *src_sd = &st->side_data[i];
1717 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1720 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1722 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1726 memcpy(dst_data, src_sd->data, src_sd->size);
1728 st->internal->inject_global_side_data = 0;
1732 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1734 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1735 av_dict_copy(&s->metadata, metadata, 0);
1736 av_dict_free(&metadata);
1737 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1740 #if FF_API_LAVF_AVCTX
1741 update_stream_avctx(s);
1744 if (s->debug & FF_FDEBUG_TS)
1745 av_log(s, AV_LOG_DEBUG,
1746 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1747 "size=%d, duration=%"PRId64", flags=%d\n",
1749 av_ts2str(pkt->pts),
1750 av_ts2str(pkt->dts),
1751 pkt->size, pkt->duration, pkt->flags);
1753 /* A demuxer might have returned EOF because of an IO error, let's
1754 * propagate this back to the user. */
1755 if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1761 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1763 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1769 ret = s->internal->packet_buffer
1770 ? avpriv_packet_list_get(&s->internal->packet_buffer,
1771 &s->internal->packet_buffer_end, pkt)
1772 : read_frame_internal(s, pkt);
1779 PacketList *pktl = s->internal->packet_buffer;
1782 AVPacket *next_pkt = &pktl->pkt;
1784 if (next_pkt->dts != AV_NOPTS_VALUE) {
1785 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1786 // last dts seen for this stream. if any of packets following
1787 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1788 int64_t last_dts = next_pkt->dts;
1789 av_assert2(wrap_bits <= 64);
1790 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1791 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1792 av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1793 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1795 next_pkt->pts = pktl->pkt.dts;
1797 if (last_dts != AV_NOPTS_VALUE) {
1798 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1799 last_dts = pktl->pkt.dts;
1804 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1805 // Fixing the last reference frame had none pts issue (For MXF etc).
1806 // We only do this when
1808 // 2. we are not able to resolve a pts value for current packet.
1809 // 3. the packets for this stream at the end of the files had valid dts.
1810 next_pkt->pts = last_dts + next_pkt->duration;
1812 pktl = s->internal->packet_buffer;
1815 /* read packet from packet buffer, if there is data */
1816 st = s->streams[next_pkt->stream_index];
1817 if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1818 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1819 ret = avpriv_packet_list_get(&s->internal->packet_buffer,
1820 &s->internal->packet_buffer_end, pkt);
1825 ret = read_frame_internal(s, pkt);
1827 if (pktl && ret != AVERROR(EAGAIN)) {
1834 ret = avpriv_packet_list_put(&s->internal->packet_buffer,
1835 &s->internal->packet_buffer_end,
1838 av_packet_unref(pkt);
1845 st = s->streams[pkt->stream_index];
1846 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1847 ff_reduce_index(s, st->index);
1848 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1851 if (is_relative(pkt->dts))
1852 pkt->dts -= RELATIVE_TS_BASE;
1853 if (is_relative(pkt->pts))
1854 pkt->pts -= RELATIVE_TS_BASE;
1859 /* XXX: suppress the packet queue */
1860 static void flush_packet_queue(AVFormatContext *s)
1864 avpriv_packet_list_free(&s->internal->parse_queue, &s->internal->parse_queue_end);
1865 avpriv_packet_list_free(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1866 avpriv_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1868 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1871 /*******************************************************/
1874 int av_find_default_stream_index(AVFormatContext *s)
1878 int best_stream = 0;
1879 int best_score = INT_MIN;
1881 if (s->nb_streams <= 0)
1883 for (i = 0; i < s->nb_streams; i++) {
1886 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1887 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
1889 if (st->codecpar->width && st->codecpar->height)
1893 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1894 if (st->codecpar->sample_rate)
1897 if (st->codec_info_nb_frames)
1900 if (st->discard != AVDISCARD_ALL)
1903 if (score > best_score) {
1911 /** Flush the frame reader. */
1912 void ff_read_frame_flush(AVFormatContext *s)
1917 flush_packet_queue(s);
1919 /* Reset read state for each stream. */
1920 for (i = 0; i < s->nb_streams; i++) {
1924 av_parser_close(st->parser);
1927 st->last_IP_pts = AV_NOPTS_VALUE;
1928 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
1929 if (st->first_dts == AV_NOPTS_VALUE)
1930 st->cur_dts = RELATIVE_TS_BASE;
1932 /* We set the current DTS to an unspecified origin. */
1933 st->cur_dts = AV_NOPTS_VALUE;
1935 st->probe_packets = s->max_probe_packets;
1937 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1938 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
1940 if (s->internal->inject_global_side_data)
1941 st->internal->inject_global_side_data = 1;
1943 st->internal->skip_samples = 0;
1947 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1951 for (i = 0; i < s->nb_streams; i++) {
1952 AVStream *st = s->streams[i];
1955 av_rescale(timestamp,
1956 st->time_base.den * (int64_t) ref_st->time_base.num,
1957 st->time_base.num * (int64_t) ref_st->time_base.den);
1961 void ff_reduce_index(AVFormatContext *s, int stream_index)
1963 AVStream *st = s->streams[stream_index];
1964 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1966 if ((unsigned) st->internal->nb_index_entries >= max_entries) {
1968 for (i = 0; 2 * i < st->internal->nb_index_entries; i++)
1969 st->internal->index_entries[i] = st->internal->index_entries[2 * i];
1970 st->internal->nb_index_entries = i;
1974 int ff_add_index_entry(AVIndexEntry **index_entries,
1975 int *nb_index_entries,
1976 unsigned int *index_entries_allocated_size,
1977 int64_t pos, int64_t timestamp,
1978 int size, int distance, int flags)
1980 AVIndexEntry *entries, *ie;
1983 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1986 if (timestamp == AV_NOPTS_VALUE)
1987 return AVERROR(EINVAL);
1989 if (size < 0 || size > 0x3FFFFFFF)
1990 return AVERROR(EINVAL);
1992 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1993 timestamp -= RELATIVE_TS_BASE;
1995 entries = av_fast_realloc(*index_entries,
1996 index_entries_allocated_size,
1997 (*nb_index_entries + 1) *
1998 sizeof(AVIndexEntry));
2002 *index_entries = entries;
2004 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
2005 timestamp, AVSEEK_FLAG_ANY);
2008 index = (*nb_index_entries)++;
2009 ie = &entries[index];
2010 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
2012 ie = &entries[index];
2013 if (ie->timestamp != timestamp) {
2014 if (ie->timestamp <= timestamp)
2016 memmove(entries + index + 1, entries + index,
2017 sizeof(AVIndexEntry) * (*nb_index_entries - index));
2018 (*nb_index_entries)++;
2019 } else if (ie->pos == pos && distance < ie->min_distance)
2020 // do not reduce the distance
2021 distance = ie->min_distance;
2025 ie->timestamp = timestamp;
2026 ie->min_distance = distance;
2033 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
2034 int size, int distance, int flags)
2036 timestamp = wrap_timestamp(st, timestamp);
2037 return ff_add_index_entry(&st->internal->index_entries, &st->internal->nb_index_entries,
2038 &st->internal->index_entries_allocated_size, pos,
2039 timestamp, size, distance, flags);
2042 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
2043 int64_t wanted_timestamp, int flags)
2051 // Optimize appending index entries at the end.
2052 if (b && entries[b - 1].timestamp < wanted_timestamp)
2058 // Search for the next non-discarded packet.
2059 while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
2061 if (m == b && entries[m].timestamp >= wanted_timestamp) {
2067 timestamp = entries[m].timestamp;
2068 if (timestamp >= wanted_timestamp)
2070 if (timestamp <= wanted_timestamp)
2073 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
2075 if (!(flags & AVSEEK_FLAG_ANY))
2076 while (m >= 0 && m < nb_entries &&
2077 !(entries[m].flags & AVINDEX_KEYFRAME))
2078 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
2080 if (m == nb_entries)
2085 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
2088 int64_t pos_delta = 0;
2090 //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
2091 const char *proto = avio_find_protocol_name(s->url);
2093 av_assert0(time_tolerance >= 0);
2096 av_log(s, AV_LOG_INFO,
2097 "Protocol name not provided, cannot determine if input is local or "
2098 "a network protocol, buffers and access patterns cannot be configured "
2099 "optimally without knowing the protocol\n");
2102 if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2105 for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
2106 AVStream *st1 = s->streams[ist1];
2107 for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
2108 AVStream *st2 = s->streams[ist2];
2114 for (i1 = i2 = 0; i1 < st1->internal->nb_index_entries; i1++) {
2115 AVIndexEntry *e1 = &st1->internal->index_entries[i1];
2116 int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
2118 skip = FFMAX(skip, e1->size);
2119 for (; i2 < st2->internal->nb_index_entries; i2++) {
2120 AVIndexEntry *e2 = &st2->internal->index_entries[i2];
2121 int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
2122 if (e2_pts < e1_pts || e2_pts - (uint64_t)e1_pts < time_tolerance)
2124 pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
2132 /* XXX This could be adjusted depending on protocol*/
2133 if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
2134 av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
2136 /* realloc the buffer and the original data will be retained */
2137 if (ffio_realloc_buf(s->pb, pos_delta)) {
2138 av_log(s, AV_LOG_ERROR, "Realloc buffer fail.\n");
2142 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
2145 if (skip < (1<<23)) {
2146 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
2150 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2152 return ff_index_search_timestamp(st->internal->index_entries, st->internal->nb_index_entries,
2153 wanted_timestamp, flags);
2156 int avformat_index_get_entries_count(const AVStream *st)
2158 return st->internal->nb_index_entries;
2161 const AVIndexEntry *avformat_index_get_entry(const AVStream *st, int idx)
2163 if (idx < 0 || idx >= st->internal->nb_index_entries)
2166 return &st->internal->index_entries[idx];
2169 const AVIndexEntry *avformat_index_get_entry_from_timestamp(const AVStream *st,
2170 int64_t wanted_timestamp,
2173 int idx = ff_index_search_timestamp(st->internal->index_entries,
2174 st->internal->nb_index_entries,
2175 wanted_timestamp, flags);
2180 return &st->internal->index_entries[idx];
2183 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
2184 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2186 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
2187 if (stream_index >= 0)
2188 ts = wrap_timestamp(s->streams[stream_index], ts);
2192 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
2193 int64_t target_ts, int flags)
2195 const AVInputFormat *avif = s->iformat;
2196 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2197 int64_t ts_min, ts_max, ts;
2202 if (stream_index < 0)
2205 av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2208 ts_min = AV_NOPTS_VALUE;
2209 pos_limit = -1; // GCC falsely says it may be uninitialized.
2211 st = s->streams[stream_index];
2212 if (st->internal->index_entries) {
2215 /* FIXME: Whole function must be checked for non-keyframe entries in
2216 * index case, especially read_timestamp(). */
2217 index = av_index_search_timestamp(st, target_ts,
2218 flags | AVSEEK_FLAG_BACKWARD);
2219 index = FFMAX(index, 0);
2220 e = &st->internal->index_entries[index];
2222 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
2224 ts_min = e->timestamp;
2225 av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2226 pos_min, av_ts2str(ts_min));
2228 av_assert1(index == 0);
2231 index = av_index_search_timestamp(st, target_ts,
2232 flags & ~AVSEEK_FLAG_BACKWARD);
2233 av_assert0(index < st->internal->nb_index_entries);
2235 e = &st->internal->index_entries[index];
2236 av_assert1(e->timestamp >= target_ts);
2238 ts_max = e->timestamp;
2239 pos_limit = pos_max - e->min_distance;
2240 av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2241 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2245 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
2246 ts_min, ts_max, flags, &ts, avif->read_timestamp);
2251 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2254 ff_read_frame_flush(s);
2255 ff_update_cur_dts(s, st, ts);
2260 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
2261 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2263 int64_t step = 1024;
2264 int64_t limit, ts_max;
2265 int64_t filesize = avio_size(s->pb);
2266 int64_t pos_max = filesize - 1;
2269 pos_max = FFMAX(0, (pos_max) - step);
2270 ts_max = ff_read_timestamp(s, stream_index,
2271 &pos_max, limit, read_timestamp);
2273 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2274 if (ts_max == AV_NOPTS_VALUE)
2278 int64_t tmp_pos = pos_max + 1;
2279 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
2280 &tmp_pos, INT64_MAX, read_timestamp);
2281 if (tmp_ts == AV_NOPTS_VALUE)
2283 av_assert0(tmp_pos > pos_max);
2286 if (tmp_pos >= filesize)
2298 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
2299 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
2300 int64_t ts_min, int64_t ts_max,
2301 int flags, int64_t *ts_ret,
2302 int64_t (*read_timestamp)(struct AVFormatContext *, int,
2303 int64_t *, int64_t))
2310 av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2312 if (ts_min == AV_NOPTS_VALUE) {
2313 pos_min = s->internal->data_offset;
2314 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2315 if (ts_min == AV_NOPTS_VALUE)
2319 if (ts_min >= target_ts) {
2324 if (ts_max == AV_NOPTS_VALUE) {
2325 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2327 pos_limit = pos_max;
2330 if (ts_max <= target_ts) {
2335 av_assert0(ts_min < ts_max);
2338 while (pos_min < pos_limit) {
2339 av_log(s, AV_LOG_TRACE,
2340 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2341 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2342 av_assert0(pos_limit <= pos_max);
2344 if (no_change == 0) {
2345 int64_t approximate_keyframe_distance = pos_max - pos_limit;
2346 // interpolate position (better than dichotomy)
2347 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2349 pos_min - approximate_keyframe_distance;
2350 } else if (no_change == 1) {
2351 // bisection if interpolation did not change min / max pos last time
2352 pos = (pos_min + pos_limit) >> 1;
2354 /* linear search if bisection failed, can only happen if there
2355 * are very few or no keyframes between min/max */
2360 else if (pos > pos_limit)
2364 // May pass pos_limit instead of -1.
2365 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2370 av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2371 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2372 pos_min, pos, pos_max,
2373 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2374 pos_limit, start_pos, no_change);
2375 if (ts == AV_NOPTS_VALUE) {
2376 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2379 if (target_ts <= ts) {
2380 pos_limit = start_pos - 1;
2384 if (target_ts >= ts) {
2390 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2391 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2394 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2396 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2397 av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2398 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2404 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2405 int64_t pos, int flags)
2407 int64_t pos_min, pos_max;
2409 pos_min = s->internal->data_offset;
2410 pos_max = avio_size(s->pb) - 1;
2414 else if (pos > pos_max)
2417 avio_seek(s->pb, pos, SEEK_SET);
2419 s->io_repositioned = 1;
2424 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2425 int64_t timestamp, int flags)
2432 st = s->streams[stream_index];
2434 index = av_index_search_timestamp(st, timestamp, flags);
2436 if (index < 0 && st->internal->nb_index_entries &&
2437 timestamp < st->internal->index_entries[0].timestamp)
2440 if (index < 0 || index == st->internal->nb_index_entries - 1) {
2441 AVPacket *pkt = s->internal->pkt;
2444 if (st->internal->nb_index_entries) {
2445 av_assert0(st->internal->index_entries);
2446 ie = &st->internal->index_entries[st->internal->nb_index_entries - 1];
2447 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2449 ff_update_cur_dts(s, st, ie->timestamp);
2451 if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2454 av_packet_unref(pkt);
2458 read_status = av_read_frame(s, pkt);
2459 } while (read_status == AVERROR(EAGAIN));
2460 if (read_status < 0)
2462 if (stream_index == pkt->stream_index && pkt->dts > timestamp) {
2463 if (pkt->flags & AV_PKT_FLAG_KEY) {
2464 av_packet_unref(pkt);
2467 if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2468 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);
2469 av_packet_unref(pkt);
2473 av_packet_unref(pkt);
2475 index = av_index_search_timestamp(st, timestamp, flags);
2480 ff_read_frame_flush(s);
2481 if (s->iformat->read_seek)
2482 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2484 ie = &st->internal->index_entries[index];
2485 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2487 ff_update_cur_dts(s, st, ie->timestamp);
2492 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2493 int64_t timestamp, int flags)
2498 if (flags & AVSEEK_FLAG_BYTE) {
2499 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2501 ff_read_frame_flush(s);
2502 return seek_frame_byte(s, stream_index, timestamp, flags);
2505 if (stream_index < 0) {
2506 stream_index = av_find_default_stream_index(s);
2507 if (stream_index < 0)
2510 st = s->streams[stream_index];
2511 /* timestamp for default must be expressed in AV_TIME_BASE units */
2512 timestamp = av_rescale(timestamp, st->time_base.den,
2513 AV_TIME_BASE * (int64_t) st->time_base.num);
2516 /* first, we try the format specific seek */
2517 if (s->iformat->read_seek) {
2518 ff_read_frame_flush(s);
2519 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2525 if (s->iformat->read_timestamp &&
2526 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2527 ff_read_frame_flush(s);
2528 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2529 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2530 ff_read_frame_flush(s);
2531 return seek_frame_generic(s, stream_index, timestamp, flags);
2536 int av_seek_frame(AVFormatContext *s, int stream_index,
2537 int64_t timestamp, int flags)
2541 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2542 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2543 if ((flags & AVSEEK_FLAG_BACKWARD))
2547 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2548 flags & ~AVSEEK_FLAG_BACKWARD);
2551 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2554 ret = avformat_queue_attached_pictures(s);
2559 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2560 int64_t ts, int64_t max_ts, int flags)
2562 if (min_ts > ts || max_ts < ts)
2564 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2565 return AVERROR(EINVAL);
2568 flags |= AVSEEK_FLAG_ANY;
2569 flags &= ~AVSEEK_FLAG_BACKWARD;
2571 if (s->iformat->read_seek2) {
2573 ff_read_frame_flush(s);
2575 if (stream_index == -1 && s->nb_streams == 1) {
2576 AVRational time_base = s->streams[0]->time_base;
2577 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2578 min_ts = av_rescale_rnd(min_ts, time_base.den,
2579 time_base.num * (int64_t)AV_TIME_BASE,
2580 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2581 max_ts = av_rescale_rnd(max_ts, time_base.den,
2582 time_base.num * (int64_t)AV_TIME_BASE,
2583 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2587 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2591 ret = avformat_queue_attached_pictures(s);
2595 if (s->iformat->read_timestamp) {
2596 // try to seek via read_timestamp()
2599 // Fall back on old API if new is not implemented but old is.
2600 // Note the old API has somewhat different semantics.
2601 if (s->iformat->read_seek || 1) {
2602 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2603 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2604 if (ret<0 && ts != min_ts && max_ts != ts) {
2605 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2607 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2612 // try some generic seek like seek_frame_generic() but with new ts semantics
2613 return -1; //unreachable
2616 int avformat_flush(AVFormatContext *s)
2618 ff_read_frame_flush(s);
2622 /*******************************************************/
2625 * Return TRUE if the stream has accurate duration in any stream.
2627 * @return TRUE if the stream has accurate duration for at least one component.
2629 static int has_duration(AVFormatContext *ic)
2634 for (i = 0; i < ic->nb_streams; i++) {
2635 st = ic->streams[i];
2636 if (st->duration != AV_NOPTS_VALUE)
2639 if (ic->duration != AV_NOPTS_VALUE)
2645 * Estimate the stream timings from the one of each components.
2647 * Also computes the global bitrate if possible.
2649 static void update_stream_timings(AVFormatContext *ic)
2651 int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2652 int64_t duration, duration1, duration_text, filesize;
2656 start_time = INT64_MAX;
2657 start_time_text = INT64_MAX;
2658 end_time = INT64_MIN;
2659 end_time_text = INT64_MIN;
2660 duration = INT64_MIN;
2661 duration_text = INT64_MIN;
2663 for (i = 0; i < ic->nb_streams; i++) {
2664 AVStream *st = ic->streams[i];
2665 int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2666 st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
2667 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2668 start_time1 = av_rescale_q(st->start_time, st->time_base,
2671 start_time_text = FFMIN(start_time_text, start_time1);
2673 start_time = FFMIN(start_time, start_time1);
2674 end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
2676 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
2677 if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2678 end_time1 += start_time1;
2680 end_time_text = FFMAX(end_time_text, end_time1);
2682 end_time = FFMAX(end_time, end_time1);
2684 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2685 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2686 p->start_time = start_time1;
2687 if (p->end_time < end_time1)
2688 p->end_time = end_time1;
2691 if (st->duration != AV_NOPTS_VALUE) {
2692 duration1 = av_rescale_q(st->duration, st->time_base,
2695 duration_text = FFMAX(duration_text, duration1);
2697 duration = FFMAX(duration, duration1);
2700 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2701 start_time = start_time_text;
2702 else if (start_time > start_time_text)
2703 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2705 if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2706 end_time = end_time_text;
2707 else if (end_time < end_time_text)
2708 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
2710 if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
2711 duration = duration_text;
2712 else if (duration < duration_text)
2713 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
2715 if (start_time != INT64_MAX) {
2716 ic->start_time = start_time;
2717 if (end_time != INT64_MIN) {
2718 if (ic->nb_programs > 1) {
2719 for (i = 0; i < ic->nb_programs; i++) {
2720 p = ic->programs[i];
2721 if (p->start_time != AV_NOPTS_VALUE &&
2722 p->end_time > p->start_time &&
2723 p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2724 duration = FFMAX(duration, p->end_time - p->start_time);
2726 } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2727 duration = FFMAX(duration, end_time - start_time);
2731 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2732 ic->duration = duration;
2734 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2735 /* compute the bitrate */
2736 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2737 (double) ic->duration;
2738 if (bitrate >= 0 && bitrate <= INT64_MAX)
2739 ic->bit_rate = bitrate;
2743 static void fill_all_stream_timings(AVFormatContext *ic)
2748 update_stream_timings(ic);
2749 for (i = 0; i < ic->nb_streams; i++) {
2750 st = ic->streams[i];
2751 if (st->start_time == AV_NOPTS_VALUE) {
2752 if (ic->start_time != AV_NOPTS_VALUE)
2753 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2755 if (ic->duration != AV_NOPTS_VALUE)
2756 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2762 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2764 int64_t filesize, duration;
2765 int i, show_warning = 0;
2768 /* if bit_rate is already set, we believe it */
2769 if (ic->bit_rate <= 0) {
2770 int64_t bit_rate = 0;
2771 for (i = 0; i < ic->nb_streams; i++) {
2772 st = ic->streams[i];
2773 if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
2774 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2775 if (st->codecpar->bit_rate > 0) {
2776 if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2780 bit_rate += st->codecpar->bit_rate;
2781 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2782 // If we have a videostream with packets but without a bitrate
2783 // then consider the sum not known
2788 ic->bit_rate = bit_rate;
2791 /* if duration is already set, we believe it */
2792 if (ic->duration == AV_NOPTS_VALUE &&
2793 ic->bit_rate != 0) {
2794 filesize = ic->pb ? avio_size(ic->pb) : 0;
2795 if (filesize > ic->internal->data_offset) {
2796 filesize -= ic->internal->data_offset;
2797 for (i = 0; i < ic->nb_streams; i++) {
2798 st = ic->streams[i];
2799 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2800 && st->duration == AV_NOPTS_VALUE) {
2801 duration = av_rescale(filesize, 8LL * st->time_base.den,
2803 (int64_t) st->time_base.num);
2804 st->duration = duration;
2811 av_log(ic, AV_LOG_WARNING,
2812 "Estimating duration from bitrate, this may be inaccurate\n");
2815 #define DURATION_MAX_READ_SIZE 250000LL
2816 #define DURATION_MAX_RETRY 6
2818 /* only usable for MPEG-PS streams */
2819 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2821 AVPacket *pkt = ic->internal->pkt;
2823 int num, den, read_size, i, ret;
2824 int found_duration = 0;
2826 int64_t filesize, offset, duration;
2829 /* flush packet queue */
2830 flush_packet_queue(ic);
2832 for (i = 0; i < ic->nb_streams; i++) {
2833 st = ic->streams[i];
2834 if (st->start_time == AV_NOPTS_VALUE &&
2835 st->first_dts == AV_NOPTS_VALUE &&
2836 st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
2837 av_log(ic, AV_LOG_WARNING,
2838 "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2841 av_parser_close(st->parser);
2846 if (ic->skip_estimate_duration_from_pts) {
2847 av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
2848 goto skip_duration_calc;
2851 av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2852 /* estimate the end time (duration) */
2853 /* XXX: may need to support wrapping */
2854 filesize = ic->pb ? avio_size(ic->pb) : 0;
2856 is_end = found_duration;
2857 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2861 avio_seek(ic->pb, offset, SEEK_SET);
2864 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2868 ret = ff_read_packet(ic, pkt);
2869 } while (ret == AVERROR(EAGAIN));
2872 read_size += pkt->size;
2873 st = ic->streams[pkt->stream_index];
2874 if (pkt->pts != AV_NOPTS_VALUE &&
2875 (st->start_time != AV_NOPTS_VALUE ||
2876 st->first_dts != AV_NOPTS_VALUE)) {
2877 if (pkt->duration == 0) {
2878 ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2880 pkt->duration = av_rescale_rnd(1,
2881 num * (int64_t) st->time_base.den,
2882 den * (int64_t) st->time_base.num,
2886 duration = pkt->pts + pkt->duration;
2888 if (st->start_time != AV_NOPTS_VALUE)
2889 duration -= st->start_time;
2891 duration -= st->first_dts;
2893 if (st->duration == AV_NOPTS_VALUE || st->internal->info->last_duration<= 0 ||
2894 (st->duration < duration && FFABS(duration - st->internal->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2895 st->duration = duration;
2896 st->internal->info->last_duration = duration;
2899 av_packet_unref(pkt);
2902 /* check if all audio/video streams have valid duration */
2905 for (i = 0; i < ic->nb_streams; i++) {
2906 st = ic->streams[i];
2907 switch (st->codecpar->codec_type) {
2908 case AVMEDIA_TYPE_VIDEO:
2909 case AVMEDIA_TYPE_AUDIO:
2910 if (st->duration == AV_NOPTS_VALUE)
2917 ++retry <= DURATION_MAX_RETRY);
2919 av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2921 /* warn about audio/video streams which duration could not be estimated */
2922 for (i = 0; i < ic->nb_streams; i++) {
2923 st = ic->streams[i];
2924 if (st->duration == AV_NOPTS_VALUE) {
2925 switch (st->codecpar->codec_type) {
2926 case AVMEDIA_TYPE_VIDEO:
2927 case AVMEDIA_TYPE_AUDIO:
2928 if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2929 av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
2931 av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
2936 fill_all_stream_timings(ic);
2938 avio_seek(ic->pb, old_offset, SEEK_SET);
2939 for (i = 0; i < ic->nb_streams; i++) {
2942 st = ic->streams[i];
2943 st->cur_dts = st->first_dts;
2944 st->last_IP_pts = AV_NOPTS_VALUE;
2945 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
2946 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2947 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
2951 /* 1:1 map to AVDurationEstimationMethod */
2952 static const char *const duration_name[] = {
2953 [AVFMT_DURATION_FROM_PTS] = "pts",
2954 [AVFMT_DURATION_FROM_STREAM] = "stream",
2955 [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2958 static const char *duration_estimate_name(enum AVDurationEstimationMethod method)
2960 return duration_name[method];
2963 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2967 /* get the file size, if possible */
2968 if (ic->iformat->flags & AVFMT_NOFILE) {
2971 file_size = avio_size(ic->pb);
2972 file_size = FFMAX(0, file_size);
2975 if ((!strcmp(ic->iformat->name, "mpeg") ||
2976 !strcmp(ic->iformat->name, "mpegts")) &&
2977 file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2978 /* get accurate estimate from the PTSes */
2979 estimate_timings_from_pts(ic, old_offset);
2980 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2981 } else if (has_duration(ic)) {
2982 /* at least one component has timings - we use them for all
2984 fill_all_stream_timings(ic);
2985 /* nut demuxer estimate the duration from PTS */
2986 if(!strcmp(ic->iformat->name, "nut"))
2987 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2989 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2991 /* less precise: use bitrate info */
2992 estimate_timings_from_bit_rate(ic);
2993 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2995 update_stream_timings(ic);
2997 for (unsigned i = 0; i < ic->nb_streams; i++) {
2998 AVStream *st = ic->streams[i];
2999 if (st->time_base.den)
3000 av_log(ic, AV_LOG_TRACE, "stream %u: start_time: %s duration: %s\n", i,
3001 av_ts2timestr(st->start_time, &st->time_base),
3002 av_ts2timestr(st->duration, &st->time_base));
3004 av_log(ic, AV_LOG_TRACE,
3005 "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
3006 av_ts2timestr(ic->start_time, &AV_TIME_BASE_Q),
3007 av_ts2timestr(ic->duration, &AV_TIME_BASE_Q),
3008 duration_estimate_name(ic->duration_estimation_method),
3009 (int64_t)ic->bit_rate / 1000);
3012 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
3014 AVCodecContext *avctx = st->internal->avctx;
3016 #define FAIL(errmsg) do { \
3018 *errmsg_ptr = errmsg; \
3022 if ( avctx->codec_id == AV_CODEC_ID_NONE
3023 && avctx->codec_type != AVMEDIA_TYPE_DATA)
3024 FAIL("unknown codec");
3025 switch (avctx->codec_type) {
3026 case AVMEDIA_TYPE_AUDIO:
3027 if (!avctx->frame_size && determinable_frame_size(avctx))
3028 FAIL("unspecified frame size");
3029 if (st->internal->info->found_decoder >= 0 &&
3030 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
3031 FAIL("unspecified sample format");
3032 if (!avctx->sample_rate)
3033 FAIL("unspecified sample rate");
3034 if (!avctx->channels)
3035 FAIL("unspecified number of channels");
3036 if (st->internal->info->found_decoder >= 0 && !st->internal->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
3037 FAIL("no decodable DTS frames");
3039 case AVMEDIA_TYPE_VIDEO:
3041 FAIL("unspecified size");
3042 if (st->internal->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
3043 FAIL("unspecified pixel format");
3044 if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
3045 if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !st->codec_info_nb_frames)
3046 FAIL("no frame in rv30/40 and no sar");
3048 case AVMEDIA_TYPE_SUBTITLE:
3049 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
3050 FAIL("unspecified size");
3052 case AVMEDIA_TYPE_DATA:
3053 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
3059 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
3060 static int try_decode_frame(AVFormatContext *s, AVStream *st,
3061 const AVPacket *avpkt, AVDictionary **options)
3063 AVCodecContext *avctx = st->internal->avctx;
3064 const AVCodec *codec;
3065 int got_picture = 1, ret = 0;
3066 AVFrame *frame = av_frame_alloc();
3067 AVSubtitle subtitle;
3068 AVPacket pkt = *avpkt;
3069 int do_skip_frame = 0;
3070 enum AVDiscard skip_frame;
3073 return AVERROR(ENOMEM);
3075 if (!avcodec_is_open(avctx) &&
3076 st->internal->info->found_decoder <= 0 &&
3077 (st->codecpar->codec_id != -st->internal->info->found_decoder || !st->codecpar->codec_id)) {
3078 AVDictionary *thread_opt = NULL;
3080 codec = find_probe_decoder(s, st, st->codecpar->codec_id);
3083 st->internal->info->found_decoder = -st->codecpar->codec_id;
3088 /* Force thread count to 1 since the H.264 decoder will not extract
3089 * SPS and PPS to extradata during multi-threaded decoding. */
3090 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
3091 /* Force lowres to 0. The decoder might reduce the video size by the
3092 * lowres factor, and we don't want that propagated to the stream's
3094 av_dict_set(options ? options : &thread_opt, "lowres", "0", 0);
3095 if (s->codec_whitelist)
3096 av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3097 ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3099 av_dict_free(&thread_opt);
3101 st->internal->info->found_decoder = -avctx->codec_id;
3104 st->internal->info->found_decoder = 1;
3105 } else if (!st->internal->info->found_decoder)
3106 st->internal->info->found_decoder = 1;
3108 if (st->internal->info->found_decoder < 0) {
3113 if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
3115 skip_frame = avctx->skip_frame;
3116 avctx->skip_frame = AVDISCARD_ALL;
3119 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
3121 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
3122 (!st->codec_info_nb_frames &&
3123 (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
3125 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3126 avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3127 ret = avcodec_send_packet(avctx, &pkt);
3128 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3132 ret = avcodec_receive_frame(avctx, frame);
3135 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
3137 } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3138 ret = avcodec_decode_subtitle2(avctx, &subtitle,
3139 &got_picture, &pkt);
3141 avsubtitle_free(&subtitle);
3147 st->internal->nb_decoded_frames++;
3152 if (!pkt.data && !got_picture)
3156 if (do_skip_frame) {
3157 avctx->skip_frame = skip_frame;
3160 av_frame_free(&frame);
3164 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3166 while (tags->id != AV_CODEC_ID_NONE) {
3174 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3177 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3178 if (tag == tags[i].tag)
3180 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3181 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3183 return AV_CODEC_ID_NONE;
3186 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
3188 if (bps <= 0 || bps > 64)
3189 return AV_CODEC_ID_NONE;
3194 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
3196 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
3198 return AV_CODEC_ID_NONE;
3203 if (sflags & (1 << (bps - 1))) {
3206 return AV_CODEC_ID_PCM_S8;
3208 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
3210 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
3212 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
3214 return be ? AV_CODEC_ID_PCM_S64BE : AV_CODEC_ID_PCM_S64LE;
3216 return AV_CODEC_ID_NONE;
3221 return AV_CODEC_ID_PCM_U8;
3223 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
3225 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
3227 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
3229 return AV_CODEC_ID_NONE;
3235 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3238 if (!av_codec_get_tag2(tags, id, &tag))
3243 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
3247 for (i = 0; tags && tags[i]; i++) {
3248 const AVCodecTag *codec_tags = tags[i];
3249 while (codec_tags->id != AV_CODEC_ID_NONE) {
3250 if (codec_tags->id == id) {
3251 *tag = codec_tags->tag;
3260 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3263 for (i = 0; tags && tags[i]; i++) {
3264 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
3265 if (id != AV_CODEC_ID_NONE)
3268 return AV_CODEC_ID_NONE;
3271 static int chapter_start_cmp(const void *p1, const void *p2)
3273 AVChapter *ch1 = *(AVChapter**)p1;
3274 AVChapter *ch2 = *(AVChapter**)p2;
3275 int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
3278 return (ch1 > ch2) - (ch1 < ch2);
3281 static int compute_chapters_end(AVFormatContext *s)
3284 int64_t max_time = 0;
3285 AVChapter **timetable = av_malloc(s->nb_chapters * sizeof(*timetable));
3288 return AVERROR(ENOMEM);
3290 if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3291 max_time = s->duration +
3292 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3294 for (i = 0; i < s->nb_chapters; i++)
3295 timetable[i] = s->chapters[i];
3296 qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
3298 for (i = 0; i < s->nb_chapters; i++)
3299 if (timetable[i]->end == AV_NOPTS_VALUE) {
3300 AVChapter *ch = timetable[i];
3301 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3305 if (i + 1 < s->nb_chapters) {
3306 AVChapter *ch1 = timetable[i + 1];
3307 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3309 if (next_start > ch->start && next_start < end)
3312 ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3318 static int get_std_framerate(int i)
3321 return (i + 1) * 1001;
3325 return (i + 31) * 1001 * 12;
3329 return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3333 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3336 /* Is the time base unreliable?
3337 * This is a heuristic to balance between quick acceptance of the values in
3338 * the headers vs. some extra checks.
3339 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3340 * MPEG-2 commonly misuses field repeat flags to store different framerates.
3341 * And there are "variable" fps files this needs to detect as well. */
3342 static int tb_unreliable(AVCodecContext *c)
3344 if (c->time_base.den >= 101LL * c->time_base.num ||
3345 c->time_base.den < 5LL * c->time_base.num ||
3346 // c->codec_tag == AV_RL32("DIVX") ||
3347 // c->codec_tag == AV_RL32("XVID") ||
3348 c->codec_tag == AV_RL32("mp4v") ||
3349 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3350 c->codec_id == AV_CODEC_ID_GIF ||
3351 c->codec_id == AV_CODEC_ID_HEVC ||
3352 c->codec_id == AV_CODEC_ID_H264)
3357 int ff_alloc_extradata(AVCodecParameters *par, int size)
3359 av_freep(&par->extradata);
3360 par->extradata_size = 0;
3362 if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3363 return AVERROR(EINVAL);
3365 par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3366 if (!par->extradata)
3367 return AVERROR(ENOMEM);
3369 memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3370 par->extradata_size = size;
3375 int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3377 int ret = ff_alloc_extradata(par, size);
3380 ret = avio_read(pb, par->extradata, size);
3382 av_freep(&par->extradata);
3383 par->extradata_size = 0;
3384 av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3385 return ret < 0 ? ret : AVERROR_INVALIDDATA;
3391 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3394 int64_t last = st->internal->info->last_dts;
3396 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3397 && ts - (uint64_t)last < INT64_MAX) {
3398 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3399 int64_t duration = ts - last;
3401 if (!st->internal->info->duration_error)
3402 st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3403 if (!st->internal->info->duration_error)
3404 return AVERROR(ENOMEM);
3406 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3407 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3408 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3409 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3410 int framerate = get_std_framerate(i);
3411 double sdts = dts*framerate/(1001*12);
3412 for (j= 0; j<2; j++) {
3413 int64_t ticks = llrint(sdts+j*0.5);
3414 double error= sdts - ticks + j*0.5;
3415 st->internal->info->duration_error[j][0][i] += error;
3416 st->internal->info->duration_error[j][1][i] += error*error;
3420 if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3421 st->internal->info->duration_count++;
3422 st->internal->info->rfps_duration_sum += duration;
3425 if (st->internal->info->duration_count % 10 == 0) {
3426 int n = st->internal->info->duration_count;
3427 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3428 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3429 double a0 = st->internal->info->duration_error[0][0][i] / n;
3430 double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3431 double a1 = st->internal->info->duration_error[1][0][i] / n;
3432 double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3433 if (error0 > 0.04 && error1 > 0.04) {
3434 st->internal->info->duration_error[0][1][i] = 2e10;
3435 st->internal->info->duration_error[1][1][i] = 2e10;
3441 // ignore the first 4 values, they might have some random jitter
3442 if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3443 st->internal->info->duration_gcd = av_gcd(st->internal->info->duration_gcd, duration);
3445 if (ts != AV_NOPTS_VALUE)
3446 st->internal->info->last_dts = ts;
3451 void ff_rfps_calculate(AVFormatContext *ic)
3455 for (i = 0; i < ic->nb_streams; i++) {
3456 AVStream *st = ic->streams[i];
3458 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3460 // the check for tb_unreliable() is not completely correct, since this is not about handling
3461 // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3462 // ipmovie.c produces.
3463 if (tb_unreliable(st->internal->avctx) && st->internal->info->duration_count > 15 && st->internal->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num &&
3464 st->internal->info->duration_gcd < INT64_MAX / st->time_base.num)
3465 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->internal->info->duration_gcd, INT_MAX);
3466 if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3467 && tb_unreliable(st->internal->avctx)) {
3469 double best_error= 0.01;
3470 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3472 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3475 if (st->internal->info->codec_info_duration &&
3476 st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3478 if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3481 if (av_q2d(st->time_base) * st->internal->info->rfps_duration_sum / st->internal->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3484 for (k= 0; k<2; k++) {
3485 int n = st->internal->info->duration_count;
3486 double a= st->internal->info->duration_error[k][0][j] / n;
3487 double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3489 if (error < best_error && best_error> 0.000000001) {
3491 num = get_std_framerate(j);
3494 av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3497 // do not increase frame rate by more than 1 % in order to match a standard rate.
3498 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3499 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3501 if ( !st->avg_frame_rate.num
3502 && st->r_frame_rate.num && st->internal->info->rfps_duration_sum
3503 && st->internal->info->codec_info_duration <= 0
3504 && st->internal->info->duration_count > 2
3505 && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->internal->info->rfps_duration_sum / (double)st->internal->info->duration_count) <= 1.0
3507 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3508 st->avg_frame_rate = st->r_frame_rate;
3511 av_freep(&st->internal->info->duration_error);
3512 st->internal->info->last_dts = AV_NOPTS_VALUE;
3513 st->internal->info->duration_count = 0;
3514 st->internal->info->rfps_duration_sum = 0;
3518 static int extract_extradata_check(AVStream *st)
3520 const AVBitStreamFilter *f;
3522 f = av_bsf_get_by_name("extract_extradata");
3527 const enum AVCodecID *ids;
3528 for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3529 if (*ids == st->codecpar->codec_id)
3536 static int extract_extradata_init(AVStream *st)
3538 AVStreamInternal *sti = st->internal;
3539 const AVBitStreamFilter *f;
3542 f = av_bsf_get_by_name("extract_extradata");
3546 /* check that the codec id is supported */
3547 ret = extract_extradata_check(st);
3551 ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3555 ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3560 sti->extract_extradata.bsf->time_base_in = st->time_base;
3562 ret = av_bsf_init(sti->extract_extradata.bsf);
3567 sti->extract_extradata.inited = 1;
3571 av_bsf_free(&sti->extract_extradata.bsf);
3575 static int extract_extradata(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
3577 AVStreamInternal *sti = st->internal;
3578 AVPacket *pkt_ref = s->internal->parse_pkt;
3581 if (!sti->extract_extradata.inited) {
3582 ret = extract_extradata_init(st);
3587 if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3590 ret = av_packet_ref(pkt_ref, pkt);
3594 ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3596 av_packet_unref(pkt_ref);
3600 while (ret >= 0 && !sti->avctx->extradata) {
3601 ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3603 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3608 for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3609 AVPacketSideData *side_data = &pkt_ref->side_data[i];
3610 if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3611 sti->avctx->extradata = side_data->data;
3612 sti->avctx->extradata_size = side_data->size;
3613 side_data->data = NULL;
3614 side_data->size = 0;
3618 av_packet_unref(pkt_ref);
3624 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
3628 for (i = 0; i < avctx->nb_coded_side_data; i++) {
3629 const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3631 dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3633 return AVERROR(ENOMEM);
3634 memcpy(dst_data, sd_src->data, sd_src->size);
3639 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3641 int i, count = 0, ret = 0, j;
3644 AVCodecContext *avctx;
3645 AVPacket *pkt1 = ic->internal->pkt;
3646 int64_t old_offset = avio_tell(ic->pb);
3647 // new streams might appear, no options for those
3648 int orig_nb_streams = ic->nb_streams;
3650 int64_t max_analyze_duration = ic->max_analyze_duration;
3651 int64_t max_stream_analyze_duration;
3652 int64_t max_subtitle_analyze_duration;
3653 int64_t probesize = ic->probesize;
3654 int eof_reached = 0;
3655 int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3657 flush_codecs = probesize > 0;
3659 av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3661 max_stream_analyze_duration = max_analyze_duration;
3662 max_subtitle_analyze_duration = max_analyze_duration;
3663 if (!max_analyze_duration) {
3664 max_stream_analyze_duration =
3665 max_analyze_duration = 5*AV_TIME_BASE;
3666 max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3667 if (!strcmp(ic->iformat->name, "flv"))
3668 max_stream_analyze_duration = 90*AV_TIME_BASE;
3669 if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3670 max_stream_analyze_duration = 7*AV_TIME_BASE;
3674 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3675 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3677 for (i = 0; i < ic->nb_streams; i++) {
3678 const AVCodec *codec;
3679 AVDictionary *thread_opt = NULL;
3680 st = ic->streams[i];
3681 avctx = st->internal->avctx;
3683 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3684 st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3685 /* if (!st->time_base.num)
3687 if (!avctx->time_base.num)
3688 avctx->time_base = st->time_base;
3691 /* check if the caller has overridden the codec id */
3692 #if FF_API_LAVF_AVCTX
3693 FF_DISABLE_DEPRECATION_WARNINGS
3694 if (st->codec->codec_id != st->internal->orig_codec_id) {
3695 st->codecpar->codec_id = st->codec->codec_id;
3696 st->codecpar->codec_type = st->codec->codec_type;
3697 st->internal->orig_codec_id = st->codec->codec_id;
3699 FF_ENABLE_DEPRECATION_WARNINGS
3701 // only for the split stuff
3702 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3703 st->parser = av_parser_init(st->codecpar->codec_id);
3705 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3706 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3707 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3708 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3710 } else if (st->need_parsing) {
3711 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3712 "%s, packets or times may be invalid.\n",
3713 avcodec_get_name(st->codecpar->codec_id));
3717 if (st->codecpar->codec_id != st->internal->orig_codec_id)
3718 st->internal->orig_codec_id = st->codecpar->codec_id;
3720 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3722 goto find_stream_info_err;
3723 if (st->internal->request_probe <= 0)
3724 st->internal->avctx_inited = 1;
3726 codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3728 /* Force thread count to 1 since the H.264 decoder will not extract
3729 * SPS and PPS to extradata during multi-threaded decoding. */
3730 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3731 /* Force lowres to 0. The decoder might reduce the video size by the
3732 * lowres factor, and we don't want that propagated to the stream's
3734 av_dict_set(options ? &options[i] : &thread_opt, "lowres", "0", 0);
3736 if (ic->codec_whitelist)
3737 av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3739 // Try to just open decoders, in case this is enough to get parameters.
3740 // Also ensure that subtitle_header is properly set.
3741 if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0 ||
3742 st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3743 if (codec && !avctx->codec)
3744 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3745 av_log(ic, AV_LOG_WARNING,
3746 "Failed to open codec in %s\n",__FUNCTION__);
3749 av_dict_free(&thread_opt);
3752 for (i = 0; i < ic->nb_streams; i++) {
3753 #if FF_API_R_FRAME_RATE
3754 ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
3756 ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
3757 ic->streams[i]->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3762 const AVPacket *pkt;
3763 int analyzed_all_streams;
3764 if (ff_check_interrupt(&ic->interrupt_callback)) {
3766 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3770 /* check if one codec still needs to be handled */
3771 for (i = 0; i < ic->nb_streams; i++) {
3772 int fps_analyze_framecount = 20;
3775 st = ic->streams[i];
3776 if (!has_codec_parameters(st, NULL))
3778 /* If the timebase is coarse (like the usual millisecond precision
3779 * of mkv), we need to analyze more frames to reliably arrive at
3780 * the correct fps. */
3781 if (av_q2d(st->time_base) > 0.0005)
3782 fps_analyze_framecount *= 2;
3783 if (!tb_unreliable(st->internal->avctx))
3784 fps_analyze_framecount = 0;
3785 if (ic->fps_probe_size >= 0)
3786 fps_analyze_framecount = ic->fps_probe_size;
3787 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3788 fps_analyze_framecount = 0;
3789 /* variable fps and no guess at the real fps */
3790 count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3791 st->internal->info->codec_info_duration_fields/2 :
3792 st->internal->info->duration_count;
3793 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3794 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3795 if (count < fps_analyze_framecount)
3798 // Look at the first 3 frames if there is evidence of frame delay
3799 // but the decoder delay is not set.
3800 if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3802 if (!st->internal->avctx->extradata &&
3803 (!st->internal->extract_extradata.inited ||
3804 st->internal->extract_extradata.bsf) &&
3805 extract_extradata_check(st))
3807 if (st->first_dts == AV_NOPTS_VALUE &&
3808 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3809 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3810 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3811 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3814 analyzed_all_streams = 0;
3815 if (!missing_streams || !*missing_streams)
3816 if (i == ic->nb_streams) {
3817 analyzed_all_streams = 1;
3818 /* NOTE: If the format has no header, then we need to read some
3819 * packets to get most of the streams, so we cannot stop here. */
3820 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3821 /* If we found the info for all the codecs, we can stop. */
3823 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3828 /* We did not get all the codec info, but we read too much data. */
3829 if (read_size >= probesize) {
3831 av_log(ic, AV_LOG_DEBUG,
3832 "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3833 for (i = 0; i < ic->nb_streams; i++)
3834 if (!ic->streams[i]->r_frame_rate.num &&
3835 ic->streams[i]->internal->info->duration_count <= 1 &&
3836 ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3837 strcmp(ic->iformat->name, "image2"))
3838 av_log(ic, AV_LOG_WARNING,
3839 "Stream #%d: not enough frames to estimate rate; "
3840 "consider increasing probesize\n", i);
3844 /* NOTE: A new stream can be added there if no header in file
3845 * (AVFMTCTX_NOHEADER). */
3846 ret = read_frame_internal(ic, pkt1);
3847 if (ret == AVERROR(EAGAIN))
3856 if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3857 ret = avpriv_packet_list_put(&ic->internal->packet_buffer,
3858 &ic->internal->packet_buffer_end,
3861 goto unref_then_goto_end;
3863 pkt = &ic->internal->packet_buffer_end->pkt;
3868 st = ic->streams[pkt->stream_index];
3869 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3870 read_size += pkt->size;
3872 avctx = st->internal->avctx;
3873 if (!st->internal->avctx_inited) {
3874 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3876 goto unref_then_goto_end;
3877 st->internal->avctx_inited = 1;
3880 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3881 /* check for non-increasing dts */
3882 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3883 st->internal->info->fps_last_dts >= pkt->dts) {
3884 av_log(ic, AV_LOG_DEBUG,
3885 "Non-increasing DTS in stream %d: packet %d with DTS "
3886 "%"PRId64", packet %d with DTS %"PRId64"\n",
3887 st->index, st->internal->info->fps_last_dts_idx,
3888 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3890 st->internal->info->fps_first_dts =
3891 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3893 /* Check for a discontinuity in dts. If the difference in dts
3894 * is more than 1000 times the average packet duration in the
3895 * sequence, we treat it as a discontinuity. */
3896 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3897 st->internal->info->fps_last_dts_idx > st->internal->info->fps_first_dts_idx &&
3898 (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3899 (st->internal->info->fps_last_dts - (uint64_t)st->internal->info->fps_first_dts) /
3900 (st->internal->info->fps_last_dts_idx - st->internal->info->fps_first_dts_idx)) {
3901 av_log(ic, AV_LOG_WARNING,
3902 "DTS discontinuity in stream %d: packet %d with DTS "
3903 "%"PRId64", packet %d with DTS %"PRId64"\n",
3904 st->index, st->internal->info->fps_last_dts_idx,
3905 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3907 st->internal->info->fps_first_dts =
3908 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3911 /* update stored dts values */
3912 if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3913 st->internal->info->fps_first_dts = pkt->dts;
3914 st->internal->info->fps_first_dts_idx = st->codec_info_nb_frames;
3916 st->internal->info->fps_last_dts = pkt->dts;
3917 st->internal->info->fps_last_dts_idx = st->codec_info_nb_frames;
3919 if (st->codec_info_nb_frames>1) {
3923 if (st->time_base.den > 0)
3924 t = av_rescale_q(st->internal->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3925 if (st->avg_frame_rate.num > 0)
3926 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3929 && st->codec_info_nb_frames>30
3930 && st->internal->info->fps_first_dts != AV_NOPTS_VALUE
3931 && st->internal->info->fps_last_dts != AV_NOPTS_VALUE) {
3932 int64_t dur = av_sat_sub64(st->internal->info->fps_last_dts, st->internal->info->fps_first_dts);
3933 t = FFMAX(t, av_rescale_q(dur, st->time_base, AV_TIME_BASE_Q));
3936 if (analyzed_all_streams) limit = max_analyze_duration;
3937 else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3938 else limit = max_stream_analyze_duration;
3941 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3943 t, pkt->stream_index);
3944 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3945 av_packet_unref(pkt1);
3948 if (pkt->duration) {
3949 if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3950 st->internal->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->internal->info->codec_info_duration + pkt->duration);
3952 st->internal->info->codec_info_duration += pkt->duration;
3953 st->internal->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3956 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3957 #if FF_API_R_FRAME_RATE
3958 ff_rfps_add_frame(ic, st, pkt->dts);
3960 if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3961 st->internal->info->frame_delay_evidence = 1;
3963 if (!st->internal->avctx->extradata) {
3964 ret = extract_extradata(ic, st, pkt);
3966 goto unref_then_goto_end;
3969 /* If still no information, we try to open the codec and to
3970 * decompress the frame. We try to avoid that in most cases as
3971 * it takes longer and uses more memory. For MPEG-4, we need to
3972 * decompress for QuickTime.
3974 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3975 * least one frame of codec data, this makes sure the codec initializes
3976 * the channel configuration and does not only trust the values from
3978 try_decode_frame(ic, st, pkt,
3979 (options && i < orig_nb_streams) ? &options[i] : NULL);
3981 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3982 av_packet_unref(pkt1);
3984 st->codec_info_nb_frames++;
3990 for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3991 st = ic->streams[stream_index];
3992 avctx = st->internal->avctx;
3993 if (!has_codec_parameters(st, NULL)) {
3994 const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3995 if (codec && !avctx->codec) {
3996 AVDictionary *opts = NULL;
3997 if (ic->codec_whitelist)
3998 av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3999 if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
4000 av_log(ic, AV_LOG_WARNING,
4001 "Failed to open codec in %s\n",__FUNCTION__);
4002 av_dict_free(&opts);
4006 // EOF already reached while reading the stream above.
4007 // So continue with reoordering DTS with whatever delay we have.
4008 if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
4009 update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
4015 AVPacket *empty_pkt = ic->internal->pkt;
4017 av_packet_unref(empty_pkt);
4019 for (i = 0; i < ic->nb_streams; i++) {
4021 st = ic->streams[i];
4023 /* flush the decoders */
4024 if (st->internal->info->found_decoder == 1) {
4026 err = try_decode_frame(ic, st, empty_pkt,
4027 (options && i < orig_nb_streams)
4028 ? &options[i] : NULL);
4029 } while (err > 0 && !has_codec_parameters(st, NULL));
4032 av_log(ic, AV_LOG_INFO,
4033 "decoding for stream %d failed\n", st->index);
4039 ff_rfps_calculate(ic);
4041 for (i = 0; i < ic->nb_streams; i++) {
4042 st = ic->streams[i];
4043 avctx = st->internal->avctx;
4044 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
4045 if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
4046 uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
4047 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
4048 avctx->codec_tag= tag;
4051 /* estimate average framerate if not set by demuxer */
4052 if (st->internal->info->codec_info_duration_fields &&
4053 !st->avg_frame_rate.num &&
4054 st->internal->info->codec_info_duration) {
4056 double best_error = 0.01;
4057 AVRational codec_frame_rate = avctx->framerate;
4059 if (st->internal->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
4060 st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
4061 st->internal->info->codec_info_duration < 0)
4063 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4064 st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
4065 st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
4067 /* Round guessed framerate to a "standard" framerate if it's
4068 * within 1% of the original estimate. */
4069 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
4070 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
4071 double error = fabs(av_q2d(st->avg_frame_rate) /
4072 av_q2d(std_fps) - 1);
4074 if (error < best_error) {
4076 best_fps = std_fps.num;
4079 if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
4080 error = fabs(av_q2d(codec_frame_rate) /
4081 av_q2d(std_fps) - 1);
4082 if (error < best_error) {
4084 best_fps = std_fps.num;
4089 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4090 best_fps, 12 * 1001, INT_MAX);
4093 if (!st->r_frame_rate.num) {
4094 if ( avctx->time_base.den * (int64_t) st->time_base.num
4095 <= avctx->time_base.num * avctx->ticks_per_frame * (uint64_t) st->time_base.den) {
4096 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4097 avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4099 st->r_frame_rate.num = st->time_base.den;
4100 st->r_frame_rate.den = st->time_base.num;
4103 if (st->internal->display_aspect_ratio.num && st->internal->display_aspect_ratio.den) {
4104 AVRational hw_ratio = { avctx->height, avctx->width };
4105 st->sample_aspect_ratio = av_mul_q(st->internal->display_aspect_ratio,
4108 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4109 if (!avctx->bits_per_coded_sample)
4110 avctx->bits_per_coded_sample =
4111 av_get_bits_per_sample(avctx->codec_id);
4112 // set stream disposition based on audio service type
4113 switch (avctx->audio_service_type) {
4114 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4115 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
4117 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4118 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
4120 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4121 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
4123 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4124 st->disposition = AV_DISPOSITION_COMMENT;
4126 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4127 st->disposition = AV_DISPOSITION_KARAOKE;
4134 estimate_timings(ic, old_offset);
4136 av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4138 if (ret >= 0 && ic->nb_streams)
4139 /* We could not have all the codec parameters before EOF. */
4141 for (i = 0; i < ic->nb_streams; i++) {
4143 st = ic->streams[i];
4145 /* if no packet was ever seen, update context now for has_codec_parameters */
4146 if (!st->internal->avctx_inited) {
4147 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4148 st->codecpar->format == AV_SAMPLE_FMT_NONE)
4149 st->codecpar->format = st->internal->avctx->sample_fmt;
4150 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
4152 goto find_stream_info_err;
4154 if (!has_codec_parameters(st, &errmsg)) {
4156 avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4157 av_log(ic, AV_LOG_WARNING,
4158 "Could not find codec parameters for stream %d (%s): %s\n"
4159 "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4160 i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4166 ret = compute_chapters_end(ic);
4168 goto find_stream_info_err;
4170 /* update the stream parameters from the internal codec contexts */
4171 for (i = 0; i < ic->nb_streams; i++) {
4172 st = ic->streams[i];
4174 if (st->internal->avctx_inited) {
4175 ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
4177 goto find_stream_info_err;
4178 ret = add_coded_side_data(st, st->internal->avctx);
4180 goto find_stream_info_err;
4183 #if FF_API_LAVF_AVCTX
4184 FF_DISABLE_DEPRECATION_WARNINGS
4185 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
4187 goto find_stream_info_err;
4189 // The old API (AVStream.codec) "requires" the resolution to be adjusted
4190 // by the lowres factor.
4191 if (st->internal->avctx->lowres && st->internal->avctx->width) {
4192 st->codec->lowres = st->internal->avctx->lowres;
4193 st->codec->width = st->internal->avctx->width;
4194 st->codec->height = st->internal->avctx->height;
4197 if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4198 st->codec->time_base = st->internal->avctx->time_base;
4199 st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
4201 st->codec->framerate = st->avg_frame_rate;
4203 if (st->internal->avctx->subtitle_header) {
4204 st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
4205 if (!st->codec->subtitle_header)
4206 goto find_stream_info_err;
4207 st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
4208 memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
4209 st->codec->subtitle_header_size);
4212 // Fields unavailable in AVCodecParameters
4213 st->codec->coded_width = st->internal->avctx->coded_width;
4214 st->codec->coded_height = st->internal->avctx->coded_height;
4215 st->codec->properties = st->internal->avctx->properties;
4216 FF_ENABLE_DEPRECATION_WARNINGS
4219 st->internal->avctx_inited = 0;
4222 find_stream_info_err:
4223 for (i = 0; i < ic->nb_streams; i++) {
4224 st = ic->streams[i];
4225 if (st->internal->info)
4226 av_freep(&st->internal->info->duration_error);
4227 avcodec_close(ic->streams[i]->internal->avctx);
4228 av_freep(&ic->streams[i]->internal->info);
4229 av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
4232 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
4233 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
4236 unref_then_goto_end:
4237 av_packet_unref(pkt1);
4238 goto find_stream_info_err;
4241 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4245 for (i = 0; i < ic->nb_programs; i++) {
4246 if (ic->programs[i] == last) {
4250 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
4251 if (ic->programs[i]->stream_index[j] == s)
4252 return ic->programs[i];
4258 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
4259 int wanted_stream_nb, int related_stream,
4260 AVCodec **decoder_ret, int flags)
4262 int i, nb_streams = ic->nb_streams;
4263 int ret = AVERROR_STREAM_NOT_FOUND;
4264 int best_count = -1, best_multiframe = -1, best_disposition = -1;
4265 int count, multiframe, disposition;
4266 int64_t best_bitrate = -1;
4268 unsigned *program = NULL;
4269 const AVCodec *decoder = NULL, *best_decoder = NULL;
4271 if (related_stream >= 0 && wanted_stream_nb < 0) {
4272 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4274 program = p->stream_index;
4275 nb_streams = p->nb_stream_indexes;
4278 for (i = 0; i < nb_streams; i++) {
4279 int real_stream_index = program ? program[i] : i;
4280 AVStream *st = ic->streams[real_stream_index];
4281 AVCodecParameters *par = st->codecpar;
4282 if (par->codec_type != type)
4284 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4286 if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4289 decoder = find_decoder(ic, st, par->codec_id);
4292 ret = AVERROR_DECODER_NOT_FOUND;
4296 disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
4297 + !! (st->disposition & AV_DISPOSITION_DEFAULT);
4298 count = st->codec_info_nb_frames;
4299 bitrate = par->bit_rate;
4300 multiframe = FFMIN(5, count);
4301 if ((best_disposition > disposition) ||
4302 (best_disposition == disposition && best_multiframe > multiframe) ||
4303 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate > bitrate) ||
4304 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4306 best_disposition = disposition;
4308 best_bitrate = bitrate;
4309 best_multiframe = multiframe;
4310 ret = real_stream_index;
4311 best_decoder = decoder;
4312 if (program && i == nb_streams - 1 && ret < 0) {
4314 nb_streams = ic->nb_streams;
4315 /* no related stream found, try again with everything */
4320 *decoder_ret = (AVCodec*)best_decoder;
4324 /*******************************************************/
4326 int av_read_play(AVFormatContext *s)
4328 if (s->iformat->read_play)
4329 return s->iformat->read_play(s);
4331 return avio_pause(s->pb, 0);
4332 return AVERROR(ENOSYS);
4335 int av_read_pause(AVFormatContext *s)
4337 if (s->iformat->read_pause)
4338 return s->iformat->read_pause(s);
4340 return avio_pause(s->pb, 1);
4341 return AVERROR(ENOSYS);
4344 int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
4349 dst->time_base = src->time_base;
4350 dst->nb_frames = src->nb_frames;
4351 dst->disposition = src->disposition;
4352 dst->sample_aspect_ratio = src->sample_aspect_ratio;
4353 dst->avg_frame_rate = src->avg_frame_rate;
4354 dst->r_frame_rate = src->r_frame_rate;
4356 av_dict_free(&dst->metadata);
4357 ret = av_dict_copy(&dst->metadata, src->metadata, 0);
4361 ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
4365 /* Free existing side data*/
4366 for (i = 0; i < dst->nb_side_data; i++)
4367 av_free(dst->side_data[i].data);
4368 av_freep(&dst->side_data);
4369 dst->nb_side_data = 0;
4371 /* Copy side data if present */
4372 if (src->nb_side_data) {
4373 dst->side_data = av_mallocz_array(src->nb_side_data,
4374 sizeof(AVPacketSideData));
4375 if (!dst->side_data)
4376 return AVERROR(ENOMEM);
4377 dst->nb_side_data = src->nb_side_data;
4379 for (i = 0; i < src->nb_side_data; i++) {
4380 uint8_t *data = av_memdup(src->side_data[i].data,
4381 src->side_data[i].size);
4383 return AVERROR(ENOMEM);
4384 dst->side_data[i].type = src->side_data[i].type;
4385 dst->side_data[i].size = src->side_data[i].size;
4386 dst->side_data[i].data = data;
4393 static void free_stream(AVStream **pst)
4395 AVStream *st = *pst;
4401 for (i = 0; i < st->nb_side_data; i++)
4402 av_freep(&st->side_data[i].data);
4403 av_freep(&st->side_data);
4406 av_parser_close(st->parser);
4408 if (st->attached_pic.data)
4409 av_packet_unref(&st->attached_pic);
4412 avcodec_free_context(&st->internal->avctx);
4413 av_bsf_free(&st->internal->bsfc);
4414 av_freep(&st->internal->priv_pts);
4415 av_freep(&st->internal->index_entries);
4416 av_freep(&st->internal->probe_data.buf);
4418 av_bsf_free(&st->internal->extract_extradata.bsf);
4420 if (st->internal->info)
4421 av_freep(&st->internal->info->duration_error);
4422 av_freep(&st->internal->info);
4424 av_freep(&st->internal);
4426 av_dict_free(&st->metadata);
4427 avcodec_parameters_free(&st->codecpar);
4428 #if FF_API_LAVF_AVCTX
4429 FF_DISABLE_DEPRECATION_WARNINGS
4430 avcodec_free_context(&st->codec);
4431 FF_ENABLE_DEPRECATION_WARNINGS
4433 av_freep(&st->priv_data);
4438 void ff_free_stream(AVFormatContext *s, AVStream *st)
4440 av_assert0(s->nb_streams>0);
4441 av_assert0(s->streams[ s->nb_streams - 1 ] == st);
4443 free_stream(&s->streams[ --s->nb_streams ]);
4446 void avformat_free_context(AVFormatContext *s)
4453 if (s->oformat && s->oformat->deinit && s->internal->initialized)
4454 s->oformat->deinit(s);
4457 if (s->iformat && s->iformat->priv_class && s->priv_data)
4458 av_opt_free(s->priv_data);
4459 if (s->oformat && s->oformat->priv_class && s->priv_data)
4460 av_opt_free(s->priv_data);
4462 for (i = 0; i < s->nb_streams; i++)
4463 free_stream(&s->streams[i]);
4466 for (i = 0; i < s->nb_programs; i++) {
4467 av_dict_free(&s->programs[i]->metadata);
4468 av_freep(&s->programs[i]->stream_index);
4469 av_freep(&s->programs[i]);
4473 av_freep(&s->programs);
4474 av_freep(&s->priv_data);
4475 while (s->nb_chapters--) {
4476 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4477 av_freep(&s->chapters[s->nb_chapters]);
4479 av_freep(&s->chapters);
4480 av_dict_free(&s->metadata);
4481 av_dict_free(&s->internal->id3v2_meta);
4482 av_packet_free(&s->internal->pkt);
4483 av_packet_free(&s->internal->parse_pkt);
4484 av_freep(&s->streams);
4485 flush_packet_queue(s);
4486 av_freep(&s->internal);
4491 void avformat_close_input(AVFormatContext **ps)
4502 if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4503 (s->flags & AVFMT_FLAG_CUSTOM_IO))
4506 flush_packet_queue(s);
4509 if (s->iformat->read_close)
4510 s->iformat->read_close(s);
4512 avformat_free_context(s);
4519 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4525 if (s->nb_streams >= s->max_streams) {
4526 av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter"
4527 " (%d), see the documentation if you wish to increase it\n",
4531 streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4534 s->streams = streams;
4536 st = av_mallocz(sizeof(AVStream));
4540 #if FF_API_LAVF_AVCTX
4541 FF_DISABLE_DEPRECATION_WARNINGS
4542 st->codec = avcodec_alloc_context3(c);
4547 FF_ENABLE_DEPRECATION_WARNINGS
4550 st->internal = av_mallocz(sizeof(*st->internal));
4554 st->internal->info = av_mallocz(sizeof(*st->internal->info));
4555 if (!st->internal->info)
4557 st->internal->info->last_dts = AV_NOPTS_VALUE;
4559 st->codecpar = avcodec_parameters_alloc();
4563 st->internal->avctx = avcodec_alloc_context3(NULL);
4564 if (!st->internal->avctx)
4568 #if FF_API_LAVF_AVCTX
4569 FF_DISABLE_DEPRECATION_WARNINGS
4570 /* no default bitrate if decoding */
4571 st->codec->bit_rate = 0;
4572 FF_ENABLE_DEPRECATION_WARNINGS
4575 /* default pts setting is MPEG-like */
4576 avpriv_set_pts_info(st, 33, 1, 90000);
4577 /* we set the current DTS to 0 so that formats without any timestamps
4578 * but durations get some timestamps, formats with some unknown
4579 * timestamps have their first few packets buffered and the
4580 * timestamps corrected before they are returned to the user */
4581 st->cur_dts = RELATIVE_TS_BASE;
4583 st->cur_dts = AV_NOPTS_VALUE;
4586 st->index = s->nb_streams;
4587 st->start_time = AV_NOPTS_VALUE;
4588 st->duration = AV_NOPTS_VALUE;
4589 st->first_dts = AV_NOPTS_VALUE;
4590 st->probe_packets = s->max_probe_packets;
4591 st->internal->pts_wrap_reference = AV_NOPTS_VALUE;
4592 st->internal->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4594 st->last_IP_pts = AV_NOPTS_VALUE;
4595 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
4596 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
4597 st->internal->pts_buffer[i] = AV_NOPTS_VALUE;
4599 st->sample_aspect_ratio = (AVRational) { 0, 1 };
4601 #if FF_API_R_FRAME_RATE
4602 st->internal->info->last_dts = AV_NOPTS_VALUE;
4604 st->internal->info->fps_first_dts = AV_NOPTS_VALUE;
4605 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
4607 st->internal->inject_global_side_data = s->internal->inject_global_side_data;
4609 st->internal->need_context_update = 1;
4611 s->streams[s->nb_streams++] = st;
4618 AVProgram *av_new_program(AVFormatContext *ac, int id)
4620 AVProgram *program = NULL;
4623 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4625 for (i = 0; i < ac->nb_programs; i++)
4626 if (ac->programs[i]->id == id)
4627 program = ac->programs[i];
4630 program = av_mallocz(sizeof(AVProgram));
4633 ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
4638 program->discard = AVDISCARD_NONE;
4639 program->pmt_version = -1;
4641 program->pts_wrap_reference = AV_NOPTS_VALUE;
4642 program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4643 program->start_time =
4644 program->end_time = AV_NOPTS_VALUE;
4649 #if FF_API_CHAPTER_ID_INT
4650 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
4652 AVChapter *avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base,
4654 int64_t start, int64_t end, const char *title)
4656 AVChapter *chapter = NULL;
4659 if (end != AV_NOPTS_VALUE && start > end) {
4660 av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
4664 if (!s->nb_chapters) {
4665 s->internal->chapter_ids_monotonic = 1;
4666 } else if (!s->internal->chapter_ids_monotonic || s->chapters[s->nb_chapters-1]->id >= id) {
4667 s->internal->chapter_ids_monotonic = 0;
4668 for (i = 0; i < s->nb_chapters; i++)
4669 if (s->chapters[i]->id == id)
4670 chapter = s->chapters[i];
4674 chapter = av_mallocz(sizeof(AVChapter));
4677 ret = av_dynarray_add_nofree(&s->chapters, &s->nb_chapters, chapter);
4683 av_dict_set(&chapter->metadata, "title", title, 0);
4685 chapter->time_base = time_base;
4686 chapter->start = start;
4692 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4695 AVProgram *program = NULL;
4698 if (idx >= ac->nb_streams) {
4699 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
4703 for (i = 0; i < ac->nb_programs; i++) {
4704 if (ac->programs[i]->id != progid)
4706 program = ac->programs[i];
4707 for (j = 0; j < program->nb_stream_indexes; j++)
4708 if (program->stream_index[j] == idx)
4711 tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4714 program->stream_index = tmp;
4715 program->stream_index[program->nb_stream_indexes++] = idx;
4720 uint64_t ff_ntp_time(void)
4722 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4725 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
4727 uint64_t ntp_ts, frac_part, sec;
4730 //current ntp time in seconds and micro seconds
4731 sec = ntp_time_us / 1000000;
4732 usec = ntp_time_us % 1000000;
4734 //encoding in ntp timestamp format
4735 frac_part = usec * 0xFFFFFFFFULL;
4736 frac_part /= 1000000;
4738 if (sec > 0xFFFFFFFFULL)
4739 av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");
4742 ntp_ts |= frac_part;
4747 uint64_t ff_parse_ntp_time(uint64_t ntp_ts)
4749 uint64_t sec = ntp_ts >> 32;
4750 uint64_t frac_part = ntp_ts & 0xFFFFFFFFULL;
4751 uint64_t usec = (frac_part * 1000000) / 0xFFFFFFFFULL;
4753 return (sec * 1000000) + usec;
4756 int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4759 char *q, buf1[20], c;
4760 int nd, len, percentd_found;
4772 while (av_isdigit(*p)) {
4773 if (nd >= INT_MAX / 10 - 255)
4775 nd = nd * 10 + *p++ - '0';
4778 } while (av_isdigit(c));
4784 if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4789 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
4791 if ((q - buf + len) > buf_size - 1)
4793 memcpy(q, buf1, len);
4801 if ((q - buf) < buf_size - 1)
4805 if (!percentd_found)
4814 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
4816 return av_get_frame_filename2(buf, buf_size, path, number, 0);
4819 void av_url_split(char *proto, int proto_size,
4820 char *authorization, int authorization_size,
4821 char *hostname, int hostname_size,
4822 int *port_ptr, char *path, int path_size, const char *url)
4824 const char *p, *ls, *at, *at2, *col, *brk;
4830 if (authorization_size > 0)
4831 authorization[0] = 0;
4832 if (hostname_size > 0)
4837 /* parse protocol */
4838 if ((p = strchr(url, ':'))) {
4839 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
4846 /* no protocol means plain filename */
4847 av_strlcpy(path, url, path_size);
4851 /* separate path from hostname */
4852 ls = p + strcspn(p, "/?#");
4853 av_strlcpy(path, ls, path_size);
4855 /* the rest is hostname, use that to parse auth/port */
4857 /* authorization (user[:pass]@hostname) */
4859 while ((at = strchr(p, '@')) && at < ls) {
4860 av_strlcpy(authorization, at2,
4861 FFMIN(authorization_size, at + 1 - at2));
4862 p = at + 1; /* skip '@' */
4865 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4867 av_strlcpy(hostname, p + 1,
4868 FFMIN(hostname_size, brk - p));
4869 if (brk[1] == ':' && port_ptr)
4870 *port_ptr = atoi(brk + 2);
4871 } else if ((col = strchr(p, ':')) && col < ls) {
4872 av_strlcpy(hostname, p,
4873 FFMIN(col + 1 - p, hostname_size));
4875 *port_ptr = atoi(col + 1);
4877 av_strlcpy(hostname, p,
4878 FFMIN(ls + 1 - p, hostname_size));
4882 int ff_mkdir_p(const char *path)
4885 char *temp = av_strdup(path);
4889 if (!path || !temp) {
4893 if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
4895 } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
4899 for ( ; *pos != '\0'; ++pos) {
4900 if (*pos == '/' || *pos == '\\') {
4903 ret = mkdir(temp, 0755);
4908 if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
4909 ret = mkdir(temp, 0755);
4916 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4919 static const char hex_table_uc[16] = { '0', '1', '2', '3',
4922 'C', 'D', 'E', 'F' };
4923 static const char hex_table_lc[16] = { '0', '1', '2', '3',
4926 'c', 'd', 'e', 'f' };
4927 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4929 for (i = 0; i < s; i++) {
4930 buff[i * 2] = hex_table[src[i] >> 4];
4931 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4937 int ff_hex_to_data(uint8_t *data, const char *p)
4944 p += strspn(p, SPACE_CHARS);
4947 c = av_toupper((unsigned char) *p++);
4948 if (c >= '0' && c <= '9')
4950 else if (c >= 'A' && c <= 'F')
4965 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4966 unsigned int pts_num, unsigned int pts_den)
4969 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4970 if (new_tb.num != pts_num)
4971 av_log(NULL, AV_LOG_DEBUG,
4972 "st:%d removing common factor %d from timebase\n",
4973 s->index, pts_num / new_tb.num);
4975 av_log(NULL, AV_LOG_WARNING,
4976 "st:%d has too large timebase, reducing\n", s->index);
4978 if (new_tb.num <= 0 || new_tb.den <= 0) {
4979 av_log(NULL, AV_LOG_ERROR,
4980 "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4981 new_tb.num, new_tb.den,
4985 s->time_base = new_tb;
4986 #if FF_API_LAVF_AVCTX
4987 FF_DISABLE_DEPRECATION_WARNINGS
4988 s->codec->pkt_timebase = new_tb;
4989 FF_ENABLE_DEPRECATION_WARNINGS
4991 s->internal->avctx->pkt_timebase = new_tb;
4992 s->pts_wrap_bits = pts_wrap_bits;
4995 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4998 const char *ptr = str;
5000 /* Parse key=value pairs. */
5003 char *dest = NULL, *dest_end;
5004 int key_len, dest_len = 0;
5006 /* Skip whitespace and potential commas. */
5007 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
5014 if (!(ptr = strchr(key, '=')))
5017 key_len = ptr - key;
5019 callback_get_buf(context, key, key_len, &dest, &dest_len);
5020 dest_end = dest + dest_len - 1;
5024 while (*ptr && *ptr != '\"') {
5028 if (dest && dest < dest_end)
5032 if (dest && dest < dest_end)
5040 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
5041 if (dest && dest < dest_end)
5049 int ff_find_stream_index(AVFormatContext *s, int id)
5052 for (i = 0; i < s->nb_streams; i++)
5053 if (s->streams[i]->id == id)
5058 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
5062 unsigned int codec_tag;
5063 if (ofmt->query_codec)
5064 return ofmt->query_codec(codec_id, std_compliance);
5065 else if (ofmt->codec_tag)
5066 return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
5067 else if (codec_id == ofmt->video_codec ||
5068 codec_id == ofmt->audio_codec ||
5069 codec_id == ofmt->subtitle_codec ||
5070 codec_id == ofmt->data_codec)
5073 return AVERROR_PATCHWELCOME;
5076 int avformat_network_init(void)
5080 if ((ret = ff_network_init()) < 0)
5082 if ((ret = ff_tls_init()) < 0)
5088 int avformat_network_deinit(void)
5097 int ff_add_param_change(AVPacket *pkt, int32_t channels,
5098 uint64_t channel_layout, int32_t sample_rate,
5099 int32_t width, int32_t height)
5105 return AVERROR(EINVAL);
5108 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
5110 if (channel_layout) {
5112 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
5116 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
5118 if (width || height) {
5120 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
5122 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
5124 return AVERROR(ENOMEM);
5125 bytestream_put_le32(&data, flags);
5127 bytestream_put_le32(&data, channels);
5129 bytestream_put_le64(&data, channel_layout);
5131 bytestream_put_le32(&data, sample_rate);
5132 if (width || height) {
5133 bytestream_put_le32(&data, width);
5134 bytestream_put_le32(&data, height);
5139 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
5141 AVRational undef = {0, 1};
5142 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
5143 AVRational codec_sample_aspect_ratio = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5144 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
5146 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
5147 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
5148 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
5149 stream_sample_aspect_ratio = undef;
5151 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
5152 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
5153 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
5154 frame_sample_aspect_ratio = undef;
5156 if (stream_sample_aspect_ratio.num)
5157 return stream_sample_aspect_ratio;
5159 return frame_sample_aspect_ratio;
5162 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
5164 AVRational fr = st->r_frame_rate;
5165 AVRational codec_fr = st->internal->avctx->framerate;
5166 AVRational avg_fr = st->avg_frame_rate;
5168 if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
5169 av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
5174 if (st->internal->avctx->ticks_per_frame > 1) {
5175 if ( codec_fr.num > 0 && codec_fr.den > 0 &&
5176 (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))
5184 * Matches a stream specifier (but ignores requested index).
5186 * @param indexptr set to point to the requested stream index if there is one
5188 * @return <0 on error
5189 * 0 if st is NOT a matching stream
5190 * >0 if st is a matching stream
5192 static int match_stream_specifier(AVFormatContext *s, AVStream *st,
5193 const char *spec, const char **indexptr, AVProgram **p)
5195 int match = 1; /* Stores if the specifier matches so far. */
5197 if (*spec <= '9' && *spec >= '0') { /* opt:index */
5201 } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
5202 *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5203 enum AVMediaType type;
5207 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
5208 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
5209 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
5210 case 'd': type = AVMEDIA_TYPE_DATA; break;
5211 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
5212 case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5213 default: av_assert0(0);
5215 if (*spec && *spec++ != ':') /* If we are not at the end, then another specifier must follow. */
5216 return AVERROR(EINVAL);
5218 #if FF_API_LAVF_AVCTX
5219 FF_DISABLE_DEPRECATION_WARNINGS
5220 if (type != st->codecpar->codec_type
5221 && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
5223 FF_ENABLE_DEPRECATION_WARNINGS
5225 if (type != st->codecpar->codec_type)
5228 if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
5230 } else if (*spec == 'p' && *(spec + 1) == ':') {
5235 prog_id = strtol(spec, &endptr, 0);
5236 /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
5237 if (spec == endptr || (*endptr && *endptr++ != ':'))
5238 return AVERROR(EINVAL);
5241 for (i = 0; i < s->nb_programs; i++) {
5242 if (s->programs[i]->id != prog_id)
5245 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
5246 if (st->index == s->programs[i]->stream_index[j]) {
5249 *p = s->programs[i];
5258 } else if (*spec == '#' ||
5259 (*spec == 'i' && *(spec + 1) == ':')) {
5262 spec += 1 + (*spec == 'i');
5263 stream_id = strtol(spec, &endptr, 0);
5264 if (spec == endptr || *endptr) /* Disallow empty id and make sure we are at the end. */
5265 return AVERROR(EINVAL);
5266 return match && (stream_id == st->id);
5267 } else if (*spec == 'm' && *(spec + 1) == ':') {
5268 AVDictionaryEntry *tag;
5274 val = strchr(spec, ':');
5276 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
5278 return AVERROR(ENOMEM);
5280 tag = av_dict_get(st->metadata, key, NULL, 0);
5282 if (!val || !strcmp(tag->value, val + 1))
5291 return match && ret;
5292 } else if (*spec == 'u' && *(spec + 1) == '\0') {
5293 AVCodecParameters *par = st->codecpar;
5294 #if FF_API_LAVF_AVCTX
5295 FF_DISABLE_DEPRECATION_WARNINGS
5296 AVCodecContext *codec = st->codec;
5297 FF_ENABLE_DEPRECATION_WARNINGS
5300 switch (par->codec_type) {
5301 case AVMEDIA_TYPE_AUDIO:
5302 val = par->sample_rate && par->channels;
5303 #if FF_API_LAVF_AVCTX
5304 val = val || (codec->sample_rate && codec->channels);
5306 if (par->format == AV_SAMPLE_FMT_NONE
5307 #if FF_API_LAVF_AVCTX
5308 && codec->sample_fmt == AV_SAMPLE_FMT_NONE
5313 case AVMEDIA_TYPE_VIDEO:
5314 val = par->width && par->height;
5315 #if FF_API_LAVF_AVCTX
5316 val = val || (codec->width && codec->height);
5318 if (par->format == AV_PIX_FMT_NONE
5319 #if FF_API_LAVF_AVCTX
5320 && codec->pix_fmt == AV_PIX_FMT_NONE
5325 case AVMEDIA_TYPE_UNKNOWN:
5332 #if FF_API_LAVF_AVCTX
5333 return match && ((par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0);
5335 return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
5338 return AVERROR(EINVAL);
5346 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
5351 const char *indexptr = NULL;
5352 AVProgram *p = NULL;
5355 ret = match_stream_specifier(s, st, spec, &indexptr, &p);
5362 index = strtol(indexptr, &endptr, 0);
5363 if (*endptr) { /* We can't have anything after the requested index. */
5364 ret = AVERROR(EINVAL);
5368 /* This is not really needed but saves us a loop for simple stream index specifiers. */
5369 if (spec == indexptr)
5370 return (index == st->index);
5372 /* If we requested a matching stream index, we have to ensure st is that. */
5373 nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
5374 for (int i = 0; i < nb_streams && index >= 0; i++) {
5375 AVStream *candidate = p ? s->streams[p->stream_index[i]] : s->streams[i];
5376 ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
5379 if (ret > 0 && index-- == 0 && st == candidate)
5385 if (ret == AVERROR(EINVAL))
5386 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
5390 int ff_generate_avci_extradata(AVStream *st)
5392 static const uint8_t avci100_1080p_extradata[] = {
5394 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5395 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5396 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5397 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
5398 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
5399 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
5400 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
5401 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
5402 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
5404 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5407 static const uint8_t avci100_1080i_extradata[] = {
5409 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5410 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5411 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5412 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
5413 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
5414 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
5415 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
5416 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
5417 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
5418 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
5419 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5421 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5424 static const uint8_t avci50_1080p_extradata[] = {
5426 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5427 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5428 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5429 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5430 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5431 0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
5432 0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
5433 0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
5434 0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
5436 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5439 static const uint8_t avci50_1080i_extradata[] = {
5441 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5442 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5443 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5444 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
5445 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
5446 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
5447 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
5448 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
5449 0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
5450 0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5451 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
5453 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5456 static const uint8_t avci100_720p_extradata[] = {
5458 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5459 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
5460 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
5461 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
5462 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
5463 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
5464 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
5465 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
5466 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
5467 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
5469 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
5472 static const uint8_t avci50_720p_extradata[] = {
5474 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
5475 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5476 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5477 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5478 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5479 0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
5480 0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
5481 0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
5482 0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
5484 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5488 const uint8_t *data = NULL;
5491 if (st->codecpar->width == 1920) {
5492 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5493 data = avci100_1080p_extradata;
5494 size = sizeof(avci100_1080p_extradata);
5496 data = avci100_1080i_extradata;
5497 size = sizeof(avci100_1080i_extradata);
5499 } else if (st->codecpar->width == 1440) {
5500 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5501 data = avci50_1080p_extradata;
5502 size = sizeof(avci50_1080p_extradata);
5504 data = avci50_1080i_extradata;
5505 size = sizeof(avci50_1080i_extradata);
5507 } else if (st->codecpar->width == 1280) {
5508 data = avci100_720p_extradata;
5509 size = sizeof(avci100_720p_extradata);
5510 } else if (st->codecpar->width == 960) {
5511 data = avci50_720p_extradata;
5512 size = sizeof(avci50_720p_extradata);
5518 if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
5520 memcpy(st->codecpar->extradata, data, size);
5525 uint8_t *av_stream_get_side_data(const AVStream *st,
5526 enum AVPacketSideDataType type, buffer_size_t *size)
5530 for (i = 0; i < st->nb_side_data; i++) {
5531 if (st->side_data[i].type == type) {
5533 *size = st->side_data[i].size;
5534 return st->side_data[i].data;
5542 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
5543 uint8_t *data, size_t size)
5545 AVPacketSideData *sd, *tmp;
5548 for (i = 0; i < st->nb_side_data; i++) {
5549 sd = &st->side_data[i];
5551 if (sd->type == type) {
5552 av_freep(&sd->data);
5559 if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
5560 return AVERROR(ERANGE);
5562 tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5564 return AVERROR(ENOMEM);
5567 st->side_data = tmp;
5570 sd = &st->side_data[st->nb_side_data - 1];
5578 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
5582 uint8_t *data = av_malloc(size);
5587 ret = av_stream_add_side_data(st, type, data, size);
5596 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
5599 const AVBitStreamFilter *bsf;
5602 av_assert0(!st->internal->bsfc);
5604 if (!(bsf = av_bsf_get_by_name(name))) {
5605 av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5606 return AVERROR_BSF_NOT_FOUND;
5609 if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
5612 bsfc->time_base_in = st->time_base;
5613 if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
5618 if (args && bsfc->filter->priv_class) {
5619 const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
5620 const char * shorthand[2] = {NULL};
5623 shorthand[0] = opt->name;
5625 if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
5631 if ((ret = av_bsf_init(bsfc)) < 0) {
5636 st->internal->bsfc = bsfc;
5638 av_log(NULL, AV_LOG_VERBOSE,
5639 "Automatically inserted bitstream filter '%s'; args='%s'\n",
5640 name, args ? args : "");
5644 int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
5647 return AVERROR(EINVAL);
5649 if (!(s->oformat->flags & AVFMT_NOFILE))
5650 return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
5654 void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
5657 s->io_close(s, *pb);
5661 int ff_is_http_proto(char *filename) {
5662 const char *proto = avio_find_protocol_name(filename);
5663 return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
5666 int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
5668 AVDictionaryEntry *entry;
5669 int64_t parsed_timestamp;
5671 if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
5672 if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
5673 *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
5676 av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
5683 int ff_standardize_creation_time(AVFormatContext *s)
5686 int ret = ff_parse_creation_time_metadata(s, ×tamp, 0);
5688 return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5692 int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5697 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
5699 if (size != AVPALETTE_SIZE) {
5700 av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
5701 return AVERROR_INVALIDDATA;
5703 memcpy(palette, side_data, AVPALETTE_SIZE);
5707 if (ret == CONTAINS_PAL) {
5709 for (i = 0; i < AVPALETTE_COUNT; i++)
5710 palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
5717 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
5722 ret = av_bprint_finalize(buf, &str);
5725 if (!av_bprint_is_complete(buf)) {
5727 return AVERROR(ENOMEM);
5730 par->extradata = str;
5731 /* Note: the string is NUL terminated (so extradata can be read as a
5732 * string), but the ending character is not accounted in the size (in
5733 * binary formats you are likely not supposed to mux that character). When
5734 * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
5736 par->extradata_size = buf->len;
5740 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
5741 AVStream *ost, const AVStream *ist,
5742 enum AVTimebaseSource copy_tb)
5744 //TODO: use [io]st->internal->avctx
5745 const AVCodecContext *dec_ctx;
5746 AVCodecContext *enc_ctx;
5748 #if FF_API_LAVF_AVCTX
5749 FF_DISABLE_DEPRECATION_WARNINGS
5750 dec_ctx = ist->codec;
5751 enc_ctx = ost->codec;
5752 FF_ENABLE_DEPRECATION_WARNINGS
5754 dec_ctx = ist->internal->avctx;
5755 enc_ctx = ost->internal->avctx;
5758 enc_ctx->time_base = ist->time_base;
5760 * Avi is a special case here because it supports variable fps but
5761 * having the fps and timebase differe significantly adds quite some
5764 if (!strcmp(ofmt->name, "avi")) {
5765 #if FF_API_R_FRAME_RATE
5766 if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
5767 && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
5768 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
5769 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
5770 && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
5771 || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
5772 enc_ctx->time_base.num = ist->r_frame_rate.den;
5773 enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
5774 enc_ctx->ticks_per_frame = 2;
5777 if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
5778 && av_q2d(ist->time_base) < 1.0/500
5779 || copy_tb == AVFMT_TBCF_DECODER) {
5780 enc_ctx->time_base = dec_ctx->time_base;
5781 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5782 enc_ctx->time_base.den *= 2;
5783 enc_ctx->ticks_per_frame = 2;
5785 } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5786 && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5787 if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
5788 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
5789 && av_q2d(ist->time_base) < 1.0/500
5790 || copy_tb == AVFMT_TBCF_DECODER) {
5791 enc_ctx->time_base = dec_ctx->time_base;
5792 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5796 if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5797 && dec_ctx->time_base.num < dec_ctx->time_base.den
5798 && dec_ctx->time_base.num > 0
5799 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
5800 enc_ctx->time_base = dec_ctx->time_base;
5803 av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
5804 enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
5809 AVRational av_stream_get_codec_timebase(const AVStream *st)
5811 // See avformat_transfer_internal_stream_timing_info() TODO.
5812 #if FF_API_LAVF_AVCTX
5813 FF_DISABLE_DEPRECATION_WARNINGS
5814 return st->codec->time_base;
5815 FF_ENABLE_DEPRECATION_WARNINGS
5817 return st->internal->avctx->time_base;
5821 void ff_format_set_url(AVFormatContext *s, char *url)
5826 #if FF_API_FORMAT_FILENAME
5827 FF_DISABLE_DEPRECATION_WARNINGS
5828 av_strlcpy(s->filename, url, sizeof(s->filename));
5829 FF_ENABLE_DEPRECATION_WARNINGS