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)
127 int64_t av_stream_get_end_pts(const AVStream *st)
129 if (st->internal->priv_pts) {
130 return st->internal->priv_pts->val;
132 return AV_NOPTS_VALUE;
135 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
140 void av_format_inject_global_side_data(AVFormatContext *s)
143 s->internal->inject_global_side_data = 1;
144 for (i = 0; i < s->nb_streams; i++) {
145 AVStream *st = s->streams[i];
146 st->internal->inject_global_side_data = 1;
150 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
152 av_assert0(!dst->codec_whitelist &&
153 !dst->format_whitelist &&
154 !dst->protocol_whitelist &&
155 !dst->protocol_blacklist);
156 dst-> codec_whitelist = av_strdup(src->codec_whitelist);
157 dst->format_whitelist = av_strdup(src->format_whitelist);
158 dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
159 dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
160 if ( (src-> codec_whitelist && !dst-> codec_whitelist)
161 || (src-> format_whitelist && !dst-> format_whitelist)
162 || (src->protocol_whitelist && !dst->protocol_whitelist)
163 || (src->protocol_blacklist && !dst->protocol_blacklist)) {
164 av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
165 return AVERROR(ENOMEM);
170 static const AVCodec *find_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
172 #if FF_API_LAVF_AVCTX
173 FF_DISABLE_DEPRECATION_WARNINGS
174 if (st->codec->codec)
175 return st->codec->codec;
176 FF_ENABLE_DEPRECATION_WARNINGS
179 switch (st->codecpar->codec_type) {
180 case AVMEDIA_TYPE_VIDEO:
181 if (s->video_codec) return s->video_codec;
183 case AVMEDIA_TYPE_AUDIO:
184 if (s->audio_codec) return s->audio_codec;
186 case AVMEDIA_TYPE_SUBTITLE:
187 if (s->subtitle_codec) return s->subtitle_codec;
191 return avcodec_find_decoder(codec_id);
194 static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
196 const AVCodec *codec;
198 #if CONFIG_H264_DECODER
199 /* Other parts of the code assume this decoder to be used for h264,
200 * so force it if possible. */
201 if (codec_id == AV_CODEC_ID_H264)
202 return avcodec_find_decoder_by_name("h264");
205 codec = find_decoder(s, st, codec_id);
209 if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
210 const AVCodec *probe_codec = NULL;
212 while ((probe_codec = av_codec_iterate(&iter))) {
213 if (probe_codec->id == codec->id &&
214 av_codec_is_decoder(probe_codec) &&
215 !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
224 #if FF_API_FORMAT_GET_SET
225 int av_format_get_probe_score(const AVFormatContext *s)
227 return s->probe_score;
231 /* an arbitrarily chosen "sane" max packet size -- 50M */
232 #define SANE_CHUNK_SIZE (50000000)
234 int ffio_limit(AVIOContext *s, int size)
236 if (s->maxsize>= 0) {
237 int64_t pos = avio_tell(s);
238 int64_t remaining= s->maxsize - pos;
239 if (remaining < size) {
240 int64_t newsize = avio_size(s);
241 if (!s->maxsize || s->maxsize<newsize)
242 s->maxsize = newsize - !newsize;
243 if (pos > s->maxsize && s->maxsize >= 0)
244 s->maxsize = AVERROR(EIO);
246 remaining = s->maxsize - pos;
249 if (s->maxsize >= 0 && remaining < size && size > 1) {
250 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG,
251 "Truncating packet of size %d to %"PRId64"\n",
252 size, remaining + !remaining);
253 size = remaining + !remaining;
259 /* Read the data in sane-sized chunks and append to pkt.
260 * Return the number of bytes read or an error. */
261 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
263 int orig_size = pkt->size;
267 int prev_size = pkt->size;
270 /* When the caller requests a lot of data, limit it to the amount
271 * left in file or SANE_CHUNK_SIZE when it is not known. */
273 if (read_size > SANE_CHUNK_SIZE/10) {
274 read_size = ffio_limit(s, read_size);
275 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
277 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
280 ret = av_grow_packet(pkt, read_size);
284 ret = avio_read(s, pkt->data + prev_size, read_size);
285 if (ret != read_size) {
286 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
293 pkt->flags |= AV_PKT_FLAG_CORRUPT;
296 av_packet_unref(pkt);
297 return pkt->size > orig_size ? pkt->size - orig_size : ret;
300 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
302 #if FF_API_INIT_PACKET
303 FF_DISABLE_DEPRECATION_WARNINGS
307 FF_ENABLE_DEPRECATION_WARNINGS
309 av_packet_unref(pkt);
311 pkt->pos = avio_tell(s);
313 return append_packet_chunked(s, pkt, size);
316 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
319 return av_get_packet(s, pkt, size);
320 return append_packet_chunked(s, pkt, size);
323 int av_filename_number_test(const char *filename)
327 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
330 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
333 static const struct {
336 enum AVMediaType type;
338 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
339 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
340 { "aptx", AV_CODEC_ID_APTX, AVMEDIA_TYPE_AUDIO },
341 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
342 { "dvbsub", AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
343 { "dvbtxt", AV_CODEC_ID_DVB_TELETEXT,AVMEDIA_TYPE_SUBTITLE },
344 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
345 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
346 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
347 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
348 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
349 { "mjpeg_2000",AV_CODEC_ID_JPEG2000, AVMEDIA_TYPE_VIDEO },
350 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
351 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
352 { "truehd", AV_CODEC_ID_TRUEHD, AVMEDIA_TYPE_AUDIO },
356 const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
360 av_log(s, AV_LOG_DEBUG,
361 "Probe with size=%d, packets=%d detected %s with score=%d\n",
362 pd->buf_size, s->max_probe_packets - st->probe_packets,
364 for (i = 0; fmt_id_type[i].name; i++) {
365 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
366 if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
367 st->codecpar->sample_rate)
369 if (st->internal->request_probe > score &&
370 st->codecpar->codec_id != fmt_id_type[i].id)
372 st->codecpar->codec_id = fmt_id_type[i].id;
373 st->codecpar->codec_type = fmt_id_type[i].type;
374 st->internal->need_context_update = 1;
375 #if FF_API_LAVF_AVCTX
376 FF_DISABLE_DEPRECATION_WARNINGS
377 st->codec->codec_type = st->codecpar->codec_type;
378 st->codec->codec_id = st->codecpar->codec_id;
379 FF_ENABLE_DEPRECATION_WARNINGS
388 /************************************************************/
389 /* input media file */
391 #if FF_API_DEMUXER_OPEN
392 int av_demuxer_open(AVFormatContext *ic) {
395 if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
396 av_log(ic, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", ic->format_whitelist);
397 return AVERROR(EINVAL);
400 if (ic->iformat->read_header) {
401 err = ic->iformat->read_header(ic);
406 if (ic->pb && !ic->internal->data_offset)
407 ic->internal->data_offset = avio_tell(ic->pb);
412 /* Open input file and probe the format if necessary. */
413 static int init_input(AVFormatContext *s, const char *filename,
414 AVDictionary **options)
417 AVProbeData pd = { filename, NULL, 0 };
418 int score = AVPROBE_SCORE_RETRY;
421 s->flags |= AVFMT_FLAG_CUSTOM_IO;
423 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
424 s, 0, s->format_probesize);
425 else if (s->iformat->flags & AVFMT_NOFILE)
426 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
427 "will be ignored with AVFMT_NOFILE format.\n");
431 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
432 (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
435 if ((ret = s->io_open(s, &s->pb, filename, AVIO_FLAG_READ | s->avio_flags, options)) < 0)
440 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
441 s, 0, s->format_probesize);
444 int avformat_queue_attached_pictures(AVFormatContext *s)
447 for (i = 0; i < s->nb_streams; i++)
448 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
449 s->streams[i]->discard < AVDISCARD_ALL) {
450 if (s->streams[i]->attached_pic.size <= 0) {
451 av_log(s, AV_LOG_WARNING,
452 "Attached picture on stream %d has invalid size, "
457 ret = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
458 &s->internal->raw_packet_buffer_end,
459 &s->streams[i]->attached_pic,
467 int ff_add_attached_pic(AVFormatContext *s, AVStream *st0, AVIOContext *pb,
468 AVBufferRef **buf, int size)
474 if (!st && !(st = avformat_new_stream(s, NULL)))
475 return AVERROR(ENOMEM);
476 pkt = &st->attached_pic;
479 av_packet_unref(pkt);
481 pkt->data = (*buf)->data;
482 pkt->size = (*buf)->size - AV_INPUT_BUFFER_PADDING_SIZE;
485 ret = av_get_packet(pb, pkt, size);
489 st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
490 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
492 pkt->stream_index = st->index;
493 pkt->flags |= AV_PKT_FLAG_KEY;
498 ff_free_stream(s, st);
502 static int update_stream_avctx(AVFormatContext *s)
505 for (i = 0; i < s->nb_streams; i++) {
506 AVStream *st = s->streams[i];
508 if (!st->internal->need_context_update)
511 /* close parser, because it depends on the codec */
512 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
513 av_parser_close(st->parser);
517 /* update internal codec context, for the parser */
518 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
522 #if FF_API_LAVF_AVCTX
523 FF_DISABLE_DEPRECATION_WARNINGS
524 /* update deprecated public codec context */
525 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
528 FF_ENABLE_DEPRECATION_WARNINGS
531 st->internal->need_context_update = 0;
537 int avformat_open_input(AVFormatContext **ps, const char *filename,
538 const AVInputFormat *fmt, AVDictionary **options)
540 AVFormatContext *s = *ps;
542 AVDictionary *tmp = NULL;
543 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
545 if (!s && !(s = avformat_alloc_context()))
546 return AVERROR(ENOMEM);
548 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
549 return AVERROR(EINVAL);
555 av_dict_copy(&tmp, *options, 0);
557 if (s->pb) // must be before any goto fail
558 s->flags |= AVFMT_FLAG_CUSTOM_IO;
560 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
563 if (!(s->url = av_strdup(filename ? filename : ""))) {
564 ret = AVERROR(ENOMEM);
568 #if FF_API_FORMAT_FILENAME
569 FF_DISABLE_DEPRECATION_WARNINGS
570 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
571 FF_ENABLE_DEPRECATION_WARNINGS
573 if ((ret = init_input(s, filename, &tmp)) < 0)
575 s->probe_score = ret;
577 if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
578 s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
579 if (!s->protocol_whitelist) {
580 ret = AVERROR(ENOMEM);
585 if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
586 s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
587 if (!s->protocol_blacklist) {
588 ret = AVERROR(ENOMEM);
593 if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
594 av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
595 ret = AVERROR(EINVAL);
599 avio_skip(s->pb, s->skip_initial_bytes);
601 /* Check filename in case an image number is expected. */
602 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
603 if (!av_filename_number_test(filename)) {
604 ret = AVERROR(EINVAL);
609 s->duration = s->start_time = AV_NOPTS_VALUE;
611 /* Allocate private data. */
612 if (s->iformat->priv_data_size > 0) {
613 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
614 ret = AVERROR(ENOMEM);
617 if (s->iformat->priv_class) {
618 *(const AVClass **) s->priv_data = s->iformat->priv_class;
619 av_opt_set_defaults(s->priv_data);
620 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
625 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
627 ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
629 #if FF_API_DEMUXER_OPEN
630 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
632 if (s->iformat->read_header)
634 if ((ret = s->iformat->read_header(s)) < 0)
638 s->metadata = s->internal->id3v2_meta;
639 s->internal->id3v2_meta = NULL;
640 } else if (s->internal->id3v2_meta) {
641 av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
642 av_dict_free(&s->internal->id3v2_meta);
645 if (id3v2_extra_meta) {
646 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
647 !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
648 if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
650 if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
652 if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
655 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
657 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
659 if ((ret = avformat_queue_attached_pictures(s)) < 0)
662 #if FF_API_DEMUXER_OPEN
663 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
665 if (s->pb && !s->internal->data_offset)
667 s->internal->data_offset = avio_tell(s->pb);
669 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
671 update_stream_avctx(s);
673 for (i = 0; i < s->nb_streams; i++)
674 s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
677 av_dict_free(options);
684 if (s->iformat->read_close)
685 s->iformat->read_close(s);
687 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
689 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
691 avformat_free_context(s);
696 /*******************************************************/
698 static void force_codec_ids(AVFormatContext *s, AVStream *st)
700 switch (st->codecpar->codec_type) {
701 case AVMEDIA_TYPE_VIDEO:
702 if (s->video_codec_id)
703 st->codecpar->codec_id = s->video_codec_id;
705 case AVMEDIA_TYPE_AUDIO:
706 if (s->audio_codec_id)
707 st->codecpar->codec_id = s->audio_codec_id;
709 case AVMEDIA_TYPE_SUBTITLE:
710 if (s->subtitle_codec_id)
711 st->codecpar->codec_id = s->subtitle_codec_id;
713 case AVMEDIA_TYPE_DATA:
714 if (s->data_codec_id)
715 st->codecpar->codec_id = s->data_codec_id;
720 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
722 if (st->internal->request_probe>0) {
723 AVProbeData *pd = &st->internal->probe_data;
725 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
729 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
731 av_log(s, AV_LOG_WARNING,
732 "Failed to reallocate probe buffer for stream %d\n",
737 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
738 pd->buf_size += pkt->size;
739 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
742 st->probe_packets = 0;
744 av_log(s, AV_LOG_WARNING,
745 "nothing to probe for stream %d\n", st->index);
749 end= s->internal->raw_packet_buffer_remaining_size <= 0
750 || st->probe_packets<= 0;
752 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
753 int score = set_codec_from_probe_data(s, st, pd);
754 if ( (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
758 st->internal->request_probe = -1;
759 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
760 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
762 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
764 force_codec_ids(s, st);
770 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
772 int64_t ref = pkt->dts;
773 int i, pts_wrap_behavior;
774 int64_t pts_wrap_reference;
775 AVProgram *first_program;
777 if (ref == AV_NOPTS_VALUE)
779 if (st->internal->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
781 ref &= (1LL << st->pts_wrap_bits)-1;
783 // reference time stamp should be 60 s before first time stamp
784 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
785 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
786 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
787 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
788 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
790 first_program = av_find_program_from_stream(s, NULL, stream_index);
792 if (!first_program) {
793 int default_stream_index = av_find_default_stream_index(s);
794 if (s->streams[default_stream_index]->internal->pts_wrap_reference == AV_NOPTS_VALUE) {
795 for (i = 0; i < s->nb_streams; i++) {
796 if (av_find_program_from_stream(s, NULL, i))
798 s->streams[i]->internal->pts_wrap_reference = pts_wrap_reference;
799 s->streams[i]->internal->pts_wrap_behavior = pts_wrap_behavior;
803 st->internal->pts_wrap_reference = s->streams[default_stream_index]->internal->pts_wrap_reference;
804 st->internal->pts_wrap_behavior = s->streams[default_stream_index]->internal->pts_wrap_behavior;
808 AVProgram *program = first_program;
810 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
811 pts_wrap_reference = program->pts_wrap_reference;
812 pts_wrap_behavior = program->pts_wrap_behavior;
815 program = av_find_program_from_stream(s, program, stream_index);
818 // update every program with differing pts_wrap_reference
819 program = first_program;
821 if (program->pts_wrap_reference != pts_wrap_reference) {
822 for (i = 0; i<program->nb_stream_indexes; i++) {
823 s->streams[program->stream_index[i]]->internal->pts_wrap_reference = pts_wrap_reference;
824 s->streams[program->stream_index[i]]->internal->pts_wrap_behavior = pts_wrap_behavior;
827 program->pts_wrap_reference = pts_wrap_reference;
828 program->pts_wrap_behavior = pts_wrap_behavior;
830 program = av_find_program_from_stream(s, program, stream_index);
836 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
841 #if FF_API_INIT_PACKET
842 FF_DISABLE_DEPRECATION_WARNINGS
846 FF_ENABLE_DEPRECATION_WARNINGS
848 av_packet_unref(pkt);
852 PacketList *pktl = s->internal->raw_packet_buffer;
853 const AVPacket *pkt1;
856 st = s->streams[pktl->pkt.stream_index];
857 if (s->internal->raw_packet_buffer_remaining_size <= 0)
858 if ((err = probe_codec(s, st, NULL)) < 0)
860 if (st->internal->request_probe <= 0) {
861 avpriv_packet_list_get(&s->internal->raw_packet_buffer,
862 &s->internal->raw_packet_buffer_end, pkt);
863 s->internal->raw_packet_buffer_remaining_size += pkt->size;
868 err = s->iformat->read_packet(s, pkt);
870 av_packet_unref(pkt);
872 /* Some demuxers return FFERROR_REDO when they consume
873 data and discard it (ignored streams, junk, extradata).
874 We must re-call the demuxer to get the real packet. */
875 if (err == FFERROR_REDO)
877 if (!pktl || err == AVERROR(EAGAIN))
879 for (i = 0; i < s->nb_streams; i++) {
881 if (st->probe_packets || st->internal->request_probe > 0)
882 if ((err = probe_codec(s, st, NULL)) < 0)
884 av_assert0(st->internal->request_probe <= 0);
889 err = av_packet_make_refcounted(pkt);
891 av_packet_unref(pkt);
895 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
896 av_log(s, AV_LOG_WARNING,
897 "Packet corrupt (stream = %d, dts = %s)",
898 pkt->stream_index, av_ts2str(pkt->dts));
899 if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
900 av_log(s, AV_LOG_WARNING, ", dropping it.\n");
901 av_packet_unref(pkt);
904 av_log(s, AV_LOG_WARNING, ".\n");
907 av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
908 "Invalid stream index.\n");
910 st = s->streams[pkt->stream_index];
912 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
913 // correct first time stamps to negative values
914 if (!is_relative(st->first_dts))
915 st->first_dts = wrap_timestamp(st, st->first_dts);
916 if (!is_relative(st->start_time))
917 st->start_time = wrap_timestamp(st, st->start_time);
918 if (!is_relative(st->cur_dts))
919 st->cur_dts = wrap_timestamp(st, st->cur_dts);
922 pkt->dts = wrap_timestamp(st, pkt->dts);
923 pkt->pts = wrap_timestamp(st, pkt->pts);
925 force_codec_ids(s, st);
927 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
928 if (s->use_wallclock_as_timestamps)
929 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
931 if (!pktl && st->internal->request_probe <= 0)
934 err = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
935 &s->internal->raw_packet_buffer_end,
938 av_packet_unref(pkt);
941 pkt1 = &s->internal->raw_packet_buffer_end->pkt;
942 s->internal->raw_packet_buffer_remaining_size -= pkt1->size;
944 if ((err = probe_codec(s, st, pkt1)) < 0)
950 /**********************************************************/
952 static int determinable_frame_size(AVCodecContext *avctx)
954 switch(avctx->codec_id) {
955 case AV_CODEC_ID_MP1:
956 case AV_CODEC_ID_MP2:
957 case AV_CODEC_ID_MP3:
958 case AV_CODEC_ID_CODEC2:
966 * Return the frame duration in seconds. Return 0 if not available.
968 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
969 AVCodecParserContext *pc, AVPacket *pkt)
971 AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
972 av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
973 int frame_size, sample_rate;
975 #if FF_API_LAVF_AVCTX
976 FF_DISABLE_DEPRECATION_WARNINGS
977 if ((!codec_framerate.den || !codec_framerate.num) && st->codec->time_base.den && st->codec->time_base.num)
978 codec_framerate = av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
979 FF_ENABLE_DEPRECATION_WARNINGS
984 switch (st->codecpar->codec_type) {
985 case AVMEDIA_TYPE_VIDEO:
986 if (st->r_frame_rate.num && !pc && s->iformat) {
987 *pnum = st->r_frame_rate.den;
988 *pden = st->r_frame_rate.num;
989 } else if (st->time_base.num * 1000LL > st->time_base.den) {
990 *pnum = st->time_base.num;
991 *pden = st->time_base.den;
992 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
993 av_assert0(st->internal->avctx->ticks_per_frame);
994 av_reduce(pnum, pden,
996 codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
999 if (pc && pc->repeat_pict) {
1000 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
1001 av_reduce(pnum, pden,
1002 (*pnum) * (1LL + pc->repeat_pict),
1006 /* If this codec can be interlaced or progressive then we need
1007 * a parser to compute duration of a packet. Thus if we have
1008 * no parser in such case leave duration undefined. */
1009 if (st->internal->avctx->ticks_per_frame > 1 && !pc)
1013 case AVMEDIA_TYPE_AUDIO:
1014 if (st->internal->avctx_inited) {
1015 frame_size = av_get_audio_frame_duration(st->internal->avctx, pkt->size);
1016 sample_rate = st->internal->avctx->sample_rate;
1018 frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
1019 sample_rate = st->codecpar->sample_rate;
1021 if (frame_size <= 0 || sample_rate <= 0)
1024 *pden = sample_rate;
1031 int ff_is_intra_only(enum AVCodecID id)
1033 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
1036 if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
1037 !(d->props & AV_CODEC_PROP_INTRA_ONLY))
1042 static int has_decode_delay_been_guessed(AVStream *st)
1044 if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
1045 if (!st->internal->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
1047 #if CONFIG_H264_DECODER
1048 if (st->internal->avctx->has_b_frames &&
1049 avpriv_h264_has_num_reorder_frames(st->internal->avctx) == st->internal->avctx->has_b_frames)
1052 if (st->internal->avctx->has_b_frames<3)
1053 return st->internal->nb_decoded_frames >= 7;
1054 else if (st->internal->avctx->has_b_frames<4)
1055 return st->internal->nb_decoded_frames >= 18;
1057 return st->internal->nb_decoded_frames >= 20;
1060 static PacketList *get_next_pkt(AVFormatContext *s, AVStream *st, PacketList *pktl)
1064 if (pktl == s->internal->packet_buffer_end)
1065 return s->internal->parse_queue;
1069 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
1070 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1071 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1074 int delay = st->internal->avctx->has_b_frames;
1077 if (dts == AV_NOPTS_VALUE) {
1078 int64_t best_score = INT64_MAX;
1079 for (i = 0; i<delay; i++) {
1080 if (st->internal->pts_reorder_error_count[i]) {
1081 int64_t score = st->internal->pts_reorder_error[i] / st->internal->pts_reorder_error_count[i];
1082 if (score < best_score) {
1084 dts = pts_buffer[i];
1089 for (i = 0; i<delay; i++) {
1090 if (pts_buffer[i] != AV_NOPTS_VALUE) {
1091 int64_t diff = FFABS(pts_buffer[i] - dts)
1092 + (uint64_t)st->internal->pts_reorder_error[i];
1093 diff = FFMAX(diff, st->internal->pts_reorder_error[i]);
1094 st->internal->pts_reorder_error[i] = diff;
1095 st->internal->pts_reorder_error_count[i]++;
1096 if (st->internal->pts_reorder_error_count[i] > 250) {
1097 st->internal->pts_reorder_error[i] >>= 1;
1098 st->internal->pts_reorder_error_count[i] >>= 1;
1105 if (dts == AV_NOPTS_VALUE)
1106 dts = pts_buffer[0];
1112 * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
1113 * of the packets in a window.
1115 static void update_dts_from_pts(AVFormatContext *s, int stream_index,
1116 PacketList *pkt_buffer)
1118 AVStream *st = s->streams[stream_index];
1119 int delay = st->internal->avctx->has_b_frames;
1122 int64_t pts_buffer[MAX_REORDER_DELAY+1];
1124 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1125 pts_buffer[i] = AV_NOPTS_VALUE;
1127 for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
1128 if (pkt_buffer->pkt.stream_index != stream_index)
1131 if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1132 pts_buffer[0] = pkt_buffer->pkt.pts;
1133 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1134 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1136 pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
1141 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1142 int64_t dts, int64_t pts, AVPacket *pkt)
1144 AVStream *st = s->streams[stream_index];
1145 PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1146 PacketList *pktl_it;
1150 if (st->first_dts != AV_NOPTS_VALUE ||
1151 dts == AV_NOPTS_VALUE ||
1152 st->cur_dts == AV_NOPTS_VALUE ||
1153 st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1154 dts < INT_MIN + (st->cur_dts - RELATIVE_TS_BASE) ||
1158 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1160 shift = (uint64_t)st->first_dts - RELATIVE_TS_BASE;
1162 if (is_relative(pts))
1165 for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
1166 if (pktl_it->pkt.stream_index != stream_index)
1168 if (is_relative(pktl_it->pkt.pts))
1169 pktl_it->pkt.pts += shift;
1171 if (is_relative(pktl_it->pkt.dts))
1172 pktl_it->pkt.dts += shift;
1174 if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1175 st->start_time = pktl_it->pkt.pts;
1176 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1177 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));
1181 if (has_decode_delay_been_guessed(st)) {
1182 update_dts_from_pts(s, stream_index, pktl);
1185 if (st->start_time == AV_NOPTS_VALUE) {
1186 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
1187 st->start_time = pts;
1189 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1190 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));
1194 static void update_initial_durations(AVFormatContext *s, AVStream *st,
1195 int stream_index, int64_t duration)
1197 PacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1198 int64_t cur_dts = RELATIVE_TS_BASE;
1200 if (st->first_dts != AV_NOPTS_VALUE) {
1201 if (st->internal->update_initial_durations_done)
1203 st->internal->update_initial_durations_done = 1;
1204 cur_dts = st->first_dts;
1205 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1206 if (pktl->pkt.stream_index == stream_index) {
1207 if (pktl->pkt.pts != pktl->pkt.dts ||
1208 pktl->pkt.dts != AV_NOPTS_VALUE ||
1211 cur_dts -= duration;
1214 if (pktl && pktl->pkt.dts != st->first_dts) {
1215 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1216 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1220 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1223 pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1224 st->first_dts = cur_dts;
1225 } else if (st->cur_dts != RELATIVE_TS_BASE)
1228 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1229 if (pktl->pkt.stream_index != stream_index)
1231 if ((pktl->pkt.pts == pktl->pkt.dts ||
1232 pktl->pkt.pts == AV_NOPTS_VALUE) &&
1233 (pktl->pkt.dts == AV_NOPTS_VALUE ||
1234 pktl->pkt.dts == st->first_dts ||
1235 pktl->pkt.dts == RELATIVE_TS_BASE) &&
1236 !pktl->pkt.duration) {
1237 pktl->pkt.dts = cur_dts;
1238 if (!st->internal->avctx->has_b_frames)
1239 pktl->pkt.pts = cur_dts;
1240 pktl->pkt.duration = duration;
1243 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1246 st->cur_dts = cur_dts;
1249 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1250 AVCodecParserContext *pc, AVPacket *pkt,
1251 int64_t next_dts, int64_t next_pts)
1253 int num, den, presentation_delayed, delay, i;
1255 AVRational duration;
1256 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1257 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1259 if (s->flags & AVFMT_FLAG_NOFILLIN)
1262 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1263 if (pkt->dts == pkt->pts && st->internal->last_dts_for_order_check != AV_NOPTS_VALUE) {
1264 if (st->internal->last_dts_for_order_check <= pkt->dts) {
1265 st->internal->dts_ordered++;
1267 av_log(s, st->internal->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1268 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1270 st->internal->last_dts_for_order_check);
1271 st->internal->dts_misordered++;
1273 if (st->internal->dts_ordered + st->internal->dts_misordered > 250) {
1274 st->internal->dts_ordered >>= 1;
1275 st->internal->dts_misordered >>= 1;
1279 st->internal->last_dts_for_order_check = pkt->dts;
1280 if (st->internal->dts_ordered < 8*st->internal->dts_misordered && pkt->dts == pkt->pts)
1281 pkt->dts = AV_NOPTS_VALUE;
1284 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1285 pkt->dts = AV_NOPTS_VALUE;
1287 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1288 && !st->internal->avctx->has_b_frames)
1289 //FIXME Set low_delay = 0 when has_b_frames = 1
1290 st->internal->avctx->has_b_frames = 1;
1292 /* do we have a video B-frame ? */
1293 delay = st->internal->avctx->has_b_frames;
1294 presentation_delayed = 0;
1296 /* XXX: need has_b_frame, but cannot get it if the codec is
1297 * not initialized */
1299 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1300 presentation_delayed = 1;
1302 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1303 st->pts_wrap_bits < 63 && pkt->dts > INT64_MIN + (1LL << st->pts_wrap_bits) &&
1304 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1305 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1306 pkt->dts -= 1LL << st->pts_wrap_bits;
1308 pkt->pts += 1LL << st->pts_wrap_bits;
1311 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1312 * We take the conservative approach and discard both.
1313 * Note: If this is misbehaving for an H.264 file, then possibly
1314 * presentation_delayed is not set correctly. */
1315 if (delay == 1 && pkt->dts == pkt->pts &&
1316 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1317 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1318 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1319 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1320 pkt->dts = AV_NOPTS_VALUE;
1323 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1324 if (pkt->duration <= 0) {
1325 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1327 duration = (AVRational) {num, den};
1328 pkt->duration = av_rescale_rnd(1,
1329 num * (int64_t) st->time_base.den,
1330 den * (int64_t) st->time_base.num,
1335 if (pkt->duration > 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1336 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1338 /* Correct timestamps with byte offset if demuxers only have timestamps
1339 * on packet boundaries */
1340 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1341 /* this will estimate bitrate based on this frame's duration and size */
1342 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1343 if (pkt->pts != AV_NOPTS_VALUE)
1345 if (pkt->dts != AV_NOPTS_VALUE)
1349 /* This may be redundant, but it should not hurt. */
1350 if (pkt->dts != AV_NOPTS_VALUE &&
1351 pkt->pts != AV_NOPTS_VALUE &&
1352 pkt->pts > pkt->dts)
1353 presentation_delayed = 1;
1355 if (s->debug & FF_FDEBUG_TS)
1356 av_log(s, AV_LOG_DEBUG,
1357 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1358 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1359 pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1361 /* Interpolate PTS and DTS if they are not present. We skip H264
1362 * currently because delay and has_b_frames are not reliably set. */
1363 if ((delay == 0 || (delay == 1 && pc)) &&
1365 if (presentation_delayed) {
1366 /* DTS = decompression timestamp */
1367 /* PTS = presentation timestamp */
1368 if (pkt->dts == AV_NOPTS_VALUE)
1369 pkt->dts = st->last_IP_pts;
1370 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1371 if (pkt->dts == AV_NOPTS_VALUE)
1372 pkt->dts = st->cur_dts;
1374 /* This is tricky: the dts must be incremented by the duration
1375 * of the frame we are displaying, i.e. the last I- or P-frame. */
1376 if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1377 st->last_IP_duration = pkt->duration;
1378 if (pkt->dts != AV_NOPTS_VALUE)
1379 st->cur_dts = av_sat_add64(pkt->dts, st->last_IP_duration);
1380 if (pkt->dts != AV_NOPTS_VALUE &&
1381 pkt->pts == AV_NOPTS_VALUE &&
1382 st->last_IP_duration > 0 &&
1383 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1384 next_dts != next_pts &&
1385 next_pts != AV_NOPTS_VALUE)
1386 pkt->pts = next_dts;
1388 if ((uint64_t)pkt->duration <= INT32_MAX)
1389 st->last_IP_duration = pkt->duration;
1390 st->last_IP_pts = pkt->pts;
1391 /* Cannot compute PTS if not present (we can compute it only
1392 * by knowing the future. */
1393 } else if (pkt->pts != AV_NOPTS_VALUE ||
1394 pkt->dts != AV_NOPTS_VALUE ||
1395 pkt->duration > 0 ) {
1397 /* presentation is not delayed : PTS and DTS are the same */
1398 if (pkt->pts == AV_NOPTS_VALUE)
1399 pkt->pts = pkt->dts;
1400 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1402 if (pkt->pts == AV_NOPTS_VALUE)
1403 pkt->pts = st->cur_dts;
1404 pkt->dts = pkt->pts;
1405 if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1406 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1410 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1411 st->internal->pts_buffer[0] = pkt->pts;
1412 for (i = 0; i<delay && st->internal->pts_buffer[i] > st->internal->pts_buffer[i + 1]; i++)
1413 FFSWAP(int64_t, st->internal->pts_buffer[i], st->internal->pts_buffer[i + 1]);
1415 if(has_decode_delay_been_guessed(st))
1416 pkt->dts = select_from_pts_buffer(st, st->internal->pts_buffer, pkt->dts);
1418 // We skipped it above so we try here.
1420 // This should happen on the first packet
1421 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1422 if (pkt->dts > st->cur_dts)
1423 st->cur_dts = pkt->dts;
1425 if (s->debug & FF_FDEBUG_TS)
1426 av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1427 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), st->index, st->id);
1430 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || ff_is_intra_only(st->codecpar->codec_id))
1431 pkt->flags |= AV_PKT_FLAG_KEY;
1435 * Parse a packet, add all split parts to parse_queue.
1437 * @param pkt Packet to parse; must not be NULL.
1438 * @param flush Indicates whether to flush. If set, pkt must be blank.
1440 static int parse_packet(AVFormatContext *s, AVPacket *pkt,
1441 int stream_index, int flush)
1443 AVPacket *out_pkt = s->internal->parse_pkt;
1444 AVStream *st = s->streams[stream_index];
1445 uint8_t *data = pkt->data;
1446 int size = pkt->size;
1447 int ret = 0, got_output = flush;
1449 if (!size && !flush && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1450 // preserve 0-size sync packets
1451 compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1454 while (size > 0 || (flush && got_output)) {
1456 int64_t next_pts = pkt->pts;
1457 int64_t next_dts = pkt->dts;
1459 len = av_parser_parse2(st->parser, st->internal->avctx,
1460 &out_pkt->data, &out_pkt->size, data, size,
1461 pkt->pts, pkt->dts, pkt->pos);
1463 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1465 /* increment read pointer */
1466 av_assert1(data || !len);
1467 data = len ? data + len : data;
1470 got_output = !!out_pkt->size;
1475 if (pkt->buf && out_pkt->data == pkt->data) {
1476 /* reference pkt->buf only when out_pkt->data is guaranteed to point
1477 * to data in it and not in the parser's internal buffer. */
1478 /* XXX: Ensure this is the case with all parsers when st->parser->flags
1479 * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1480 out_pkt->buf = av_buffer_ref(pkt->buf);
1481 if (!out_pkt->buf) {
1482 ret = AVERROR(ENOMEM);
1486 ret = av_packet_make_refcounted(out_pkt);
1491 if (pkt->side_data) {
1492 out_pkt->side_data = pkt->side_data;
1493 out_pkt->side_data_elems = pkt->side_data_elems;
1494 pkt->side_data = NULL;
1495 pkt->side_data_elems = 0;
1498 /* set the duration */
1499 out_pkt->duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1500 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1501 if (st->internal->avctx->sample_rate > 0) {
1503 av_rescale_q_rnd(st->parser->duration,
1504 (AVRational) { 1, st->internal->avctx->sample_rate },
1510 out_pkt->stream_index = st->index;
1511 out_pkt->pts = st->parser->pts;
1512 out_pkt->dts = st->parser->dts;
1513 out_pkt->pos = st->parser->pos;
1514 out_pkt->flags |= pkt->flags & AV_PKT_FLAG_DISCARD;
1516 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1517 out_pkt->pos = st->parser->frame_offset;
1519 if (st->parser->key_frame == 1 ||
1520 (st->parser->key_frame == -1 &&
1521 st->parser->pict_type == AV_PICTURE_TYPE_I))
1522 out_pkt->flags |= AV_PKT_FLAG_KEY;
1524 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1525 out_pkt->flags |= AV_PKT_FLAG_KEY;
1527 compute_pkt_fields(s, st, st->parser, out_pkt, next_dts, next_pts);
1529 ret = avpriv_packet_list_put(&s->internal->parse_queue,
1530 &s->internal->parse_queue_end,
1536 /* end of the stream => close and free the parser */
1538 av_parser_close(st->parser);
1544 av_packet_unref(out_pkt);
1545 av_packet_unref(pkt);
1549 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1551 return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1554 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1556 int ret, i, got_packet = 0;
1557 AVDictionary *metadata = NULL;
1559 while (!got_packet && !s->internal->parse_queue) {
1562 /* read next packet */
1563 ret = ff_read_packet(s, pkt);
1565 if (ret == AVERROR(EAGAIN))
1567 /* flush the parsers */
1568 for (i = 0; i < s->nb_streams; i++) {
1570 if (st->parser && st->need_parsing)
1571 parse_packet(s, pkt, st->index, 1);
1573 /* all remaining packets are now in parse_queue =>
1574 * really terminate parsing */
1578 st = s->streams[pkt->stream_index];
1580 st->event_flags |= AVSTREAM_EVENT_FLAG_NEW_PACKETS;
1582 /* update context if required */
1583 if (st->internal->need_context_update) {
1584 if (avcodec_is_open(st->internal->avctx)) {
1585 av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1586 avcodec_close(st->internal->avctx);
1587 st->internal->info->found_decoder = 0;
1590 /* close parser, because it depends on the codec */
1591 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
1592 av_parser_close(st->parser);
1596 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
1598 av_packet_unref(pkt);
1602 #if FF_API_LAVF_AVCTX
1603 FF_DISABLE_DEPRECATION_WARNINGS
1604 /* update deprecated public codec context */
1605 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
1607 av_packet_unref(pkt);
1610 FF_ENABLE_DEPRECATION_WARNINGS
1613 st->internal->need_context_update = 0;
1616 if (pkt->pts != AV_NOPTS_VALUE &&
1617 pkt->dts != AV_NOPTS_VALUE &&
1618 pkt->pts < pkt->dts) {
1619 av_log(s, AV_LOG_WARNING,
1620 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1622 av_ts2str(pkt->pts),
1623 av_ts2str(pkt->dts),
1626 if (s->debug & FF_FDEBUG_TS)
1627 av_log(s, AV_LOG_DEBUG,
1628 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1630 av_ts2str(pkt->pts),
1631 av_ts2str(pkt->dts),
1632 pkt->size, pkt->duration, pkt->flags);
1634 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1635 st->parser = av_parser_init(st->codecpar->codec_id);
1637 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1638 "%s, packets or times may be invalid.\n",
1639 avcodec_get_name(st->codecpar->codec_id));
1640 /* no parser available: just output the raw packets */
1641 st->need_parsing = AVSTREAM_PARSE_NONE;
1642 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1643 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1644 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1645 st->parser->flags |= PARSER_FLAG_ONCE;
1646 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1647 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1650 if (!st->need_parsing || !st->parser) {
1651 /* no parsing needed: we just output the packet as is */
1652 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1653 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1654 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1655 ff_reduce_index(s, st->index);
1656 av_add_index_entry(st, pkt->pos, pkt->dts,
1657 0, 0, AVINDEX_KEYFRAME);
1660 } else if (st->discard < AVDISCARD_ALL) {
1661 if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1663 st->codecpar->sample_rate = st->internal->avctx->sample_rate;
1664 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
1665 st->codecpar->channels = st->internal->avctx->channels;
1666 st->codecpar->channel_layout = st->internal->avctx->channel_layout;
1667 st->codecpar->codec_id = st->internal->avctx->codec_id;
1670 av_packet_unref(pkt);
1672 if (pkt->flags & AV_PKT_FLAG_KEY)
1673 st->internal->skip_to_keyframe = 0;
1674 if (st->internal->skip_to_keyframe) {
1675 av_packet_unref(pkt);
1680 if (!got_packet && s->internal->parse_queue)
1681 ret = avpriv_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1684 AVStream *st = s->streams[pkt->stream_index];
1685 int discard_padding = 0;
1686 if (st->internal->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1687 int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1688 int64_t sample = ts_to_samples(st, pts);
1689 int duration = ts_to_samples(st, pkt->duration);
1690 int64_t end_sample = sample + duration;
1691 if (duration > 0 && end_sample >= st->internal->first_discard_sample &&
1692 sample < st->internal->last_discard_sample)
1693 discard_padding = FFMIN(end_sample - st->internal->first_discard_sample, duration);
1695 if (st->internal->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1696 st->internal->skip_samples = st->internal->start_skip_samples;
1697 if (st->internal->skip_samples || discard_padding) {
1698 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1700 AV_WL32(p, st->internal->skip_samples);
1701 AV_WL32(p + 4, discard_padding);
1702 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->internal->skip_samples, discard_padding);
1704 st->internal->skip_samples = 0;
1707 if (st->internal->inject_global_side_data) {
1708 for (i = 0; i < st->nb_side_data; i++) {
1709 AVPacketSideData *src_sd = &st->side_data[i];
1712 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1715 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1717 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1721 memcpy(dst_data, src_sd->data, src_sd->size);
1723 st->internal->inject_global_side_data = 0;
1727 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1729 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1730 av_dict_copy(&s->metadata, metadata, 0);
1731 av_dict_free(&metadata);
1732 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1735 #if FF_API_LAVF_AVCTX
1736 update_stream_avctx(s);
1739 if (s->debug & FF_FDEBUG_TS)
1740 av_log(s, AV_LOG_DEBUG,
1741 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1742 "size=%d, duration=%"PRId64", flags=%d\n",
1744 av_ts2str(pkt->pts),
1745 av_ts2str(pkt->dts),
1746 pkt->size, pkt->duration, pkt->flags);
1748 /* A demuxer might have returned EOF because of an IO error, let's
1749 * propagate this back to the user. */
1750 if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1756 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1758 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1764 ret = s->internal->packet_buffer
1765 ? avpriv_packet_list_get(&s->internal->packet_buffer,
1766 &s->internal->packet_buffer_end, pkt)
1767 : read_frame_internal(s, pkt);
1774 PacketList *pktl = s->internal->packet_buffer;
1777 AVPacket *next_pkt = &pktl->pkt;
1779 if (next_pkt->dts != AV_NOPTS_VALUE) {
1780 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1781 // last dts seen for this stream. if any of packets following
1782 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1783 int64_t last_dts = next_pkt->dts;
1784 av_assert2(wrap_bits <= 64);
1785 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1786 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1787 av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1788 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1790 next_pkt->pts = pktl->pkt.dts;
1792 if (last_dts != AV_NOPTS_VALUE) {
1793 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1794 last_dts = pktl->pkt.dts;
1799 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1800 // Fixing the last reference frame had none pts issue (For MXF etc).
1801 // We only do this when
1803 // 2. we are not able to resolve a pts value for current packet.
1804 // 3. the packets for this stream at the end of the files had valid dts.
1805 next_pkt->pts = last_dts + next_pkt->duration;
1807 pktl = s->internal->packet_buffer;
1810 /* read packet from packet buffer, if there is data */
1811 st = s->streams[next_pkt->stream_index];
1812 if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1813 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1814 ret = avpriv_packet_list_get(&s->internal->packet_buffer,
1815 &s->internal->packet_buffer_end, pkt);
1820 ret = read_frame_internal(s, pkt);
1822 if (pktl && ret != AVERROR(EAGAIN)) {
1829 ret = avpriv_packet_list_put(&s->internal->packet_buffer,
1830 &s->internal->packet_buffer_end,
1833 av_packet_unref(pkt);
1840 st = s->streams[pkt->stream_index];
1841 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1842 ff_reduce_index(s, st->index);
1843 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1846 if (is_relative(pkt->dts))
1847 pkt->dts -= RELATIVE_TS_BASE;
1848 if (is_relative(pkt->pts))
1849 pkt->pts -= RELATIVE_TS_BASE;
1854 /* XXX: suppress the packet queue */
1855 static void flush_packet_queue(AVFormatContext *s)
1859 avpriv_packet_list_free(&s->internal->parse_queue, &s->internal->parse_queue_end);
1860 avpriv_packet_list_free(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1861 avpriv_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1863 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1866 /*******************************************************/
1869 int av_find_default_stream_index(AVFormatContext *s)
1873 int best_stream = 0;
1874 int best_score = INT_MIN;
1876 if (s->nb_streams <= 0)
1878 for (i = 0; i < s->nb_streams; i++) {
1881 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1882 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
1884 if (st->codecpar->width && st->codecpar->height)
1888 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1889 if (st->codecpar->sample_rate)
1892 if (st->codec_info_nb_frames)
1895 if (st->discard != AVDISCARD_ALL)
1898 if (score > best_score) {
1906 /** Flush the frame reader. */
1907 void ff_read_frame_flush(AVFormatContext *s)
1912 flush_packet_queue(s);
1914 /* Reset read state for each stream. */
1915 for (i = 0; i < s->nb_streams; i++) {
1919 av_parser_close(st->parser);
1922 st->last_IP_pts = AV_NOPTS_VALUE;
1923 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
1924 if (st->first_dts == AV_NOPTS_VALUE)
1925 st->cur_dts = RELATIVE_TS_BASE;
1927 /* We set the current DTS to an unspecified origin. */
1928 st->cur_dts = AV_NOPTS_VALUE;
1930 st->probe_packets = s->max_probe_packets;
1932 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1933 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
1935 if (s->internal->inject_global_side_data)
1936 st->internal->inject_global_side_data = 1;
1938 st->internal->skip_samples = 0;
1942 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1946 for (i = 0; i < s->nb_streams; i++) {
1947 AVStream *st = s->streams[i];
1950 av_rescale(timestamp,
1951 st->time_base.den * (int64_t) ref_st->time_base.num,
1952 st->time_base.num * (int64_t) ref_st->time_base.den);
1956 void ff_reduce_index(AVFormatContext *s, int stream_index)
1958 AVStream *st = s->streams[stream_index];
1959 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1961 if ((unsigned) st->internal->nb_index_entries >= max_entries) {
1963 for (i = 0; 2 * i < st->internal->nb_index_entries; i++)
1964 st->internal->index_entries[i] = st->internal->index_entries[2 * i];
1965 st->internal->nb_index_entries = i;
1969 int ff_add_index_entry(AVIndexEntry **index_entries,
1970 int *nb_index_entries,
1971 unsigned int *index_entries_allocated_size,
1972 int64_t pos, int64_t timestamp,
1973 int size, int distance, int flags)
1975 AVIndexEntry *entries, *ie;
1978 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1981 if (timestamp == AV_NOPTS_VALUE)
1982 return AVERROR(EINVAL);
1984 if (size < 0 || size > 0x3FFFFFFF)
1985 return AVERROR(EINVAL);
1987 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1988 timestamp -= RELATIVE_TS_BASE;
1990 entries = av_fast_realloc(*index_entries,
1991 index_entries_allocated_size,
1992 (*nb_index_entries + 1) *
1993 sizeof(AVIndexEntry));
1997 *index_entries = entries;
1999 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
2000 timestamp, AVSEEK_FLAG_ANY);
2003 index = (*nb_index_entries)++;
2004 ie = &entries[index];
2005 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
2007 ie = &entries[index];
2008 if (ie->timestamp != timestamp) {
2009 if (ie->timestamp <= timestamp)
2011 memmove(entries + index + 1, entries + index,
2012 sizeof(AVIndexEntry) * (*nb_index_entries - index));
2013 (*nb_index_entries)++;
2014 } else if (ie->pos == pos && distance < ie->min_distance)
2015 // do not reduce the distance
2016 distance = ie->min_distance;
2020 ie->timestamp = timestamp;
2021 ie->min_distance = distance;
2028 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
2029 int size, int distance, int flags)
2031 timestamp = wrap_timestamp(st, timestamp);
2032 return ff_add_index_entry(&st->internal->index_entries, &st->internal->nb_index_entries,
2033 &st->internal->index_entries_allocated_size, pos,
2034 timestamp, size, distance, flags);
2037 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
2038 int64_t wanted_timestamp, int flags)
2046 // Optimize appending index entries at the end.
2047 if (b && entries[b - 1].timestamp < wanted_timestamp)
2053 // Search for the next non-discarded packet.
2054 while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
2056 if (m == b && entries[m].timestamp >= wanted_timestamp) {
2062 timestamp = entries[m].timestamp;
2063 if (timestamp >= wanted_timestamp)
2065 if (timestamp <= wanted_timestamp)
2068 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
2070 if (!(flags & AVSEEK_FLAG_ANY))
2071 while (m >= 0 && m < nb_entries &&
2072 !(entries[m].flags & AVINDEX_KEYFRAME))
2073 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
2075 if (m == nb_entries)
2080 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
2083 int64_t pos_delta = 0;
2085 //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
2086 const char *proto = avio_find_protocol_name(s->url);
2088 av_assert0(time_tolerance >= 0);
2091 av_log(s, AV_LOG_INFO,
2092 "Protocol name not provided, cannot determine if input is local or "
2093 "a network protocol, buffers and access patterns cannot be configured "
2094 "optimally without knowing the protocol\n");
2097 if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2100 for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
2101 AVStream *st1 = s->streams[ist1];
2102 for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
2103 AVStream *st2 = s->streams[ist2];
2109 for (i1 = i2 = 0; i1 < st1->internal->nb_index_entries; i1++) {
2110 AVIndexEntry *e1 = &st1->internal->index_entries[i1];
2111 int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
2113 skip = FFMAX(skip, e1->size);
2114 for (; i2 < st2->internal->nb_index_entries; i2++) {
2115 AVIndexEntry *e2 = &st2->internal->index_entries[i2];
2116 int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
2117 if (e2_pts < e1_pts || e2_pts - (uint64_t)e1_pts < time_tolerance)
2119 pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
2127 /* XXX This could be adjusted depending on protocol*/
2128 if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
2129 av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
2131 /* realloc the buffer and the original data will be retained */
2132 if (ffio_realloc_buf(s->pb, pos_delta)) {
2133 av_log(s, AV_LOG_ERROR, "Realloc buffer fail.\n");
2137 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
2140 if (skip < (1<<23)) {
2141 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
2145 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2147 return ff_index_search_timestamp(st->internal->index_entries, st->internal->nb_index_entries,
2148 wanted_timestamp, flags);
2151 int avformat_index_get_entries_count(const AVStream *st)
2153 return st->internal->nb_index_entries;
2156 const AVIndexEntry *avformat_index_get_entry(const AVStream *st, int idx)
2158 if (idx < 0 || idx >= st->internal->nb_index_entries)
2161 return &st->internal->index_entries[idx];
2164 const AVIndexEntry *avformat_index_get_entry_from_timestamp(const AVStream *st,
2165 int64_t wanted_timestamp,
2168 int idx = ff_index_search_timestamp(st->internal->index_entries,
2169 st->internal->nb_index_entries,
2170 wanted_timestamp, flags);
2175 return &st->internal->index_entries[idx];
2178 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
2179 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2181 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
2182 if (stream_index >= 0)
2183 ts = wrap_timestamp(s->streams[stream_index], ts);
2187 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
2188 int64_t target_ts, int flags)
2190 const AVInputFormat *avif = s->iformat;
2191 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2192 int64_t ts_min, ts_max, ts;
2197 if (stream_index < 0)
2200 av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2203 ts_min = AV_NOPTS_VALUE;
2204 pos_limit = -1; // GCC falsely says it may be uninitialized.
2206 st = s->streams[stream_index];
2207 if (st->internal->index_entries) {
2210 /* FIXME: Whole function must be checked for non-keyframe entries in
2211 * index case, especially read_timestamp(). */
2212 index = av_index_search_timestamp(st, target_ts,
2213 flags | AVSEEK_FLAG_BACKWARD);
2214 index = FFMAX(index, 0);
2215 e = &st->internal->index_entries[index];
2217 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
2219 ts_min = e->timestamp;
2220 av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2221 pos_min, av_ts2str(ts_min));
2223 av_assert1(index == 0);
2226 index = av_index_search_timestamp(st, target_ts,
2227 flags & ~AVSEEK_FLAG_BACKWARD);
2228 av_assert0(index < st->internal->nb_index_entries);
2230 e = &st->internal->index_entries[index];
2231 av_assert1(e->timestamp >= target_ts);
2233 ts_max = e->timestamp;
2234 pos_limit = pos_max - e->min_distance;
2235 av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2236 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2240 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
2241 ts_min, ts_max, flags, &ts, avif->read_timestamp);
2246 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2249 ff_read_frame_flush(s);
2250 ff_update_cur_dts(s, st, ts);
2255 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
2256 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2258 int64_t step = 1024;
2259 int64_t limit, ts_max;
2260 int64_t filesize = avio_size(s->pb);
2261 int64_t pos_max = filesize - 1;
2264 pos_max = FFMAX(0, (pos_max) - step);
2265 ts_max = ff_read_timestamp(s, stream_index,
2266 &pos_max, limit, read_timestamp);
2268 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2269 if (ts_max == AV_NOPTS_VALUE)
2273 int64_t tmp_pos = pos_max + 1;
2274 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
2275 &tmp_pos, INT64_MAX, read_timestamp);
2276 if (tmp_ts == AV_NOPTS_VALUE)
2278 av_assert0(tmp_pos > pos_max);
2281 if (tmp_pos >= filesize)
2293 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
2294 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
2295 int64_t ts_min, int64_t ts_max,
2296 int flags, int64_t *ts_ret,
2297 int64_t (*read_timestamp)(struct AVFormatContext *, int,
2298 int64_t *, int64_t))
2305 av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2307 if (ts_min == AV_NOPTS_VALUE) {
2308 pos_min = s->internal->data_offset;
2309 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2310 if (ts_min == AV_NOPTS_VALUE)
2314 if (ts_min >= target_ts) {
2319 if (ts_max == AV_NOPTS_VALUE) {
2320 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2322 pos_limit = pos_max;
2325 if (ts_max <= target_ts) {
2330 av_assert0(ts_min < ts_max);
2333 while (pos_min < pos_limit) {
2334 av_log(s, AV_LOG_TRACE,
2335 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2336 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2337 av_assert0(pos_limit <= pos_max);
2339 if (no_change == 0) {
2340 int64_t approximate_keyframe_distance = pos_max - pos_limit;
2341 // interpolate position (better than dichotomy)
2342 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2344 pos_min - approximate_keyframe_distance;
2345 } else if (no_change == 1) {
2346 // bisection if interpolation did not change min / max pos last time
2347 pos = (pos_min + pos_limit) >> 1;
2349 /* linear search if bisection failed, can only happen if there
2350 * are very few or no keyframes between min/max */
2355 else if (pos > pos_limit)
2359 // May pass pos_limit instead of -1.
2360 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2365 av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2366 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2367 pos_min, pos, pos_max,
2368 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2369 pos_limit, start_pos, no_change);
2370 if (ts == AV_NOPTS_VALUE) {
2371 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2374 if (target_ts <= ts) {
2375 pos_limit = start_pos - 1;
2379 if (target_ts >= ts) {
2385 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2386 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2389 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2391 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2392 av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2393 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2399 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2400 int64_t pos, int flags)
2402 int64_t pos_min, pos_max;
2404 pos_min = s->internal->data_offset;
2405 pos_max = avio_size(s->pb) - 1;
2409 else if (pos > pos_max)
2412 avio_seek(s->pb, pos, SEEK_SET);
2414 s->io_repositioned = 1;
2419 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2420 int64_t timestamp, int flags)
2427 st = s->streams[stream_index];
2429 index = av_index_search_timestamp(st, timestamp, flags);
2431 if (index < 0 && st->internal->nb_index_entries &&
2432 timestamp < st->internal->index_entries[0].timestamp)
2435 if (index < 0 || index == st->internal->nb_index_entries - 1) {
2436 AVPacket *pkt = s->internal->pkt;
2439 if (st->internal->nb_index_entries) {
2440 av_assert0(st->internal->index_entries);
2441 ie = &st->internal->index_entries[st->internal->nb_index_entries - 1];
2442 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2444 ff_update_cur_dts(s, st, ie->timestamp);
2446 if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2449 av_packet_unref(pkt);
2453 read_status = av_read_frame(s, pkt);
2454 } while (read_status == AVERROR(EAGAIN));
2455 if (read_status < 0)
2457 if (stream_index == pkt->stream_index && pkt->dts > timestamp) {
2458 if (pkt->flags & AV_PKT_FLAG_KEY) {
2459 av_packet_unref(pkt);
2462 if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2463 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);
2464 av_packet_unref(pkt);
2468 av_packet_unref(pkt);
2470 index = av_index_search_timestamp(st, timestamp, flags);
2475 ff_read_frame_flush(s);
2476 if (s->iformat->read_seek)
2477 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2479 ie = &st->internal->index_entries[index];
2480 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2482 ff_update_cur_dts(s, st, ie->timestamp);
2487 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2488 int64_t timestamp, int flags)
2493 if (flags & AVSEEK_FLAG_BYTE) {
2494 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2496 ff_read_frame_flush(s);
2497 return seek_frame_byte(s, stream_index, timestamp, flags);
2500 if (stream_index < 0) {
2501 stream_index = av_find_default_stream_index(s);
2502 if (stream_index < 0)
2505 st = s->streams[stream_index];
2506 /* timestamp for default must be expressed in AV_TIME_BASE units */
2507 timestamp = av_rescale(timestamp, st->time_base.den,
2508 AV_TIME_BASE * (int64_t) st->time_base.num);
2511 /* first, we try the format specific seek */
2512 if (s->iformat->read_seek) {
2513 ff_read_frame_flush(s);
2514 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2520 if (s->iformat->read_timestamp &&
2521 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2522 ff_read_frame_flush(s);
2523 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2524 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2525 ff_read_frame_flush(s);
2526 return seek_frame_generic(s, stream_index, timestamp, flags);
2531 int av_seek_frame(AVFormatContext *s, int stream_index,
2532 int64_t timestamp, int flags)
2536 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2537 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2538 if ((flags & AVSEEK_FLAG_BACKWARD))
2542 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2543 flags & ~AVSEEK_FLAG_BACKWARD);
2546 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2549 ret = avformat_queue_attached_pictures(s);
2554 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2555 int64_t ts, int64_t max_ts, int flags)
2557 if (min_ts > ts || max_ts < ts)
2559 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2560 return AVERROR(EINVAL);
2563 flags |= AVSEEK_FLAG_ANY;
2564 flags &= ~AVSEEK_FLAG_BACKWARD;
2566 if (s->iformat->read_seek2) {
2568 ff_read_frame_flush(s);
2570 if (stream_index == -1 && s->nb_streams == 1) {
2571 AVRational time_base = s->streams[0]->time_base;
2572 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2573 min_ts = av_rescale_rnd(min_ts, time_base.den,
2574 time_base.num * (int64_t)AV_TIME_BASE,
2575 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2576 max_ts = av_rescale_rnd(max_ts, time_base.den,
2577 time_base.num * (int64_t)AV_TIME_BASE,
2578 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2582 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2586 ret = avformat_queue_attached_pictures(s);
2590 if (s->iformat->read_timestamp) {
2591 // try to seek via read_timestamp()
2594 // Fall back on old API if new is not implemented but old is.
2595 // Note the old API has somewhat different semantics.
2596 if (s->iformat->read_seek || 1) {
2597 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2598 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2599 if (ret<0 && ts != min_ts && max_ts != ts) {
2600 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2602 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2607 // try some generic seek like seek_frame_generic() but with new ts semantics
2608 return -1; //unreachable
2611 int avformat_flush(AVFormatContext *s)
2613 ff_read_frame_flush(s);
2617 /*******************************************************/
2620 * Return TRUE if the stream has accurate duration in any stream.
2622 * @return TRUE if the stream has accurate duration for at least one component.
2624 static int has_duration(AVFormatContext *ic)
2629 for (i = 0; i < ic->nb_streams; i++) {
2630 st = ic->streams[i];
2631 if (st->duration != AV_NOPTS_VALUE)
2634 if (ic->duration != AV_NOPTS_VALUE)
2640 * Estimate the stream timings from the one of each components.
2642 * Also computes the global bitrate if possible.
2644 static void update_stream_timings(AVFormatContext *ic)
2646 int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2647 int64_t duration, duration1, duration_text, filesize;
2651 start_time = INT64_MAX;
2652 start_time_text = INT64_MAX;
2653 end_time = INT64_MIN;
2654 end_time_text = INT64_MIN;
2655 duration = INT64_MIN;
2656 duration_text = INT64_MIN;
2658 for (i = 0; i < ic->nb_streams; i++) {
2659 AVStream *st = ic->streams[i];
2660 int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2661 st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
2662 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2663 start_time1 = av_rescale_q(st->start_time, st->time_base,
2666 start_time_text = FFMIN(start_time_text, start_time1);
2668 start_time = FFMIN(start_time, start_time1);
2669 end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
2671 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
2672 if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2673 end_time1 += start_time1;
2675 end_time_text = FFMAX(end_time_text, end_time1);
2677 end_time = FFMAX(end_time, end_time1);
2679 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2680 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2681 p->start_time = start_time1;
2682 if (p->end_time < end_time1)
2683 p->end_time = end_time1;
2686 if (st->duration != AV_NOPTS_VALUE) {
2687 duration1 = av_rescale_q(st->duration, st->time_base,
2690 duration_text = FFMAX(duration_text, duration1);
2692 duration = FFMAX(duration, duration1);
2695 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2696 start_time = start_time_text;
2697 else if (start_time > start_time_text)
2698 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2700 if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2701 end_time = end_time_text;
2702 else if (end_time < end_time_text)
2703 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
2705 if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
2706 duration = duration_text;
2707 else if (duration < duration_text)
2708 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
2710 if (start_time != INT64_MAX) {
2711 ic->start_time = start_time;
2712 if (end_time != INT64_MIN) {
2713 if (ic->nb_programs > 1) {
2714 for (i = 0; i < ic->nb_programs; i++) {
2715 p = ic->programs[i];
2716 if (p->start_time != AV_NOPTS_VALUE &&
2717 p->end_time > p->start_time &&
2718 p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2719 duration = FFMAX(duration, p->end_time - p->start_time);
2721 } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2722 duration = FFMAX(duration, end_time - start_time);
2726 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2727 ic->duration = duration;
2729 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2730 /* compute the bitrate */
2731 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2732 (double) ic->duration;
2733 if (bitrate >= 0 && bitrate <= INT64_MAX)
2734 ic->bit_rate = bitrate;
2738 static void fill_all_stream_timings(AVFormatContext *ic)
2743 update_stream_timings(ic);
2744 for (i = 0; i < ic->nb_streams; i++) {
2745 st = ic->streams[i];
2746 if (st->start_time == AV_NOPTS_VALUE) {
2747 if (ic->start_time != AV_NOPTS_VALUE)
2748 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2750 if (ic->duration != AV_NOPTS_VALUE)
2751 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2757 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2759 int64_t filesize, duration;
2760 int i, show_warning = 0;
2763 /* if bit_rate is already set, we believe it */
2764 if (ic->bit_rate <= 0) {
2765 int64_t bit_rate = 0;
2766 for (i = 0; i < ic->nb_streams; i++) {
2767 st = ic->streams[i];
2768 if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
2769 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2770 if (st->codecpar->bit_rate > 0) {
2771 if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2775 bit_rate += st->codecpar->bit_rate;
2776 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2777 // If we have a videostream with packets but without a bitrate
2778 // then consider the sum not known
2783 ic->bit_rate = bit_rate;
2786 /* if duration is already set, we believe it */
2787 if (ic->duration == AV_NOPTS_VALUE &&
2788 ic->bit_rate != 0) {
2789 filesize = ic->pb ? avio_size(ic->pb) : 0;
2790 if (filesize > ic->internal->data_offset) {
2791 filesize -= ic->internal->data_offset;
2792 for (i = 0; i < ic->nb_streams; i++) {
2793 st = ic->streams[i];
2794 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2795 && st->duration == AV_NOPTS_VALUE) {
2796 duration = av_rescale(filesize, 8LL * st->time_base.den,
2798 (int64_t) st->time_base.num);
2799 st->duration = duration;
2806 av_log(ic, AV_LOG_WARNING,
2807 "Estimating duration from bitrate, this may be inaccurate\n");
2810 #define DURATION_MAX_READ_SIZE 250000LL
2811 #define DURATION_MAX_RETRY 6
2813 /* only usable for MPEG-PS streams */
2814 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2816 AVPacket *pkt = ic->internal->pkt;
2818 int num, den, read_size, i, ret;
2819 int found_duration = 0;
2821 int64_t filesize, offset, duration;
2824 /* flush packet queue */
2825 flush_packet_queue(ic);
2827 for (i = 0; i < ic->nb_streams; i++) {
2828 st = ic->streams[i];
2829 if (st->start_time == AV_NOPTS_VALUE &&
2830 st->first_dts == AV_NOPTS_VALUE &&
2831 st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
2832 av_log(ic, AV_LOG_WARNING,
2833 "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2836 av_parser_close(st->parser);
2841 if (ic->skip_estimate_duration_from_pts) {
2842 av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
2843 goto skip_duration_calc;
2846 av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2847 /* estimate the end time (duration) */
2848 /* XXX: may need to support wrapping */
2849 filesize = ic->pb ? avio_size(ic->pb) : 0;
2851 is_end = found_duration;
2852 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2856 avio_seek(ic->pb, offset, SEEK_SET);
2859 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2863 ret = ff_read_packet(ic, pkt);
2864 } while (ret == AVERROR(EAGAIN));
2867 read_size += pkt->size;
2868 st = ic->streams[pkt->stream_index];
2869 if (pkt->pts != AV_NOPTS_VALUE &&
2870 (st->start_time != AV_NOPTS_VALUE ||
2871 st->first_dts != AV_NOPTS_VALUE)) {
2872 if (pkt->duration == 0) {
2873 ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2875 pkt->duration = av_rescale_rnd(1,
2876 num * (int64_t) st->time_base.den,
2877 den * (int64_t) st->time_base.num,
2881 duration = pkt->pts + pkt->duration;
2883 if (st->start_time != AV_NOPTS_VALUE)
2884 duration -= st->start_time;
2886 duration -= st->first_dts;
2888 if (st->duration == AV_NOPTS_VALUE || st->internal->info->last_duration<= 0 ||
2889 (st->duration < duration && FFABS(duration - st->internal->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2890 st->duration = duration;
2891 st->internal->info->last_duration = duration;
2894 av_packet_unref(pkt);
2897 /* check if all audio/video streams have valid duration */
2900 for (i = 0; i < ic->nb_streams; i++) {
2901 st = ic->streams[i];
2902 switch (st->codecpar->codec_type) {
2903 case AVMEDIA_TYPE_VIDEO:
2904 case AVMEDIA_TYPE_AUDIO:
2905 if (st->duration == AV_NOPTS_VALUE)
2912 ++retry <= DURATION_MAX_RETRY);
2914 av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2916 /* warn about audio/video streams which duration could not be estimated */
2917 for (i = 0; i < ic->nb_streams; i++) {
2918 st = ic->streams[i];
2919 if (st->duration == AV_NOPTS_VALUE) {
2920 switch (st->codecpar->codec_type) {
2921 case AVMEDIA_TYPE_VIDEO:
2922 case AVMEDIA_TYPE_AUDIO:
2923 if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2924 av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
2926 av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
2931 fill_all_stream_timings(ic);
2933 avio_seek(ic->pb, old_offset, SEEK_SET);
2934 for (i = 0; i < ic->nb_streams; i++) {
2937 st = ic->streams[i];
2938 st->cur_dts = st->first_dts;
2939 st->last_IP_pts = AV_NOPTS_VALUE;
2940 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
2941 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2942 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
2946 /* 1:1 map to AVDurationEstimationMethod */
2947 static const char *const duration_name[] = {
2948 [AVFMT_DURATION_FROM_PTS] = "pts",
2949 [AVFMT_DURATION_FROM_STREAM] = "stream",
2950 [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2953 static const char *duration_estimate_name(enum AVDurationEstimationMethod method)
2955 return duration_name[method];
2958 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2962 /* get the file size, if possible */
2963 if (ic->iformat->flags & AVFMT_NOFILE) {
2966 file_size = avio_size(ic->pb);
2967 file_size = FFMAX(0, file_size);
2970 if ((!strcmp(ic->iformat->name, "mpeg") ||
2971 !strcmp(ic->iformat->name, "mpegts")) &&
2972 file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2973 /* get accurate estimate from the PTSes */
2974 estimate_timings_from_pts(ic, old_offset);
2975 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2976 } else if (has_duration(ic)) {
2977 /* at least one component has timings - we use them for all
2979 fill_all_stream_timings(ic);
2980 /* nut demuxer estimate the duration from PTS */
2981 if(!strcmp(ic->iformat->name, "nut"))
2982 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2984 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2986 /* less precise: use bitrate info */
2987 estimate_timings_from_bit_rate(ic);
2988 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2990 update_stream_timings(ic);
2992 for (unsigned i = 0; i < ic->nb_streams; i++) {
2993 AVStream *st = ic->streams[i];
2994 if (st->time_base.den)
2995 av_log(ic, AV_LOG_TRACE, "stream %u: start_time: %s duration: %s\n", i,
2996 av_ts2timestr(st->start_time, &st->time_base),
2997 av_ts2timestr(st->duration, &st->time_base));
2999 av_log(ic, AV_LOG_TRACE,
3000 "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
3001 av_ts2timestr(ic->start_time, &AV_TIME_BASE_Q),
3002 av_ts2timestr(ic->duration, &AV_TIME_BASE_Q),
3003 duration_estimate_name(ic->duration_estimation_method),
3004 (int64_t)ic->bit_rate / 1000);
3007 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
3009 AVCodecContext *avctx = st->internal->avctx;
3011 #define FAIL(errmsg) do { \
3013 *errmsg_ptr = errmsg; \
3017 if ( avctx->codec_id == AV_CODEC_ID_NONE
3018 && avctx->codec_type != AVMEDIA_TYPE_DATA)
3019 FAIL("unknown codec");
3020 switch (avctx->codec_type) {
3021 case AVMEDIA_TYPE_AUDIO:
3022 if (!avctx->frame_size && determinable_frame_size(avctx))
3023 FAIL("unspecified frame size");
3024 if (st->internal->info->found_decoder >= 0 &&
3025 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
3026 FAIL("unspecified sample format");
3027 if (!avctx->sample_rate)
3028 FAIL("unspecified sample rate");
3029 if (!avctx->channels)
3030 FAIL("unspecified number of channels");
3031 if (st->internal->info->found_decoder >= 0 && !st->internal->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
3032 FAIL("no decodable DTS frames");
3034 case AVMEDIA_TYPE_VIDEO:
3036 FAIL("unspecified size");
3037 if (st->internal->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
3038 FAIL("unspecified pixel format");
3039 if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
3040 if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !st->codec_info_nb_frames)
3041 FAIL("no frame in rv30/40 and no sar");
3043 case AVMEDIA_TYPE_SUBTITLE:
3044 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
3045 FAIL("unspecified size");
3047 case AVMEDIA_TYPE_DATA:
3048 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
3054 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
3055 static int try_decode_frame(AVFormatContext *s, AVStream *st,
3056 const AVPacket *avpkt, AVDictionary **options)
3058 AVCodecContext *avctx = st->internal->avctx;
3059 const AVCodec *codec;
3060 int got_picture = 1, ret = 0;
3061 AVFrame *frame = av_frame_alloc();
3062 AVSubtitle subtitle;
3063 AVPacket pkt = *avpkt;
3064 int do_skip_frame = 0;
3065 enum AVDiscard skip_frame;
3068 return AVERROR(ENOMEM);
3070 if (!avcodec_is_open(avctx) &&
3071 st->internal->info->found_decoder <= 0 &&
3072 (st->codecpar->codec_id != -st->internal->info->found_decoder || !st->codecpar->codec_id)) {
3073 AVDictionary *thread_opt = NULL;
3075 codec = find_probe_decoder(s, st, st->codecpar->codec_id);
3078 st->internal->info->found_decoder = -st->codecpar->codec_id;
3083 /* Force thread count to 1 since the H.264 decoder will not extract
3084 * SPS and PPS to extradata during multi-threaded decoding. */
3085 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
3086 /* Force lowres to 0. The decoder might reduce the video size by the
3087 * lowres factor, and we don't want that propagated to the stream's
3089 av_dict_set(options ? options : &thread_opt, "lowres", "0", 0);
3090 if (s->codec_whitelist)
3091 av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3092 ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3094 av_dict_free(&thread_opt);
3096 st->internal->info->found_decoder = -avctx->codec_id;
3099 st->internal->info->found_decoder = 1;
3100 } else if (!st->internal->info->found_decoder)
3101 st->internal->info->found_decoder = 1;
3103 if (st->internal->info->found_decoder < 0) {
3108 if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
3110 skip_frame = avctx->skip_frame;
3111 avctx->skip_frame = AVDISCARD_ALL;
3114 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
3116 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
3117 (!st->codec_info_nb_frames &&
3118 (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
3120 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3121 avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3122 ret = avcodec_send_packet(avctx, &pkt);
3123 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3127 ret = avcodec_receive_frame(avctx, frame);
3130 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
3132 } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3133 ret = avcodec_decode_subtitle2(avctx, &subtitle,
3134 &got_picture, &pkt);
3136 avsubtitle_free(&subtitle);
3142 st->internal->nb_decoded_frames++;
3147 if (!pkt.data && !got_picture)
3151 if (do_skip_frame) {
3152 avctx->skip_frame = skip_frame;
3155 av_frame_free(&frame);
3159 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3161 while (tags->id != AV_CODEC_ID_NONE) {
3169 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3172 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3173 if (tag == tags[i].tag)
3175 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3176 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3178 return AV_CODEC_ID_NONE;
3181 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
3183 if (bps <= 0 || bps > 64)
3184 return AV_CODEC_ID_NONE;
3189 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
3191 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
3193 return AV_CODEC_ID_NONE;
3198 if (sflags & (1 << (bps - 1))) {
3201 return AV_CODEC_ID_PCM_S8;
3203 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
3205 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
3207 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
3209 return be ? AV_CODEC_ID_PCM_S64BE : AV_CODEC_ID_PCM_S64LE;
3211 return AV_CODEC_ID_NONE;
3216 return AV_CODEC_ID_PCM_U8;
3218 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
3220 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
3222 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
3224 return AV_CODEC_ID_NONE;
3230 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3233 if (!av_codec_get_tag2(tags, id, &tag))
3238 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
3242 for (i = 0; tags && tags[i]; i++) {
3243 const AVCodecTag *codec_tags = tags[i];
3244 while (codec_tags->id != AV_CODEC_ID_NONE) {
3245 if (codec_tags->id == id) {
3246 *tag = codec_tags->tag;
3255 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3258 for (i = 0; tags && tags[i]; i++) {
3259 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
3260 if (id != AV_CODEC_ID_NONE)
3263 return AV_CODEC_ID_NONE;
3266 static int chapter_start_cmp(const void *p1, const void *p2)
3268 AVChapter *ch1 = *(AVChapter**)p1;
3269 AVChapter *ch2 = *(AVChapter**)p2;
3270 int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
3273 return (ch1 > ch2) - (ch1 < ch2);
3276 static int compute_chapters_end(AVFormatContext *s)
3279 int64_t max_time = 0;
3280 AVChapter **timetable = av_malloc(s->nb_chapters * sizeof(*timetable));
3283 return AVERROR(ENOMEM);
3285 if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3286 max_time = s->duration +
3287 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3289 for (i = 0; i < s->nb_chapters; i++)
3290 timetable[i] = s->chapters[i];
3291 qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
3293 for (i = 0; i < s->nb_chapters; i++)
3294 if (timetable[i]->end == AV_NOPTS_VALUE) {
3295 AVChapter *ch = timetable[i];
3296 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3300 if (i + 1 < s->nb_chapters) {
3301 AVChapter *ch1 = timetable[i + 1];
3302 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3304 if (next_start > ch->start && next_start < end)
3307 ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3313 static int get_std_framerate(int i)
3316 return (i + 1) * 1001;
3320 return (i + 31) * 1001 * 12;
3324 return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3328 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3331 /* Is the time base unreliable?
3332 * This is a heuristic to balance between quick acceptance of the values in
3333 * the headers vs. some extra checks.
3334 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3335 * MPEG-2 commonly misuses field repeat flags to store different framerates.
3336 * And there are "variable" fps files this needs to detect as well. */
3337 static int tb_unreliable(AVCodecContext *c)
3339 if (c->time_base.den >= 101LL * c->time_base.num ||
3340 c->time_base.den < 5LL * c->time_base.num ||
3341 // c->codec_tag == AV_RL32("DIVX") ||
3342 // c->codec_tag == AV_RL32("XVID") ||
3343 c->codec_tag == AV_RL32("mp4v") ||
3344 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3345 c->codec_id == AV_CODEC_ID_GIF ||
3346 c->codec_id == AV_CODEC_ID_HEVC ||
3347 c->codec_id == AV_CODEC_ID_H264)
3352 int ff_alloc_extradata(AVCodecParameters *par, int size)
3354 av_freep(&par->extradata);
3355 par->extradata_size = 0;
3357 if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3358 return AVERROR(EINVAL);
3360 par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3361 if (!par->extradata)
3362 return AVERROR(ENOMEM);
3364 memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3365 par->extradata_size = size;
3370 int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3372 int ret = ff_alloc_extradata(par, size);
3375 ret = avio_read(pb, par->extradata, size);
3377 av_freep(&par->extradata);
3378 par->extradata_size = 0;
3379 av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3380 return ret < 0 ? ret : AVERROR_INVALIDDATA;
3386 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3389 int64_t last = st->internal->info->last_dts;
3391 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3392 && ts - (uint64_t)last < INT64_MAX) {
3393 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3394 int64_t duration = ts - last;
3396 if (!st->internal->info->duration_error)
3397 st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3398 if (!st->internal->info->duration_error)
3399 return AVERROR(ENOMEM);
3401 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3402 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3403 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3404 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3405 int framerate = get_std_framerate(i);
3406 double sdts = dts*framerate/(1001*12);
3407 for (j= 0; j<2; j++) {
3408 int64_t ticks = llrint(sdts+j*0.5);
3409 double error= sdts - ticks + j*0.5;
3410 st->internal->info->duration_error[j][0][i] += error;
3411 st->internal->info->duration_error[j][1][i] += error*error;
3415 if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3416 st->internal->info->duration_count++;
3417 st->internal->info->rfps_duration_sum += duration;
3420 if (st->internal->info->duration_count % 10 == 0) {
3421 int n = st->internal->info->duration_count;
3422 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3423 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3424 double a0 = st->internal->info->duration_error[0][0][i] / n;
3425 double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3426 double a1 = st->internal->info->duration_error[1][0][i] / n;
3427 double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3428 if (error0 > 0.04 && error1 > 0.04) {
3429 st->internal->info->duration_error[0][1][i] = 2e10;
3430 st->internal->info->duration_error[1][1][i] = 2e10;
3436 // ignore the first 4 values, they might have some random jitter
3437 if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3438 st->internal->info->duration_gcd = av_gcd(st->internal->info->duration_gcd, duration);
3440 if (ts != AV_NOPTS_VALUE)
3441 st->internal->info->last_dts = ts;
3446 void ff_rfps_calculate(AVFormatContext *ic)
3450 for (i = 0; i < ic->nb_streams; i++) {
3451 AVStream *st = ic->streams[i];
3453 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3455 // the check for tb_unreliable() is not completely correct, since this is not about handling
3456 // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3457 // ipmovie.c produces.
3458 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 &&
3459 st->internal->info->duration_gcd < INT64_MAX / st->time_base.num)
3460 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);
3461 if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3462 && tb_unreliable(st->internal->avctx)) {
3464 double best_error= 0.01;
3465 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3467 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3470 if (st->internal->info->codec_info_duration &&
3471 st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3473 if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3476 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))
3479 for (k= 0; k<2; k++) {
3480 int n = st->internal->info->duration_count;
3481 double a= st->internal->info->duration_error[k][0][j] / n;
3482 double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3484 if (error < best_error && best_error> 0.000000001) {
3486 num = get_std_framerate(j);
3489 av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3492 // do not increase frame rate by more than 1 % in order to match a standard rate.
3493 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3494 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3496 if ( !st->avg_frame_rate.num
3497 && st->r_frame_rate.num && st->internal->info->rfps_duration_sum
3498 && st->internal->info->codec_info_duration <= 0
3499 && st->internal->info->duration_count > 2
3500 && 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
3502 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3503 st->avg_frame_rate = st->r_frame_rate;
3506 av_freep(&st->internal->info->duration_error);
3507 st->internal->info->last_dts = AV_NOPTS_VALUE;
3508 st->internal->info->duration_count = 0;
3509 st->internal->info->rfps_duration_sum = 0;
3513 static int extract_extradata_check(AVStream *st)
3515 const AVBitStreamFilter *f;
3517 f = av_bsf_get_by_name("extract_extradata");
3522 const enum AVCodecID *ids;
3523 for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3524 if (*ids == st->codecpar->codec_id)
3531 static int extract_extradata_init(AVStream *st)
3533 AVStreamInternal *sti = st->internal;
3534 const AVBitStreamFilter *f;
3537 f = av_bsf_get_by_name("extract_extradata");
3541 /* check that the codec id is supported */
3542 ret = extract_extradata_check(st);
3546 ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3550 ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3555 sti->extract_extradata.bsf->time_base_in = st->time_base;
3557 ret = av_bsf_init(sti->extract_extradata.bsf);
3562 sti->extract_extradata.inited = 1;
3566 av_bsf_free(&sti->extract_extradata.bsf);
3570 static int extract_extradata(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
3572 AVStreamInternal *sti = st->internal;
3573 AVPacket *pkt_ref = s->internal->parse_pkt;
3576 if (!sti->extract_extradata.inited) {
3577 ret = extract_extradata_init(st);
3582 if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3585 ret = av_packet_ref(pkt_ref, pkt);
3589 ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3591 av_packet_unref(pkt_ref);
3595 while (ret >= 0 && !sti->avctx->extradata) {
3596 ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3598 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3603 for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3604 AVPacketSideData *side_data = &pkt_ref->side_data[i];
3605 if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3606 sti->avctx->extradata = side_data->data;
3607 sti->avctx->extradata_size = side_data->size;
3608 side_data->data = NULL;
3609 side_data->size = 0;
3613 av_packet_unref(pkt_ref);
3619 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
3623 for (i = 0; i < avctx->nb_coded_side_data; i++) {
3624 const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3626 dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3628 return AVERROR(ENOMEM);
3629 memcpy(dst_data, sd_src->data, sd_src->size);
3634 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3636 int i, count = 0, ret = 0, j;
3639 AVCodecContext *avctx;
3640 AVPacket *pkt1 = ic->internal->pkt;
3641 int64_t old_offset = avio_tell(ic->pb);
3642 // new streams might appear, no options for those
3643 int orig_nb_streams = ic->nb_streams;
3645 int64_t max_analyze_duration = ic->max_analyze_duration;
3646 int64_t max_stream_analyze_duration;
3647 int64_t max_subtitle_analyze_duration;
3648 int64_t probesize = ic->probesize;
3649 int eof_reached = 0;
3650 int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3652 flush_codecs = probesize > 0;
3654 av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3656 max_stream_analyze_duration = max_analyze_duration;
3657 max_subtitle_analyze_duration = max_analyze_duration;
3658 if (!max_analyze_duration) {
3659 max_stream_analyze_duration =
3660 max_analyze_duration = 5*AV_TIME_BASE;
3661 max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3662 if (!strcmp(ic->iformat->name, "flv"))
3663 max_stream_analyze_duration = 90*AV_TIME_BASE;
3664 if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3665 max_stream_analyze_duration = 7*AV_TIME_BASE;
3669 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3670 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3672 for (i = 0; i < ic->nb_streams; i++) {
3673 const AVCodec *codec;
3674 AVDictionary *thread_opt = NULL;
3675 st = ic->streams[i];
3676 avctx = st->internal->avctx;
3678 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3679 st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3680 /* if (!st->time_base.num)
3682 if (!avctx->time_base.num)
3683 avctx->time_base = st->time_base;
3686 /* check if the caller has overridden the codec id */
3687 #if FF_API_LAVF_AVCTX
3688 FF_DISABLE_DEPRECATION_WARNINGS
3689 if (st->codec->codec_id != st->internal->orig_codec_id) {
3690 st->codecpar->codec_id = st->codec->codec_id;
3691 st->codecpar->codec_type = st->codec->codec_type;
3692 st->internal->orig_codec_id = st->codec->codec_id;
3694 FF_ENABLE_DEPRECATION_WARNINGS
3696 // only for the split stuff
3697 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3698 st->parser = av_parser_init(st->codecpar->codec_id);
3700 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3701 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3702 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3703 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3705 } else if (st->need_parsing) {
3706 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3707 "%s, packets or times may be invalid.\n",
3708 avcodec_get_name(st->codecpar->codec_id));
3712 if (st->codecpar->codec_id != st->internal->orig_codec_id)
3713 st->internal->orig_codec_id = st->codecpar->codec_id;
3715 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3717 goto find_stream_info_err;
3718 if (st->internal->request_probe <= 0)
3719 st->internal->avctx_inited = 1;
3721 codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3723 /* Force thread count to 1 since the H.264 decoder will not extract
3724 * SPS and PPS to extradata during multi-threaded decoding. */
3725 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3726 /* Force lowres to 0. The decoder might reduce the video size by the
3727 * lowres factor, and we don't want that propagated to the stream's
3729 av_dict_set(options ? &options[i] : &thread_opt, "lowres", "0", 0);
3731 if (ic->codec_whitelist)
3732 av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3734 // Try to just open decoders, in case this is enough to get parameters.
3735 // Also ensure that subtitle_header is properly set.
3736 if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0 ||
3737 st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3738 if (codec && !avctx->codec)
3739 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3740 av_log(ic, AV_LOG_WARNING,
3741 "Failed to open codec in %s\n",__FUNCTION__);
3744 av_dict_free(&thread_opt);
3747 for (i = 0; i < ic->nb_streams; i++) {
3748 #if FF_API_R_FRAME_RATE
3749 ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
3751 ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
3752 ic->streams[i]->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3757 const AVPacket *pkt;
3758 int analyzed_all_streams;
3759 if (ff_check_interrupt(&ic->interrupt_callback)) {
3761 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3765 /* check if one codec still needs to be handled */
3766 for (i = 0; i < ic->nb_streams; i++) {
3767 int fps_analyze_framecount = 20;
3770 st = ic->streams[i];
3771 if (!has_codec_parameters(st, NULL))
3773 /* If the timebase is coarse (like the usual millisecond precision
3774 * of mkv), we need to analyze more frames to reliably arrive at
3775 * the correct fps. */
3776 if (av_q2d(st->time_base) > 0.0005)
3777 fps_analyze_framecount *= 2;
3778 if (!tb_unreliable(st->internal->avctx))
3779 fps_analyze_framecount = 0;
3780 if (ic->fps_probe_size >= 0)
3781 fps_analyze_framecount = ic->fps_probe_size;
3782 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3783 fps_analyze_framecount = 0;
3784 /* variable fps and no guess at the real fps */
3785 count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3786 st->internal->info->codec_info_duration_fields/2 :
3787 st->internal->info->duration_count;
3788 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3789 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3790 if (count < fps_analyze_framecount)
3793 // Look at the first 3 frames if there is evidence of frame delay
3794 // but the decoder delay is not set.
3795 if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3797 if (!st->internal->avctx->extradata &&
3798 (!st->internal->extract_extradata.inited ||
3799 st->internal->extract_extradata.bsf) &&
3800 extract_extradata_check(st))
3802 if (st->first_dts == AV_NOPTS_VALUE &&
3803 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3804 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3805 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3806 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3809 analyzed_all_streams = 0;
3810 if (!missing_streams || !*missing_streams)
3811 if (i == ic->nb_streams) {
3812 analyzed_all_streams = 1;
3813 /* NOTE: If the format has no header, then we need to read some
3814 * packets to get most of the streams, so we cannot stop here. */
3815 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3816 /* If we found the info for all the codecs, we can stop. */
3818 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3823 /* We did not get all the codec info, but we read too much data. */
3824 if (read_size >= probesize) {
3826 av_log(ic, AV_LOG_DEBUG,
3827 "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3828 for (i = 0; i < ic->nb_streams; i++)
3829 if (!ic->streams[i]->r_frame_rate.num &&
3830 ic->streams[i]->internal->info->duration_count <= 1 &&
3831 ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3832 strcmp(ic->iformat->name, "image2"))
3833 av_log(ic, AV_LOG_WARNING,
3834 "Stream #%d: not enough frames to estimate rate; "
3835 "consider increasing probesize\n", i);
3839 /* NOTE: A new stream can be added there if no header in file
3840 * (AVFMTCTX_NOHEADER). */
3841 ret = read_frame_internal(ic, pkt1);
3842 if (ret == AVERROR(EAGAIN))
3851 if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3852 ret = avpriv_packet_list_put(&ic->internal->packet_buffer,
3853 &ic->internal->packet_buffer_end,
3856 goto unref_then_goto_end;
3858 pkt = &ic->internal->packet_buffer_end->pkt;
3863 st = ic->streams[pkt->stream_index];
3864 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3865 read_size += pkt->size;
3867 avctx = st->internal->avctx;
3868 if (!st->internal->avctx_inited) {
3869 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3871 goto unref_then_goto_end;
3872 st->internal->avctx_inited = 1;
3875 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3876 /* check for non-increasing dts */
3877 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3878 st->internal->info->fps_last_dts >= pkt->dts) {
3879 av_log(ic, AV_LOG_DEBUG,
3880 "Non-increasing DTS in stream %d: packet %d with DTS "
3881 "%"PRId64", packet %d with DTS %"PRId64"\n",
3882 st->index, st->internal->info->fps_last_dts_idx,
3883 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3885 st->internal->info->fps_first_dts =
3886 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3888 /* Check for a discontinuity in dts. If the difference in dts
3889 * is more than 1000 times the average packet duration in the
3890 * sequence, we treat it as a discontinuity. */
3891 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3892 st->internal->info->fps_last_dts_idx > st->internal->info->fps_first_dts_idx &&
3893 (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3894 (st->internal->info->fps_last_dts - (uint64_t)st->internal->info->fps_first_dts) /
3895 (st->internal->info->fps_last_dts_idx - st->internal->info->fps_first_dts_idx)) {
3896 av_log(ic, AV_LOG_WARNING,
3897 "DTS discontinuity in stream %d: packet %d with DTS "
3898 "%"PRId64", packet %d with DTS %"PRId64"\n",
3899 st->index, st->internal->info->fps_last_dts_idx,
3900 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3902 st->internal->info->fps_first_dts =
3903 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3906 /* update stored dts values */
3907 if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3908 st->internal->info->fps_first_dts = pkt->dts;
3909 st->internal->info->fps_first_dts_idx = st->codec_info_nb_frames;
3911 st->internal->info->fps_last_dts = pkt->dts;
3912 st->internal->info->fps_last_dts_idx = st->codec_info_nb_frames;
3914 if (st->codec_info_nb_frames>1) {
3918 if (st->time_base.den > 0)
3919 t = av_rescale_q(st->internal->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3920 if (st->avg_frame_rate.num > 0)
3921 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3924 && st->codec_info_nb_frames>30
3925 && st->internal->info->fps_first_dts != AV_NOPTS_VALUE
3926 && st->internal->info->fps_last_dts != AV_NOPTS_VALUE) {
3927 int64_t dur = av_sat_sub64(st->internal->info->fps_last_dts, st->internal->info->fps_first_dts);
3928 t = FFMAX(t, av_rescale_q(dur, st->time_base, AV_TIME_BASE_Q));
3931 if (analyzed_all_streams) limit = max_analyze_duration;
3932 else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3933 else limit = max_stream_analyze_duration;
3936 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3938 t, pkt->stream_index);
3939 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3940 av_packet_unref(pkt1);
3943 if (pkt->duration) {
3944 if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3945 st->internal->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->internal->info->codec_info_duration + pkt->duration);
3947 st->internal->info->codec_info_duration += pkt->duration;
3948 st->internal->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3951 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3952 #if FF_API_R_FRAME_RATE
3953 ff_rfps_add_frame(ic, st, pkt->dts);
3955 if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3956 st->internal->info->frame_delay_evidence = 1;
3958 if (!st->internal->avctx->extradata) {
3959 ret = extract_extradata(ic, st, pkt);
3961 goto unref_then_goto_end;
3964 /* If still no information, we try to open the codec and to
3965 * decompress the frame. We try to avoid that in most cases as
3966 * it takes longer and uses more memory. For MPEG-4, we need to
3967 * decompress for QuickTime.
3969 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3970 * least one frame of codec data, this makes sure the codec initializes
3971 * the channel configuration and does not only trust the values from
3973 try_decode_frame(ic, st, pkt,
3974 (options && i < orig_nb_streams) ? &options[i] : NULL);
3976 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3977 av_packet_unref(pkt1);
3979 st->codec_info_nb_frames++;
3985 for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3986 st = ic->streams[stream_index];
3987 avctx = st->internal->avctx;
3988 if (!has_codec_parameters(st, NULL)) {
3989 const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3990 if (codec && !avctx->codec) {
3991 AVDictionary *opts = NULL;
3992 if (ic->codec_whitelist)
3993 av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3994 if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3995 av_log(ic, AV_LOG_WARNING,
3996 "Failed to open codec in %s\n",__FUNCTION__);
3997 av_dict_free(&opts);
4001 // EOF already reached while reading the stream above.
4002 // So continue with reoordering DTS with whatever delay we have.
4003 if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
4004 update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
4010 AVPacket *empty_pkt = ic->internal->pkt;
4012 av_packet_unref(empty_pkt);
4014 for (i = 0; i < ic->nb_streams; i++) {
4016 st = ic->streams[i];
4018 /* flush the decoders */
4019 if (st->internal->info->found_decoder == 1) {
4021 err = try_decode_frame(ic, st, empty_pkt,
4022 (options && i < orig_nb_streams)
4023 ? &options[i] : NULL);
4024 } while (err > 0 && !has_codec_parameters(st, NULL));
4027 av_log(ic, AV_LOG_INFO,
4028 "decoding for stream %d failed\n", st->index);
4034 ff_rfps_calculate(ic);
4036 for (i = 0; i < ic->nb_streams; i++) {
4037 st = ic->streams[i];
4038 avctx = st->internal->avctx;
4039 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
4040 if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
4041 uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
4042 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
4043 avctx->codec_tag= tag;
4046 /* estimate average framerate if not set by demuxer */
4047 if (st->internal->info->codec_info_duration_fields &&
4048 !st->avg_frame_rate.num &&
4049 st->internal->info->codec_info_duration) {
4051 double best_error = 0.01;
4052 AVRational codec_frame_rate = avctx->framerate;
4054 if (st->internal->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
4055 st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
4056 st->internal->info->codec_info_duration < 0)
4058 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4059 st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
4060 st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
4062 /* Round guessed framerate to a "standard" framerate if it's
4063 * within 1% of the original estimate. */
4064 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
4065 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
4066 double error = fabs(av_q2d(st->avg_frame_rate) /
4067 av_q2d(std_fps) - 1);
4069 if (error < best_error) {
4071 best_fps = std_fps.num;
4074 if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
4075 error = fabs(av_q2d(codec_frame_rate) /
4076 av_q2d(std_fps) - 1);
4077 if (error < best_error) {
4079 best_fps = std_fps.num;
4084 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4085 best_fps, 12 * 1001, INT_MAX);
4088 if (!st->r_frame_rate.num) {
4089 if ( avctx->time_base.den * (int64_t) st->time_base.num
4090 <= avctx->time_base.num * avctx->ticks_per_frame * (uint64_t) st->time_base.den) {
4091 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4092 avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4094 st->r_frame_rate.num = st->time_base.den;
4095 st->r_frame_rate.den = st->time_base.num;
4098 if (st->internal->display_aspect_ratio.num && st->internal->display_aspect_ratio.den) {
4099 AVRational hw_ratio = { avctx->height, avctx->width };
4100 st->sample_aspect_ratio = av_mul_q(st->internal->display_aspect_ratio,
4103 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4104 if (!avctx->bits_per_coded_sample)
4105 avctx->bits_per_coded_sample =
4106 av_get_bits_per_sample(avctx->codec_id);
4107 // set stream disposition based on audio service type
4108 switch (avctx->audio_service_type) {
4109 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4110 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
4112 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4113 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
4115 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4116 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
4118 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4119 st->disposition = AV_DISPOSITION_COMMENT;
4121 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4122 st->disposition = AV_DISPOSITION_KARAOKE;
4129 estimate_timings(ic, old_offset);
4131 av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4133 if (ret >= 0 && ic->nb_streams)
4134 /* We could not have all the codec parameters before EOF. */
4136 for (i = 0; i < ic->nb_streams; i++) {
4138 st = ic->streams[i];
4140 /* if no packet was ever seen, update context now for has_codec_parameters */
4141 if (!st->internal->avctx_inited) {
4142 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4143 st->codecpar->format == AV_SAMPLE_FMT_NONE)
4144 st->codecpar->format = st->internal->avctx->sample_fmt;
4145 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
4147 goto find_stream_info_err;
4149 if (!has_codec_parameters(st, &errmsg)) {
4151 avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4152 av_log(ic, AV_LOG_WARNING,
4153 "Could not find codec parameters for stream %d (%s): %s\n"
4154 "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4155 i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4161 ret = compute_chapters_end(ic);
4163 goto find_stream_info_err;
4165 /* update the stream parameters from the internal codec contexts */
4166 for (i = 0; i < ic->nb_streams; i++) {
4167 st = ic->streams[i];
4169 if (st->internal->avctx_inited) {
4170 ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
4172 goto find_stream_info_err;
4173 ret = add_coded_side_data(st, st->internal->avctx);
4175 goto find_stream_info_err;
4178 #if FF_API_LAVF_AVCTX
4179 FF_DISABLE_DEPRECATION_WARNINGS
4180 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
4182 goto find_stream_info_err;
4184 // The old API (AVStream.codec) "requires" the resolution to be adjusted
4185 // by the lowres factor.
4186 if (st->internal->avctx->lowres && st->internal->avctx->width) {
4187 st->codec->lowres = st->internal->avctx->lowres;
4188 st->codec->width = st->internal->avctx->width;
4189 st->codec->height = st->internal->avctx->height;
4192 if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4193 st->codec->time_base = st->internal->avctx->time_base;
4194 st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
4196 st->codec->framerate = st->avg_frame_rate;
4198 if (st->internal->avctx->subtitle_header) {
4199 st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
4200 if (!st->codec->subtitle_header)
4201 goto find_stream_info_err;
4202 st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
4203 memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
4204 st->codec->subtitle_header_size);
4207 // Fields unavailable in AVCodecParameters
4208 st->codec->coded_width = st->internal->avctx->coded_width;
4209 st->codec->coded_height = st->internal->avctx->coded_height;
4210 st->codec->properties = st->internal->avctx->properties;
4211 FF_ENABLE_DEPRECATION_WARNINGS
4214 st->internal->avctx_inited = 0;
4217 find_stream_info_err:
4218 for (i = 0; i < ic->nb_streams; i++) {
4219 st = ic->streams[i];
4220 if (st->internal->info)
4221 av_freep(&st->internal->info->duration_error);
4222 avcodec_close(ic->streams[i]->internal->avctx);
4223 av_freep(&ic->streams[i]->internal->info);
4224 av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
4227 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
4228 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
4231 unref_then_goto_end:
4232 av_packet_unref(pkt1);
4233 goto find_stream_info_err;
4236 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4240 for (i = 0; i < ic->nb_programs; i++) {
4241 if (ic->programs[i] == last) {
4245 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
4246 if (ic->programs[i]->stream_index[j] == s)
4247 return ic->programs[i];
4253 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
4254 int wanted_stream_nb, int related_stream,
4255 AVCodec **decoder_ret, int flags)
4257 int i, nb_streams = ic->nb_streams;
4258 int ret = AVERROR_STREAM_NOT_FOUND;
4259 int best_count = -1, best_multiframe = -1, best_disposition = -1;
4260 int count, multiframe, disposition;
4261 int64_t best_bitrate = -1;
4263 unsigned *program = NULL;
4264 const AVCodec *decoder = NULL, *best_decoder = NULL;
4266 if (related_stream >= 0 && wanted_stream_nb < 0) {
4267 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4269 program = p->stream_index;
4270 nb_streams = p->nb_stream_indexes;
4273 for (i = 0; i < nb_streams; i++) {
4274 int real_stream_index = program ? program[i] : i;
4275 AVStream *st = ic->streams[real_stream_index];
4276 AVCodecParameters *par = st->codecpar;
4277 if (par->codec_type != type)
4279 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4281 if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4284 decoder = find_decoder(ic, st, par->codec_id);
4287 ret = AVERROR_DECODER_NOT_FOUND;
4291 disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
4292 + !! (st->disposition & AV_DISPOSITION_DEFAULT);
4293 count = st->codec_info_nb_frames;
4294 bitrate = par->bit_rate;
4295 multiframe = FFMIN(5, count);
4296 if ((best_disposition > disposition) ||
4297 (best_disposition == disposition && best_multiframe > multiframe) ||
4298 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate > bitrate) ||
4299 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4301 best_disposition = disposition;
4303 best_bitrate = bitrate;
4304 best_multiframe = multiframe;
4305 ret = real_stream_index;
4306 best_decoder = decoder;
4307 if (program && i == nb_streams - 1 && ret < 0) {
4309 nb_streams = ic->nb_streams;
4310 /* no related stream found, try again with everything */
4315 *decoder_ret = (AVCodec*)best_decoder;
4319 /*******************************************************/
4321 int av_read_play(AVFormatContext *s)
4323 if (s->iformat->read_play)
4324 return s->iformat->read_play(s);
4326 return avio_pause(s->pb, 0);
4327 return AVERROR(ENOSYS);
4330 int av_read_pause(AVFormatContext *s)
4332 if (s->iformat->read_pause)
4333 return s->iformat->read_pause(s);
4335 return avio_pause(s->pb, 1);
4336 return AVERROR(ENOSYS);
4339 int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
4344 dst->time_base = src->time_base;
4345 dst->nb_frames = src->nb_frames;
4346 dst->disposition = src->disposition;
4347 dst->sample_aspect_ratio = src->sample_aspect_ratio;
4348 dst->avg_frame_rate = src->avg_frame_rate;
4349 dst->r_frame_rate = src->r_frame_rate;
4351 av_dict_free(&dst->metadata);
4352 ret = av_dict_copy(&dst->metadata, src->metadata, 0);
4356 ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
4360 /* Free existing side data*/
4361 for (i = 0; i < dst->nb_side_data; i++)
4362 av_free(dst->side_data[i].data);
4363 av_freep(&dst->side_data);
4364 dst->nb_side_data = 0;
4366 /* Copy side data if present */
4367 if (src->nb_side_data) {
4368 dst->side_data = av_mallocz_array(src->nb_side_data,
4369 sizeof(AVPacketSideData));
4370 if (!dst->side_data)
4371 return AVERROR(ENOMEM);
4372 dst->nb_side_data = src->nb_side_data;
4374 for (i = 0; i < src->nb_side_data; i++) {
4375 uint8_t *data = av_memdup(src->side_data[i].data,
4376 src->side_data[i].size);
4378 return AVERROR(ENOMEM);
4379 dst->side_data[i].type = src->side_data[i].type;
4380 dst->side_data[i].size = src->side_data[i].size;
4381 dst->side_data[i].data = data;
4388 static void free_stream(AVStream **pst)
4390 AVStream *st = *pst;
4396 for (i = 0; i < st->nb_side_data; i++)
4397 av_freep(&st->side_data[i].data);
4398 av_freep(&st->side_data);
4401 av_parser_close(st->parser);
4403 if (st->attached_pic.data)
4404 av_packet_unref(&st->attached_pic);
4407 avcodec_free_context(&st->internal->avctx);
4408 av_bsf_free(&st->internal->bsfc);
4409 av_freep(&st->internal->priv_pts);
4410 av_freep(&st->internal->index_entries);
4411 av_freep(&st->internal->probe_data.buf);
4413 av_bsf_free(&st->internal->extract_extradata.bsf);
4415 if (st->internal->info)
4416 av_freep(&st->internal->info->duration_error);
4417 av_freep(&st->internal->info);
4419 av_freep(&st->internal);
4421 av_dict_free(&st->metadata);
4422 avcodec_parameters_free(&st->codecpar);
4423 #if FF_API_LAVF_AVCTX
4424 FF_DISABLE_DEPRECATION_WARNINGS
4425 avcodec_free_context(&st->codec);
4426 FF_ENABLE_DEPRECATION_WARNINGS
4428 av_freep(&st->priv_data);
4433 void ff_free_stream(AVFormatContext *s, AVStream *st)
4435 av_assert0(s->nb_streams>0);
4436 av_assert0(s->streams[ s->nb_streams - 1 ] == st);
4438 free_stream(&s->streams[ --s->nb_streams ]);
4441 void avformat_free_context(AVFormatContext *s)
4448 if (s->oformat && s->oformat->deinit && s->internal->initialized)
4449 s->oformat->deinit(s);
4452 if (s->iformat && s->iformat->priv_class && s->priv_data)
4453 av_opt_free(s->priv_data);
4454 if (s->oformat && s->oformat->priv_class && s->priv_data)
4455 av_opt_free(s->priv_data);
4457 for (i = 0; i < s->nb_streams; i++)
4458 free_stream(&s->streams[i]);
4461 for (i = 0; i < s->nb_programs; i++) {
4462 av_dict_free(&s->programs[i]->metadata);
4463 av_freep(&s->programs[i]->stream_index);
4464 av_freep(&s->programs[i]);
4468 av_freep(&s->programs);
4469 av_freep(&s->priv_data);
4470 while (s->nb_chapters--) {
4471 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4472 av_freep(&s->chapters[s->nb_chapters]);
4474 av_freep(&s->chapters);
4475 av_dict_free(&s->metadata);
4476 av_dict_free(&s->internal->id3v2_meta);
4477 av_packet_free(&s->internal->pkt);
4478 av_packet_free(&s->internal->parse_pkt);
4479 av_freep(&s->streams);
4480 flush_packet_queue(s);
4481 av_freep(&s->internal);
4486 void avformat_close_input(AVFormatContext **ps)
4497 if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4498 (s->flags & AVFMT_FLAG_CUSTOM_IO))
4501 flush_packet_queue(s);
4504 if (s->iformat->read_close)
4505 s->iformat->read_close(s);
4507 avformat_free_context(s);
4514 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4520 if (s->nb_streams >= s->max_streams) {
4521 av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter"
4522 " (%d), see the documentation if you wish to increase it\n",
4526 streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4529 s->streams = streams;
4531 st = av_mallocz(sizeof(AVStream));
4535 #if FF_API_LAVF_AVCTX
4536 FF_DISABLE_DEPRECATION_WARNINGS
4537 st->codec = avcodec_alloc_context3(c);
4542 FF_ENABLE_DEPRECATION_WARNINGS
4545 st->internal = av_mallocz(sizeof(*st->internal));
4549 st->internal->info = av_mallocz(sizeof(*st->internal->info));
4550 if (!st->internal->info)
4552 st->internal->info->last_dts = AV_NOPTS_VALUE;
4554 st->codecpar = avcodec_parameters_alloc();
4558 st->internal->avctx = avcodec_alloc_context3(NULL);
4559 if (!st->internal->avctx)
4563 #if FF_API_LAVF_AVCTX
4564 FF_DISABLE_DEPRECATION_WARNINGS
4565 /* no default bitrate if decoding */
4566 st->codec->bit_rate = 0;
4567 FF_ENABLE_DEPRECATION_WARNINGS
4570 /* default pts setting is MPEG-like */
4571 avpriv_set_pts_info(st, 33, 1, 90000);
4572 /* we set the current DTS to 0 so that formats without any timestamps
4573 * but durations get some timestamps, formats with some unknown
4574 * timestamps have their first few packets buffered and the
4575 * timestamps corrected before they are returned to the user */
4576 st->cur_dts = RELATIVE_TS_BASE;
4578 st->cur_dts = AV_NOPTS_VALUE;
4581 st->index = s->nb_streams;
4582 st->start_time = AV_NOPTS_VALUE;
4583 st->duration = AV_NOPTS_VALUE;
4584 st->first_dts = AV_NOPTS_VALUE;
4585 st->probe_packets = s->max_probe_packets;
4586 st->internal->pts_wrap_reference = AV_NOPTS_VALUE;
4587 st->internal->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4589 st->last_IP_pts = AV_NOPTS_VALUE;
4590 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
4591 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
4592 st->internal->pts_buffer[i] = AV_NOPTS_VALUE;
4594 st->sample_aspect_ratio = (AVRational) { 0, 1 };
4596 #if FF_API_R_FRAME_RATE
4597 st->internal->info->last_dts = AV_NOPTS_VALUE;
4599 st->internal->info->fps_first_dts = AV_NOPTS_VALUE;
4600 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
4602 st->internal->inject_global_side_data = s->internal->inject_global_side_data;
4604 st->internal->need_context_update = 1;
4606 s->streams[s->nb_streams++] = st;
4613 AVProgram *av_new_program(AVFormatContext *ac, int id)
4615 AVProgram *program = NULL;
4618 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4620 for (i = 0; i < ac->nb_programs; i++)
4621 if (ac->programs[i]->id == id)
4622 program = ac->programs[i];
4625 program = av_mallocz(sizeof(AVProgram));
4628 ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
4633 program->discard = AVDISCARD_NONE;
4634 program->pmt_version = -1;
4636 program->pts_wrap_reference = AV_NOPTS_VALUE;
4637 program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4638 program->start_time =
4639 program->end_time = AV_NOPTS_VALUE;
4644 #if FF_API_CHAPTER_ID_INT
4645 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
4647 AVChapter *avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base,
4649 int64_t start, int64_t end, const char *title)
4651 AVChapter *chapter = NULL;
4654 if (end != AV_NOPTS_VALUE && start > end) {
4655 av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
4659 if (!s->nb_chapters) {
4660 s->internal->chapter_ids_monotonic = 1;
4661 } else if (!s->internal->chapter_ids_monotonic || s->chapters[s->nb_chapters-1]->id >= id) {
4662 s->internal->chapter_ids_monotonic = 0;
4663 for (i = 0; i < s->nb_chapters; i++)
4664 if (s->chapters[i]->id == id)
4665 chapter = s->chapters[i];
4669 chapter = av_mallocz(sizeof(AVChapter));
4672 ret = av_dynarray_add_nofree(&s->chapters, &s->nb_chapters, chapter);
4678 av_dict_set(&chapter->metadata, "title", title, 0);
4680 chapter->time_base = time_base;
4681 chapter->start = start;
4687 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4690 AVProgram *program = NULL;
4693 if (idx >= ac->nb_streams) {
4694 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
4698 for (i = 0; i < ac->nb_programs; i++) {
4699 if (ac->programs[i]->id != progid)
4701 program = ac->programs[i];
4702 for (j = 0; j < program->nb_stream_indexes; j++)
4703 if (program->stream_index[j] == idx)
4706 tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4709 program->stream_index = tmp;
4710 program->stream_index[program->nb_stream_indexes++] = idx;
4715 uint64_t ff_ntp_time(void)
4717 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4720 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
4722 uint64_t ntp_ts, frac_part, sec;
4725 //current ntp time in seconds and micro seconds
4726 sec = ntp_time_us / 1000000;
4727 usec = ntp_time_us % 1000000;
4729 //encoding in ntp timestamp format
4730 frac_part = usec * 0xFFFFFFFFULL;
4731 frac_part /= 1000000;
4733 if (sec > 0xFFFFFFFFULL)
4734 av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");
4737 ntp_ts |= frac_part;
4742 uint64_t ff_parse_ntp_time(uint64_t ntp_ts)
4744 uint64_t sec = ntp_ts >> 32;
4745 uint64_t frac_part = ntp_ts & 0xFFFFFFFFULL;
4746 uint64_t usec = (frac_part * 1000000) / 0xFFFFFFFFULL;
4748 return (sec * 1000000) + usec;
4751 int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4754 char *q, buf1[20], c;
4755 int nd, len, percentd_found;
4767 while (av_isdigit(*p)) {
4768 if (nd >= INT_MAX / 10 - 255)
4770 nd = nd * 10 + *p++ - '0';
4773 } while (av_isdigit(c));
4779 if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4784 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
4786 if ((q - buf + len) > buf_size - 1)
4788 memcpy(q, buf1, len);
4796 if ((q - buf) < buf_size - 1)
4800 if (!percentd_found)
4809 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
4811 return av_get_frame_filename2(buf, buf_size, path, number, 0);
4814 void av_url_split(char *proto, int proto_size,
4815 char *authorization, int authorization_size,
4816 char *hostname, int hostname_size,
4817 int *port_ptr, char *path, int path_size, const char *url)
4819 const char *p, *ls, *at, *at2, *col, *brk;
4825 if (authorization_size > 0)
4826 authorization[0] = 0;
4827 if (hostname_size > 0)
4832 /* parse protocol */
4833 if ((p = strchr(url, ':'))) {
4834 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
4841 /* no protocol means plain filename */
4842 av_strlcpy(path, url, path_size);
4846 /* separate path from hostname */
4847 ls = p + strcspn(p, "/?#");
4848 av_strlcpy(path, ls, path_size);
4850 /* the rest is hostname, use that to parse auth/port */
4852 /* authorization (user[:pass]@hostname) */
4854 while ((at = strchr(p, '@')) && at < ls) {
4855 av_strlcpy(authorization, at2,
4856 FFMIN(authorization_size, at + 1 - at2));
4857 p = at + 1; /* skip '@' */
4860 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4862 av_strlcpy(hostname, p + 1,
4863 FFMIN(hostname_size, brk - p));
4864 if (brk[1] == ':' && port_ptr)
4865 *port_ptr = atoi(brk + 2);
4866 } else if ((col = strchr(p, ':')) && col < ls) {
4867 av_strlcpy(hostname, p,
4868 FFMIN(col + 1 - p, hostname_size));
4870 *port_ptr = atoi(col + 1);
4872 av_strlcpy(hostname, p,
4873 FFMIN(ls + 1 - p, hostname_size));
4877 int ff_mkdir_p(const char *path)
4880 char *temp = av_strdup(path);
4884 if (!path || !temp) {
4888 if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
4890 } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
4894 for ( ; *pos != '\0'; ++pos) {
4895 if (*pos == '/' || *pos == '\\') {
4898 ret = mkdir(temp, 0755);
4903 if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
4904 ret = mkdir(temp, 0755);
4911 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4914 static const char hex_table_uc[16] = { '0', '1', '2', '3',
4917 'C', 'D', 'E', 'F' };
4918 static const char hex_table_lc[16] = { '0', '1', '2', '3',
4921 'c', 'd', 'e', 'f' };
4922 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4924 for (i = 0; i < s; i++) {
4925 buff[i * 2] = hex_table[src[i] >> 4];
4926 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4932 int ff_hex_to_data(uint8_t *data, const char *p)
4939 p += strspn(p, SPACE_CHARS);
4942 c = av_toupper((unsigned char) *p++);
4943 if (c >= '0' && c <= '9')
4945 else if (c >= 'A' && c <= 'F')
4960 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4961 unsigned int pts_num, unsigned int pts_den)
4964 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4965 if (new_tb.num != pts_num)
4966 av_log(NULL, AV_LOG_DEBUG,
4967 "st:%d removing common factor %d from timebase\n",
4968 s->index, pts_num / new_tb.num);
4970 av_log(NULL, AV_LOG_WARNING,
4971 "st:%d has too large timebase, reducing\n", s->index);
4973 if (new_tb.num <= 0 || new_tb.den <= 0) {
4974 av_log(NULL, AV_LOG_ERROR,
4975 "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4976 new_tb.num, new_tb.den,
4980 s->time_base = new_tb;
4981 #if FF_API_LAVF_AVCTX
4982 FF_DISABLE_DEPRECATION_WARNINGS
4983 s->codec->pkt_timebase = new_tb;
4984 FF_ENABLE_DEPRECATION_WARNINGS
4986 s->internal->avctx->pkt_timebase = new_tb;
4987 s->pts_wrap_bits = pts_wrap_bits;
4990 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4993 const char *ptr = str;
4995 /* Parse key=value pairs. */
4998 char *dest = NULL, *dest_end;
4999 int key_len, dest_len = 0;
5001 /* Skip whitespace and potential commas. */
5002 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
5009 if (!(ptr = strchr(key, '=')))
5012 key_len = ptr - key;
5014 callback_get_buf(context, key, key_len, &dest, &dest_len);
5015 dest_end = dest + dest_len - 1;
5019 while (*ptr && *ptr != '\"') {
5023 if (dest && dest < dest_end)
5027 if (dest && dest < dest_end)
5035 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
5036 if (dest && dest < dest_end)
5044 int ff_find_stream_index(AVFormatContext *s, int id)
5047 for (i = 0; i < s->nb_streams; i++)
5048 if (s->streams[i]->id == id)
5053 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
5057 unsigned int codec_tag;
5058 if (ofmt->query_codec)
5059 return ofmt->query_codec(codec_id, std_compliance);
5060 else if (ofmt->codec_tag)
5061 return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
5062 else if (codec_id == ofmt->video_codec ||
5063 codec_id == ofmt->audio_codec ||
5064 codec_id == ofmt->subtitle_codec ||
5065 codec_id == ofmt->data_codec)
5068 return AVERROR_PATCHWELCOME;
5071 int avformat_network_init(void)
5075 if ((ret = ff_network_init()) < 0)
5077 if ((ret = ff_tls_init()) < 0)
5083 int avformat_network_deinit(void)
5092 int ff_add_param_change(AVPacket *pkt, int32_t channels,
5093 uint64_t channel_layout, int32_t sample_rate,
5094 int32_t width, int32_t height)
5100 return AVERROR(EINVAL);
5103 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
5105 if (channel_layout) {
5107 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
5111 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
5113 if (width || height) {
5115 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
5117 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
5119 return AVERROR(ENOMEM);
5120 bytestream_put_le32(&data, flags);
5122 bytestream_put_le32(&data, channels);
5124 bytestream_put_le64(&data, channel_layout);
5126 bytestream_put_le32(&data, sample_rate);
5127 if (width || height) {
5128 bytestream_put_le32(&data, width);
5129 bytestream_put_le32(&data, height);
5134 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
5136 AVRational undef = {0, 1};
5137 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
5138 AVRational codec_sample_aspect_ratio = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5139 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
5141 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
5142 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
5143 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
5144 stream_sample_aspect_ratio = undef;
5146 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
5147 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
5148 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
5149 frame_sample_aspect_ratio = undef;
5151 if (stream_sample_aspect_ratio.num)
5152 return stream_sample_aspect_ratio;
5154 return frame_sample_aspect_ratio;
5157 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
5159 AVRational fr = st->r_frame_rate;
5160 AVRational codec_fr = st->internal->avctx->framerate;
5161 AVRational avg_fr = st->avg_frame_rate;
5163 if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
5164 av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
5169 if (st->internal->avctx->ticks_per_frame > 1) {
5170 if ( codec_fr.num > 0 && codec_fr.den > 0 &&
5171 (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))
5179 * Matches a stream specifier (but ignores requested index).
5181 * @param indexptr set to point to the requested stream index if there is one
5183 * @return <0 on error
5184 * 0 if st is NOT a matching stream
5185 * >0 if st is a matching stream
5187 static int match_stream_specifier(AVFormatContext *s, AVStream *st,
5188 const char *spec, const char **indexptr, AVProgram **p)
5190 int match = 1; /* Stores if the specifier matches so far. */
5192 if (*spec <= '9' && *spec >= '0') { /* opt:index */
5196 } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
5197 *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5198 enum AVMediaType type;
5202 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
5203 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
5204 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
5205 case 'd': type = AVMEDIA_TYPE_DATA; break;
5206 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
5207 case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5208 default: av_assert0(0);
5210 if (*spec && *spec++ != ':') /* If we are not at the end, then another specifier must follow. */
5211 return AVERROR(EINVAL);
5213 #if FF_API_LAVF_AVCTX
5214 FF_DISABLE_DEPRECATION_WARNINGS
5215 if (type != st->codecpar->codec_type
5216 && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
5218 FF_ENABLE_DEPRECATION_WARNINGS
5220 if (type != st->codecpar->codec_type)
5223 if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
5225 } else if (*spec == 'p' && *(spec + 1) == ':') {
5230 prog_id = strtol(spec, &endptr, 0);
5231 /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
5232 if (spec == endptr || (*endptr && *endptr++ != ':'))
5233 return AVERROR(EINVAL);
5236 for (i = 0; i < s->nb_programs; i++) {
5237 if (s->programs[i]->id != prog_id)
5240 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
5241 if (st->index == s->programs[i]->stream_index[j]) {
5244 *p = s->programs[i];
5253 } else if (*spec == '#' ||
5254 (*spec == 'i' && *(spec + 1) == ':')) {
5257 spec += 1 + (*spec == 'i');
5258 stream_id = strtol(spec, &endptr, 0);
5259 if (spec == endptr || *endptr) /* Disallow empty id and make sure we are at the end. */
5260 return AVERROR(EINVAL);
5261 return match && (stream_id == st->id);
5262 } else if (*spec == 'm' && *(spec + 1) == ':') {
5263 AVDictionaryEntry *tag;
5269 val = strchr(spec, ':');
5271 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
5273 return AVERROR(ENOMEM);
5275 tag = av_dict_get(st->metadata, key, NULL, 0);
5277 if (!val || !strcmp(tag->value, val + 1))
5286 return match && ret;
5287 } else if (*spec == 'u' && *(spec + 1) == '\0') {
5288 AVCodecParameters *par = st->codecpar;
5289 #if FF_API_LAVF_AVCTX
5290 FF_DISABLE_DEPRECATION_WARNINGS
5291 AVCodecContext *codec = st->codec;
5292 FF_ENABLE_DEPRECATION_WARNINGS
5295 switch (par->codec_type) {
5296 case AVMEDIA_TYPE_AUDIO:
5297 val = par->sample_rate && par->channels;
5298 #if FF_API_LAVF_AVCTX
5299 val = val || (codec->sample_rate && codec->channels);
5301 if (par->format == AV_SAMPLE_FMT_NONE
5302 #if FF_API_LAVF_AVCTX
5303 && codec->sample_fmt == AV_SAMPLE_FMT_NONE
5308 case AVMEDIA_TYPE_VIDEO:
5309 val = par->width && par->height;
5310 #if FF_API_LAVF_AVCTX
5311 val = val || (codec->width && codec->height);
5313 if (par->format == AV_PIX_FMT_NONE
5314 #if FF_API_LAVF_AVCTX
5315 && codec->pix_fmt == AV_PIX_FMT_NONE
5320 case AVMEDIA_TYPE_UNKNOWN:
5327 #if FF_API_LAVF_AVCTX
5328 return match && ((par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0);
5330 return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
5333 return AVERROR(EINVAL);
5341 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
5346 const char *indexptr = NULL;
5347 AVProgram *p = NULL;
5350 ret = match_stream_specifier(s, st, spec, &indexptr, &p);
5357 index = strtol(indexptr, &endptr, 0);
5358 if (*endptr) { /* We can't have anything after the requested index. */
5359 ret = AVERROR(EINVAL);
5363 /* This is not really needed but saves us a loop for simple stream index specifiers. */
5364 if (spec == indexptr)
5365 return (index == st->index);
5367 /* If we requested a matching stream index, we have to ensure st is that. */
5368 nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
5369 for (int i = 0; i < nb_streams && index >= 0; i++) {
5370 AVStream *candidate = p ? s->streams[p->stream_index[i]] : s->streams[i];
5371 ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
5374 if (ret > 0 && index-- == 0 && st == candidate)
5380 if (ret == AVERROR(EINVAL))
5381 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
5385 int ff_generate_avci_extradata(AVStream *st)
5387 static const uint8_t avci100_1080p_extradata[] = {
5389 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5390 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5391 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5392 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
5393 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
5394 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
5395 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
5396 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
5397 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
5399 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5402 static const uint8_t avci100_1080i_extradata[] = {
5404 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5405 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5406 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5407 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
5408 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
5409 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
5410 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
5411 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
5412 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
5413 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
5414 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5416 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5419 static const uint8_t avci50_1080p_extradata[] = {
5421 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5422 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5423 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5424 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5425 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5426 0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
5427 0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
5428 0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
5429 0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
5431 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5434 static const uint8_t avci50_1080i_extradata[] = {
5436 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5437 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5438 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5439 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
5440 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
5441 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
5442 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
5443 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
5444 0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
5445 0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5446 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
5448 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5451 static const uint8_t avci100_720p_extradata[] = {
5453 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5454 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
5455 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
5456 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
5457 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
5458 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
5459 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
5460 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
5461 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
5462 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
5464 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
5467 static const uint8_t avci50_720p_extradata[] = {
5469 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
5470 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5471 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5472 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5473 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5474 0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
5475 0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
5476 0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
5477 0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
5479 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5483 const uint8_t *data = NULL;
5486 if (st->codecpar->width == 1920) {
5487 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5488 data = avci100_1080p_extradata;
5489 size = sizeof(avci100_1080p_extradata);
5491 data = avci100_1080i_extradata;
5492 size = sizeof(avci100_1080i_extradata);
5494 } else if (st->codecpar->width == 1440) {
5495 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5496 data = avci50_1080p_extradata;
5497 size = sizeof(avci50_1080p_extradata);
5499 data = avci50_1080i_extradata;
5500 size = sizeof(avci50_1080i_extradata);
5502 } else if (st->codecpar->width == 1280) {
5503 data = avci100_720p_extradata;
5504 size = sizeof(avci100_720p_extradata);
5505 } else if (st->codecpar->width == 960) {
5506 data = avci50_720p_extradata;
5507 size = sizeof(avci50_720p_extradata);
5513 if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
5515 memcpy(st->codecpar->extradata, data, size);
5520 uint8_t *av_stream_get_side_data(const AVStream *st,
5521 enum AVPacketSideDataType type, buffer_size_t *size)
5525 for (i = 0; i < st->nb_side_data; i++) {
5526 if (st->side_data[i].type == type) {
5528 *size = st->side_data[i].size;
5529 return st->side_data[i].data;
5537 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
5538 uint8_t *data, size_t size)
5540 AVPacketSideData *sd, *tmp;
5543 for (i = 0; i < st->nb_side_data; i++) {
5544 sd = &st->side_data[i];
5546 if (sd->type == type) {
5547 av_freep(&sd->data);
5554 if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
5555 return AVERROR(ERANGE);
5557 tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5559 return AVERROR(ENOMEM);
5562 st->side_data = tmp;
5565 sd = &st->side_data[st->nb_side_data - 1];
5573 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
5577 uint8_t *data = av_malloc(size);
5582 ret = av_stream_add_side_data(st, type, data, size);
5591 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
5594 const AVBitStreamFilter *bsf;
5597 av_assert0(!st->internal->bsfc);
5599 if (!(bsf = av_bsf_get_by_name(name))) {
5600 av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5601 return AVERROR_BSF_NOT_FOUND;
5604 if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
5607 bsfc->time_base_in = st->time_base;
5608 if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
5613 if (args && bsfc->filter->priv_class) {
5614 const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
5615 const char * shorthand[2] = {NULL};
5618 shorthand[0] = opt->name;
5620 if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
5626 if ((ret = av_bsf_init(bsfc)) < 0) {
5631 st->internal->bsfc = bsfc;
5633 av_log(NULL, AV_LOG_VERBOSE,
5634 "Automatically inserted bitstream filter '%s'; args='%s'\n",
5635 name, args ? args : "");
5639 int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
5642 return AVERROR(EINVAL);
5644 if (!(s->oformat->flags & AVFMT_NOFILE))
5645 return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
5649 void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
5652 s->io_close(s, *pb);
5656 int ff_is_http_proto(char *filename) {
5657 const char *proto = avio_find_protocol_name(filename);
5658 return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
5661 int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
5663 AVDictionaryEntry *entry;
5664 int64_t parsed_timestamp;
5666 if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
5667 if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
5668 *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
5671 av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
5678 int ff_standardize_creation_time(AVFormatContext *s)
5681 int ret = ff_parse_creation_time_metadata(s, ×tamp, 0);
5683 return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5687 int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5692 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
5694 if (size != AVPALETTE_SIZE) {
5695 av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
5696 return AVERROR_INVALIDDATA;
5698 memcpy(palette, side_data, AVPALETTE_SIZE);
5702 if (ret == CONTAINS_PAL) {
5704 for (i = 0; i < AVPALETTE_COUNT; i++)
5705 palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
5712 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
5717 ret = av_bprint_finalize(buf, &str);
5720 if (!av_bprint_is_complete(buf)) {
5722 return AVERROR(ENOMEM);
5725 par->extradata = str;
5726 /* Note: the string is NUL terminated (so extradata can be read as a
5727 * string), but the ending character is not accounted in the size (in
5728 * binary formats you are likely not supposed to mux that character). When
5729 * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
5731 par->extradata_size = buf->len;
5735 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
5736 AVStream *ost, const AVStream *ist,
5737 enum AVTimebaseSource copy_tb)
5739 //TODO: use [io]st->internal->avctx
5740 const AVCodecContext *dec_ctx;
5741 AVCodecContext *enc_ctx;
5743 #if FF_API_LAVF_AVCTX
5744 FF_DISABLE_DEPRECATION_WARNINGS
5745 dec_ctx = ist->codec;
5746 enc_ctx = ost->codec;
5747 FF_ENABLE_DEPRECATION_WARNINGS
5749 dec_ctx = ist->internal->avctx;
5750 enc_ctx = ost->internal->avctx;
5753 enc_ctx->time_base = ist->time_base;
5755 * Avi is a special case here because it supports variable fps but
5756 * having the fps and timebase differe significantly adds quite some
5759 if (!strcmp(ofmt->name, "avi")) {
5760 #if FF_API_R_FRAME_RATE
5761 if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
5762 && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
5763 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
5764 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
5765 && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
5766 || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
5767 enc_ctx->time_base.num = ist->r_frame_rate.den;
5768 enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
5769 enc_ctx->ticks_per_frame = 2;
5772 if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
5773 && av_q2d(ist->time_base) < 1.0/500
5774 || copy_tb == AVFMT_TBCF_DECODER) {
5775 enc_ctx->time_base = dec_ctx->time_base;
5776 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5777 enc_ctx->time_base.den *= 2;
5778 enc_ctx->ticks_per_frame = 2;
5780 } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5781 && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5782 if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
5783 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
5784 && av_q2d(ist->time_base) < 1.0/500
5785 || copy_tb == AVFMT_TBCF_DECODER) {
5786 enc_ctx->time_base = dec_ctx->time_base;
5787 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5791 if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5792 && dec_ctx->time_base.num < dec_ctx->time_base.den
5793 && dec_ctx->time_base.num > 0
5794 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
5795 enc_ctx->time_base = dec_ctx->time_base;
5798 av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
5799 enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
5804 AVRational av_stream_get_codec_timebase(const AVStream *st)
5806 // See avformat_transfer_internal_stream_timing_info() TODO.
5807 #if FF_API_LAVF_AVCTX
5808 FF_DISABLE_DEPRECATION_WARNINGS
5809 return st->codec->time_base;
5810 FF_ENABLE_DEPRECATION_WARNINGS
5812 return st->internal->avctx->time_base;
5816 void ff_format_set_url(AVFormatContext *s, char *url)
5821 #if FF_API_FORMAT_FILENAME
5822 FF_DISABLE_DEPRECATION_WARNINGS
5823 av_strlcpy(s->filename, url, sizeof(s->filename));
5824 FF_ENABLE_DEPRECATION_WARNINGS