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 &&
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 #if FF_API_LAVF_FFSERVER
119 FF_DISABLE_DEPRECATION_WARNINGS
120 MAKE_ACCESSORS(AVStream, stream, char *, recommended_encoder_configuration)
121 FF_ENABLE_DEPRECATION_WARNINGS
123 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
124 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
125 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
126 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
127 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
128 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
129 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
130 #if FF_API_OLD_OPEN_CALLBACKS
131 FF_DISABLE_DEPRECATION_WARNINGS
132 MAKE_ACCESSORS(AVFormatContext, format, AVOpenCallback, open_cb)
133 FF_ENABLE_DEPRECATION_WARNINGS
137 int64_t av_stream_get_end_pts(const AVStream *st)
139 if (st->internal->priv_pts) {
140 return st->internal->priv_pts->val;
142 return AV_NOPTS_VALUE;
145 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
150 void av_format_inject_global_side_data(AVFormatContext *s)
153 s->internal->inject_global_side_data = 1;
154 for (i = 0; i < s->nb_streams; i++) {
155 AVStream *st = s->streams[i];
156 st->internal->inject_global_side_data = 1;
160 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
162 av_assert0(!dst->codec_whitelist &&
163 !dst->format_whitelist &&
164 !dst->protocol_whitelist &&
165 !dst->protocol_blacklist);
166 dst-> codec_whitelist = av_strdup(src->codec_whitelist);
167 dst->format_whitelist = av_strdup(src->format_whitelist);
168 dst->protocol_whitelist = av_strdup(src->protocol_whitelist);
169 dst->protocol_blacklist = av_strdup(src->protocol_blacklist);
170 if ( (src-> codec_whitelist && !dst-> codec_whitelist)
171 || (src-> format_whitelist && !dst-> format_whitelist)
172 || (src->protocol_whitelist && !dst->protocol_whitelist)
173 || (src->protocol_blacklist && !dst->protocol_blacklist)) {
174 av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
175 return AVERROR(ENOMEM);
180 static const AVCodec *find_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
182 #if FF_API_LAVF_AVCTX
183 FF_DISABLE_DEPRECATION_WARNINGS
184 if (st->codec->codec)
185 return st->codec->codec;
186 FF_ENABLE_DEPRECATION_WARNINGS
189 switch (st->codecpar->codec_type) {
190 case AVMEDIA_TYPE_VIDEO:
191 if (s->video_codec) return s->video_codec;
193 case AVMEDIA_TYPE_AUDIO:
194 if (s->audio_codec) return s->audio_codec;
196 case AVMEDIA_TYPE_SUBTITLE:
197 if (s->subtitle_codec) return s->subtitle_codec;
201 return avcodec_find_decoder(codec_id);
204 static const AVCodec *find_probe_decoder(AVFormatContext *s, const AVStream *st, enum AVCodecID codec_id)
206 const AVCodec *codec;
208 #if CONFIG_H264_DECODER
209 /* Other parts of the code assume this decoder to be used for h264,
210 * so force it if possible. */
211 if (codec_id == AV_CODEC_ID_H264)
212 return avcodec_find_decoder_by_name("h264");
215 codec = find_decoder(s, st, codec_id);
219 if (codec->capabilities & AV_CODEC_CAP_AVOID_PROBING) {
220 const AVCodec *probe_codec = NULL;
222 while ((probe_codec = av_codec_iterate(&iter))) {
223 if (probe_codec->id == codec->id &&
224 av_codec_is_decoder(probe_codec) &&
225 !(probe_codec->capabilities & (AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_EXPERIMENTAL))) {
234 #if FF_API_FORMAT_GET_SET
235 int av_format_get_probe_score(const AVFormatContext *s)
237 return s->probe_score;
241 /* an arbitrarily chosen "sane" max packet size -- 50M */
242 #define SANE_CHUNK_SIZE (50000000)
244 int ffio_limit(AVIOContext *s, int size)
246 if (s->maxsize>= 0) {
247 int64_t remaining= s->maxsize - avio_tell(s);
248 if (remaining < size) {
249 int64_t newsize = avio_size(s);
250 if (!s->maxsize || s->maxsize<newsize)
251 s->maxsize = newsize - !newsize;
252 remaining= s->maxsize - avio_tell(s);
253 remaining= FFMAX(remaining, 0);
256 if (s->maxsize >= 0 && remaining < size && size > 1) {
257 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG,
258 "Truncating packet of size %d to %"PRId64"\n",
259 size, remaining + !remaining);
260 size = remaining + !remaining;
266 /* Read the data in sane-sized chunks and append to pkt.
267 * Return the number of bytes read or an error. */
268 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
270 int orig_size = pkt->size;
274 int prev_size = pkt->size;
277 /* When the caller requests a lot of data, limit it to the amount
278 * left in file or SANE_CHUNK_SIZE when it is not known. */
280 if (read_size > SANE_CHUNK_SIZE/10) {
281 read_size = ffio_limit(s, read_size);
282 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
284 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
287 ret = av_grow_packet(pkt, read_size);
291 ret = avio_read(s, pkt->data + prev_size, read_size);
292 if (ret != read_size) {
293 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
300 pkt->flags |= AV_PKT_FLAG_CORRUPT;
303 av_packet_unref(pkt);
304 return pkt->size > orig_size ? pkt->size - orig_size : ret;
307 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
312 pkt->pos = avio_tell(s);
314 return append_packet_chunked(s, pkt, size);
317 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
320 return av_get_packet(s, pkt, size);
321 return append_packet_chunked(s, pkt, size);
324 int av_filename_number_test(const char *filename)
328 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
331 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
334 static const struct {
337 enum AVMediaType type;
339 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
340 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
341 { "aptx", AV_CODEC_ID_APTX, AVMEDIA_TYPE_AUDIO },
342 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
343 { "dvbsub", AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
344 { "dvbtxt", AV_CODEC_ID_DVB_TELETEXT,AVMEDIA_TYPE_SUBTITLE },
345 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
346 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
347 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
348 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
349 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
350 { "mjpeg_2000",AV_CODEC_ID_JPEG2000, AVMEDIA_TYPE_VIDEO },
351 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
352 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
353 { "truehd", AV_CODEC_ID_TRUEHD, AVMEDIA_TYPE_AUDIO },
357 const AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
361 av_log(s, AV_LOG_DEBUG,
362 "Probe with size=%d, packets=%d detected %s with score=%d\n",
363 pd->buf_size, s->max_probe_packets - st->probe_packets,
365 for (i = 0; fmt_id_type[i].name; i++) {
366 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
367 if (fmt_id_type[i].type != AVMEDIA_TYPE_AUDIO &&
368 st->codecpar->sample_rate)
370 if (st->internal->request_probe > score &&
371 st->codecpar->codec_id != fmt_id_type[i].id)
373 st->codecpar->codec_id = fmt_id_type[i].id;
374 st->codecpar->codec_type = fmt_id_type[i].type;
375 st->internal->need_context_update = 1;
376 #if FF_API_LAVF_AVCTX
377 FF_DISABLE_DEPRECATION_WARNINGS
378 st->codec->codec_type = st->codecpar->codec_type;
379 st->codec->codec_id = st->codecpar->codec_id;
380 FF_ENABLE_DEPRECATION_WARNINGS
389 /************************************************************/
390 /* input media file */
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 static int update_stream_avctx(AVFormatContext *s)
470 for (i = 0; i < s->nb_streams; i++) {
471 AVStream *st = s->streams[i];
473 if (!st->internal->need_context_update)
476 /* close parser, because it depends on the codec */
477 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
478 av_parser_close(st->parser);
482 /* update internal codec context, for the parser */
483 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
487 #if FF_API_LAVF_AVCTX
488 FF_DISABLE_DEPRECATION_WARNINGS
489 /* update deprecated public codec context */
490 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
493 FF_ENABLE_DEPRECATION_WARNINGS
496 st->internal->need_context_update = 0;
502 int avformat_open_input(AVFormatContext **ps, const char *filename,
503 ff_const59 AVInputFormat *fmt, AVDictionary **options)
505 AVFormatContext *s = *ps;
507 AVDictionary *tmp = NULL;
508 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
510 if (!s && !(s = avformat_alloc_context()))
511 return AVERROR(ENOMEM);
513 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
514 return AVERROR(EINVAL);
520 av_dict_copy(&tmp, *options, 0);
522 if (s->pb) // must be before any goto fail
523 s->flags |= AVFMT_FLAG_CUSTOM_IO;
525 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
528 if (!(s->url = av_strdup(filename ? filename : ""))) {
529 ret = AVERROR(ENOMEM);
533 #if FF_API_FORMAT_FILENAME
534 FF_DISABLE_DEPRECATION_WARNINGS
535 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
536 FF_ENABLE_DEPRECATION_WARNINGS
538 if ((ret = init_input(s, filename, &tmp)) < 0)
540 s->probe_score = ret;
542 if (!s->protocol_whitelist && s->pb && s->pb->protocol_whitelist) {
543 s->protocol_whitelist = av_strdup(s->pb->protocol_whitelist);
544 if (!s->protocol_whitelist) {
545 ret = AVERROR(ENOMEM);
550 if (!s->protocol_blacklist && s->pb && s->pb->protocol_blacklist) {
551 s->protocol_blacklist = av_strdup(s->pb->protocol_blacklist);
552 if (!s->protocol_blacklist) {
553 ret = AVERROR(ENOMEM);
558 if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
559 av_log(s, AV_LOG_ERROR, "Format not on whitelist \'%s\'\n", s->format_whitelist);
560 ret = AVERROR(EINVAL);
564 avio_skip(s->pb, s->skip_initial_bytes);
566 /* Check filename in case an image number is expected. */
567 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
568 if (!av_filename_number_test(filename)) {
569 ret = AVERROR(EINVAL);
574 s->duration = s->start_time = AV_NOPTS_VALUE;
576 /* Allocate private data. */
577 if (s->iformat->priv_data_size > 0) {
578 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
579 ret = AVERROR(ENOMEM);
582 if (s->iformat->priv_class) {
583 *(const AVClass **) s->priv_data = s->iformat->priv_class;
584 av_opt_set_defaults(s->priv_data);
585 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
590 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
592 ff_id3v2_read_dict(s->pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
595 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
596 if ((ret = s->iformat->read_header(s)) < 0)
600 s->metadata = s->internal->id3v2_meta;
601 s->internal->id3v2_meta = NULL;
602 } else if (s->internal->id3v2_meta) {
603 av_log(s, AV_LOG_WARNING, "Discarding ID3 tags because more suitable tags were found.\n");
604 av_dict_free(&s->internal->id3v2_meta);
607 if (id3v2_extra_meta) {
608 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
609 !strcmp(s->iformat->name, "tta") || !strcmp(s->iformat->name, "wav")) {
610 if ((ret = ff_id3v2_parse_apic(s, id3v2_extra_meta)) < 0)
612 if ((ret = ff_id3v2_parse_chapters(s, id3v2_extra_meta)) < 0)
614 if ((ret = ff_id3v2_parse_priv(s, id3v2_extra_meta)) < 0)
617 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
619 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
621 if ((ret = avformat_queue_attached_pictures(s)) < 0)
624 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
625 s->internal->data_offset = avio_tell(s->pb);
627 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
629 update_stream_avctx(s);
631 for (i = 0; i < s->nb_streams; i++)
632 s->streams[i]->internal->orig_codec_id = s->streams[i]->codecpar->codec_id;
635 av_dict_free(options);
642 if (s->iformat->read_close)
643 s->iformat->read_close(s);
645 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
647 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
649 avformat_free_context(s);
654 /*******************************************************/
656 static void force_codec_ids(AVFormatContext *s, AVStream *st)
658 switch (st->codecpar->codec_type) {
659 case AVMEDIA_TYPE_VIDEO:
660 if (s->video_codec_id)
661 st->codecpar->codec_id = s->video_codec_id;
663 case AVMEDIA_TYPE_AUDIO:
664 if (s->audio_codec_id)
665 st->codecpar->codec_id = s->audio_codec_id;
667 case AVMEDIA_TYPE_SUBTITLE:
668 if (s->subtitle_codec_id)
669 st->codecpar->codec_id = s->subtitle_codec_id;
671 case AVMEDIA_TYPE_DATA:
672 if (s->data_codec_id)
673 st->codecpar->codec_id = s->data_codec_id;
678 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
680 if (st->internal->request_probe>0) {
681 AVProbeData *pd = &st->internal->probe_data;
683 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
687 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
689 av_log(s, AV_LOG_WARNING,
690 "Failed to reallocate probe buffer for stream %d\n",
695 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
696 pd->buf_size += pkt->size;
697 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
700 st->probe_packets = 0;
702 av_log(s, AV_LOG_WARNING,
703 "nothing to probe for stream %d\n", st->index);
707 end= s->internal->raw_packet_buffer_remaining_size <= 0
708 || st->probe_packets<= 0;
710 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
711 int score = set_codec_from_probe_data(s, st, pd);
712 if ( (st->codecpar->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
716 st->internal->request_probe = -1;
717 if (st->codecpar->codec_id != AV_CODEC_ID_NONE) {
718 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
720 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
722 force_codec_ids(s, st);
728 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
730 int64_t ref = pkt->dts;
731 int i, pts_wrap_behavior;
732 int64_t pts_wrap_reference;
733 AVProgram *first_program;
735 if (ref == AV_NOPTS_VALUE)
737 if (st->internal->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
739 ref &= (1LL << st->pts_wrap_bits)-1;
741 // reference time stamp should be 60 s before first time stamp
742 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
743 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
744 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
745 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
746 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
748 first_program = av_find_program_from_stream(s, NULL, stream_index);
750 if (!first_program) {
751 int default_stream_index = av_find_default_stream_index(s);
752 if (s->streams[default_stream_index]->internal->pts_wrap_reference == AV_NOPTS_VALUE) {
753 for (i = 0; i < s->nb_streams; i++) {
754 if (av_find_program_from_stream(s, NULL, i))
756 s->streams[i]->internal->pts_wrap_reference = pts_wrap_reference;
757 s->streams[i]->internal->pts_wrap_behavior = pts_wrap_behavior;
761 st->internal->pts_wrap_reference = s->streams[default_stream_index]->internal->pts_wrap_reference;
762 st->internal->pts_wrap_behavior = s->streams[default_stream_index]->internal->pts_wrap_behavior;
766 AVProgram *program = first_program;
768 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
769 pts_wrap_reference = program->pts_wrap_reference;
770 pts_wrap_behavior = program->pts_wrap_behavior;
773 program = av_find_program_from_stream(s, program, stream_index);
776 // update every program with differing pts_wrap_reference
777 program = first_program;
779 if (program->pts_wrap_reference != pts_wrap_reference) {
780 for (i = 0; i<program->nb_stream_indexes; i++) {
781 s->streams[program->stream_index[i]]->internal->pts_wrap_reference = pts_wrap_reference;
782 s->streams[program->stream_index[i]]->internal->pts_wrap_behavior = pts_wrap_behavior;
785 program->pts_wrap_reference = pts_wrap_reference;
786 program->pts_wrap_behavior = pts_wrap_behavior;
788 program = av_find_program_from_stream(s, program, stream_index);
794 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
804 AVPacketList *pktl = s->internal->raw_packet_buffer;
805 const AVPacket *pkt1;
808 st = s->streams[pktl->pkt.stream_index];
809 if (s->internal->raw_packet_buffer_remaining_size <= 0)
810 if ((err = probe_codec(s, st, NULL)) < 0)
812 if (st->internal->request_probe <= 0) {
813 avpriv_packet_list_get(&s->internal->raw_packet_buffer,
814 &s->internal->raw_packet_buffer_end, pkt);
815 s->internal->raw_packet_buffer_remaining_size += pkt->size;
820 ret = s->iformat->read_packet(s, pkt);
822 av_packet_unref(pkt);
824 /* Some demuxers return FFERROR_REDO when they consume
825 data and discard it (ignored streams, junk, extradata).
826 We must re-call the demuxer to get the real packet. */
827 if (ret == FFERROR_REDO)
829 if (!pktl || ret == AVERROR(EAGAIN))
831 for (i = 0; i < s->nb_streams; i++) {
833 if (st->probe_packets || st->internal->request_probe > 0)
834 if ((err = probe_codec(s, st, NULL)) < 0)
836 av_assert0(st->internal->request_probe <= 0);
841 err = av_packet_make_refcounted(pkt);
843 av_packet_unref(pkt);
847 if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
848 av_log(s, AV_LOG_WARNING,
849 "Packet corrupt (stream = %d, dts = %s)",
850 pkt->stream_index, av_ts2str(pkt->dts));
851 if (s->flags & AVFMT_FLAG_DISCARD_CORRUPT) {
852 av_log(s, AV_LOG_WARNING, ", dropping it.\n");
853 av_packet_unref(pkt);
856 av_log(s, AV_LOG_WARNING, ".\n");
859 av_assert0(pkt->stream_index < (unsigned)s->nb_streams &&
860 "Invalid stream index.\n");
862 st = s->streams[pkt->stream_index];
864 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
865 // correct first time stamps to negative values
866 if (!is_relative(st->first_dts))
867 st->first_dts = wrap_timestamp(st, st->first_dts);
868 if (!is_relative(st->start_time))
869 st->start_time = wrap_timestamp(st, st->start_time);
870 if (!is_relative(st->cur_dts))
871 st->cur_dts = wrap_timestamp(st, st->cur_dts);
874 pkt->dts = wrap_timestamp(st, pkt->dts);
875 pkt->pts = wrap_timestamp(st, pkt->pts);
877 force_codec_ids(s, st);
879 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
880 if (s->use_wallclock_as_timestamps)
881 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
883 if (!pktl && st->internal->request_probe <= 0)
886 err = avpriv_packet_list_put(&s->internal->raw_packet_buffer,
887 &s->internal->raw_packet_buffer_end,
890 av_packet_unref(pkt);
893 pkt1 = &s->internal->raw_packet_buffer_end->pkt;
894 s->internal->raw_packet_buffer_remaining_size -= pkt1->size;
896 if ((err = probe_codec(s, st, pkt1)) < 0)
902 /**********************************************************/
904 static int determinable_frame_size(AVCodecContext *avctx)
906 switch(avctx->codec_id) {
907 case AV_CODEC_ID_MP1:
908 case AV_CODEC_ID_MP2:
909 case AV_CODEC_ID_MP3:
910 case AV_CODEC_ID_CODEC2:
918 * Return the frame duration in seconds. Return 0 if not available.
920 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
921 AVCodecParserContext *pc, AVPacket *pkt)
923 AVRational codec_framerate = s->iformat ? st->internal->avctx->framerate :
924 av_mul_q(av_inv_q(st->internal->avctx->time_base), (AVRational){1, st->internal->avctx->ticks_per_frame});
925 int frame_size, sample_rate;
927 #if FF_API_LAVF_AVCTX
928 FF_DISABLE_DEPRECATION_WARNINGS
929 if ((!codec_framerate.den || !codec_framerate.num) && st->codec->time_base.den && st->codec->time_base.num)
930 codec_framerate = av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
931 FF_ENABLE_DEPRECATION_WARNINGS
936 switch (st->codecpar->codec_type) {
937 case AVMEDIA_TYPE_VIDEO:
938 if (st->r_frame_rate.num && !pc && s->iformat) {
939 *pnum = st->r_frame_rate.den;
940 *pden = st->r_frame_rate.num;
941 } else if (st->time_base.num * 1000LL > st->time_base.den) {
942 *pnum = st->time_base.num;
943 *pden = st->time_base.den;
944 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
945 av_assert0(st->internal->avctx->ticks_per_frame);
946 av_reduce(pnum, pden,
948 codec_framerate.num * (int64_t)st->internal->avctx->ticks_per_frame,
951 if (pc && pc->repeat_pict) {
952 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
953 av_reduce(pnum, pden,
954 (*pnum) * (1LL + pc->repeat_pict),
958 /* If this codec can be interlaced or progressive then we need
959 * a parser to compute duration of a packet. Thus if we have
960 * no parser in such case leave duration undefined. */
961 if (st->internal->avctx->ticks_per_frame > 1 && !pc)
965 case AVMEDIA_TYPE_AUDIO:
966 if (st->internal->avctx_inited) {
967 frame_size = av_get_audio_frame_duration(st->internal->avctx, pkt->size);
968 sample_rate = st->internal->avctx->sample_rate;
970 frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
971 sample_rate = st->codecpar->sample_rate;
973 if (frame_size <= 0 || sample_rate <= 0)
983 int ff_is_intra_only(enum AVCodecID id)
985 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
988 if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
989 !(d->props & AV_CODEC_PROP_INTRA_ONLY))
994 static int has_decode_delay_been_guessed(AVStream *st)
996 if (st->codecpar->codec_id != AV_CODEC_ID_H264) return 1;
997 if (!st->internal->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
999 #if CONFIG_H264_DECODER
1000 if (st->internal->avctx->has_b_frames &&
1001 avpriv_h264_has_num_reorder_frames(st->internal->avctx) == st->internal->avctx->has_b_frames)
1004 if (st->internal->avctx->has_b_frames<3)
1005 return st->internal->nb_decoded_frames >= 7;
1006 else if (st->internal->avctx->has_b_frames<4)
1007 return st->internal->nb_decoded_frames >= 18;
1009 return st->internal->nb_decoded_frames >= 20;
1012 static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
1016 if (pktl == s->internal->packet_buffer_end)
1017 return s->internal->parse_queue;
1021 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
1022 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1023 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1026 int delay = st->internal->avctx->has_b_frames;
1029 if (dts == AV_NOPTS_VALUE) {
1030 int64_t best_score = INT64_MAX;
1031 for (i = 0; i<delay; i++) {
1032 if (st->internal->pts_reorder_error_count[i]) {
1033 int64_t score = st->internal->pts_reorder_error[i] / st->internal->pts_reorder_error_count[i];
1034 if (score < best_score) {
1036 dts = pts_buffer[i];
1041 for (i = 0; i<delay; i++) {
1042 if (pts_buffer[i] != AV_NOPTS_VALUE) {
1043 int64_t diff = FFABS(pts_buffer[i] - dts)
1044 + (uint64_t)st->internal->pts_reorder_error[i];
1045 diff = FFMAX(diff, st->internal->pts_reorder_error[i]);
1046 st->internal->pts_reorder_error[i] = diff;
1047 st->internal->pts_reorder_error_count[i]++;
1048 if (st->internal->pts_reorder_error_count[i] > 250) {
1049 st->internal->pts_reorder_error[i] >>= 1;
1050 st->internal->pts_reorder_error_count[i] >>= 1;
1057 if (dts == AV_NOPTS_VALUE)
1058 dts = pts_buffer[0];
1064 * Updates the dts of packets of a stream in pkt_buffer, by re-ordering the pts
1065 * of the packets in a window.
1067 static void update_dts_from_pts(AVFormatContext *s, int stream_index,
1068 AVPacketList *pkt_buffer)
1070 AVStream *st = s->streams[stream_index];
1071 int delay = st->internal->avctx->has_b_frames;
1074 int64_t pts_buffer[MAX_REORDER_DELAY+1];
1076 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1077 pts_buffer[i] = AV_NOPTS_VALUE;
1079 for (; pkt_buffer; pkt_buffer = get_next_pkt(s, st, pkt_buffer)) {
1080 if (pkt_buffer->pkt.stream_index != stream_index)
1083 if (pkt_buffer->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1084 pts_buffer[0] = pkt_buffer->pkt.pts;
1085 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1086 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1088 pkt_buffer->pkt.dts = select_from_pts_buffer(st, pts_buffer, pkt_buffer->pkt.dts);
1093 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1094 int64_t dts, int64_t pts, AVPacket *pkt)
1096 AVStream *st = s->streams[stream_index];
1097 AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1098 AVPacketList *pktl_it;
1102 if (st->first_dts != AV_NOPTS_VALUE ||
1103 dts == AV_NOPTS_VALUE ||
1104 st->cur_dts == AV_NOPTS_VALUE ||
1105 st->cur_dts < INT_MIN + RELATIVE_TS_BASE ||
1109 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1111 shift = (uint64_t)st->first_dts - RELATIVE_TS_BASE;
1113 if (is_relative(pts))
1116 for (pktl_it = pktl; pktl_it; pktl_it = get_next_pkt(s, st, pktl_it)) {
1117 if (pktl_it->pkt.stream_index != stream_index)
1119 if (is_relative(pktl_it->pkt.pts))
1120 pktl_it->pkt.pts += shift;
1122 if (is_relative(pktl_it->pkt.dts))
1123 pktl_it->pkt.dts += shift;
1125 if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
1126 st->start_time = pktl_it->pkt.pts;
1127 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1128 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));
1132 if (has_decode_delay_been_guessed(st)) {
1133 update_dts_from_pts(s, stream_index, pktl);
1136 if (st->start_time == AV_NOPTS_VALUE) {
1137 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
1138 st->start_time = pts;
1140 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
1141 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));
1145 static void update_initial_durations(AVFormatContext *s, AVStream *st,
1146 int stream_index, int64_t duration)
1148 AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1149 int64_t cur_dts = RELATIVE_TS_BASE;
1151 if (st->first_dts != AV_NOPTS_VALUE) {
1152 if (st->internal->update_initial_durations_done)
1154 st->internal->update_initial_durations_done = 1;
1155 cur_dts = st->first_dts;
1156 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1157 if (pktl->pkt.stream_index == stream_index) {
1158 if (pktl->pkt.pts != pktl->pkt.dts ||
1159 pktl->pkt.dts != AV_NOPTS_VALUE ||
1162 cur_dts -= duration;
1165 if (pktl && pktl->pkt.dts != st->first_dts) {
1166 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
1167 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1171 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1174 pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
1175 st->first_dts = cur_dts;
1176 } else if (st->cur_dts != RELATIVE_TS_BASE)
1179 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1180 if (pktl->pkt.stream_index != stream_index)
1182 if ((pktl->pkt.pts == pktl->pkt.dts ||
1183 pktl->pkt.pts == AV_NOPTS_VALUE) &&
1184 (pktl->pkt.dts == AV_NOPTS_VALUE ||
1185 pktl->pkt.dts == st->first_dts ||
1186 pktl->pkt.dts == RELATIVE_TS_BASE) &&
1187 !pktl->pkt.duration) {
1188 pktl->pkt.dts = cur_dts;
1189 if (!st->internal->avctx->has_b_frames)
1190 pktl->pkt.pts = cur_dts;
1191 pktl->pkt.duration = duration;
1194 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1197 st->cur_dts = cur_dts;
1200 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1201 AVCodecParserContext *pc, AVPacket *pkt,
1202 int64_t next_dts, int64_t next_pts)
1204 int num, den, presentation_delayed, delay, i;
1206 AVRational duration;
1207 int onein_oneout = st->codecpar->codec_id != AV_CODEC_ID_H264 &&
1208 st->codecpar->codec_id != AV_CODEC_ID_HEVC;
1210 if (s->flags & AVFMT_FLAG_NOFILLIN)
1213 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1214 if (pkt->dts == pkt->pts && st->internal->last_dts_for_order_check != AV_NOPTS_VALUE) {
1215 if (st->internal->last_dts_for_order_check <= pkt->dts) {
1216 st->internal->dts_ordered++;
1218 av_log(s, st->internal->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1219 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1221 st->internal->last_dts_for_order_check);
1222 st->internal->dts_misordered++;
1224 if (st->internal->dts_ordered + st->internal->dts_misordered > 250) {
1225 st->internal->dts_ordered >>= 1;
1226 st->internal->dts_misordered >>= 1;
1230 st->internal->last_dts_for_order_check = pkt->dts;
1231 if (st->internal->dts_ordered < 8*st->internal->dts_misordered && pkt->dts == pkt->pts)
1232 pkt->dts = AV_NOPTS_VALUE;
1235 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1236 pkt->dts = AV_NOPTS_VALUE;
1238 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1239 && !st->internal->avctx->has_b_frames)
1240 //FIXME Set low_delay = 0 when has_b_frames = 1
1241 st->internal->avctx->has_b_frames = 1;
1243 /* do we have a video B-frame ? */
1244 delay = st->internal->avctx->has_b_frames;
1245 presentation_delayed = 0;
1247 /* XXX: need has_b_frame, but cannot get it if the codec is
1248 * not initialized */
1250 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1251 presentation_delayed = 1;
1253 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1254 st->pts_wrap_bits < 63 &&
1255 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1256 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1257 pkt->dts -= 1LL << st->pts_wrap_bits;
1259 pkt->pts += 1LL << st->pts_wrap_bits;
1262 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1263 * We take the conservative approach and discard both.
1264 * Note: If this is misbehaving for an H.264 file, then possibly
1265 * presentation_delayed is not set correctly. */
1266 if (delay == 1 && pkt->dts == pkt->pts &&
1267 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1268 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1269 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1270 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1271 pkt->dts = AV_NOPTS_VALUE;
1274 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1275 if (pkt->duration <= 0) {
1276 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1278 duration = (AVRational) {num, den};
1279 pkt->duration = av_rescale_rnd(1,
1280 num * (int64_t) st->time_base.den,
1281 den * (int64_t) st->time_base.num,
1286 if (pkt->duration > 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1287 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1289 /* Correct timestamps with byte offset if demuxers only have timestamps
1290 * on packet boundaries */
1291 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1292 /* this will estimate bitrate based on this frame's duration and size */
1293 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1294 if (pkt->pts != AV_NOPTS_VALUE)
1296 if (pkt->dts != AV_NOPTS_VALUE)
1300 /* This may be redundant, but it should not hurt. */
1301 if (pkt->dts != AV_NOPTS_VALUE &&
1302 pkt->pts != AV_NOPTS_VALUE &&
1303 pkt->pts > pkt->dts)
1304 presentation_delayed = 1;
1306 if (s->debug & FF_FDEBUG_TS)
1307 av_log(s, AV_LOG_DEBUG,
1308 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1309 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1310 pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1312 /* Interpolate PTS and DTS if they are not present. We skip H264
1313 * currently because delay and has_b_frames are not reliably set. */
1314 if ((delay == 0 || (delay == 1 && pc)) &&
1316 if (presentation_delayed) {
1317 /* DTS = decompression timestamp */
1318 /* PTS = presentation timestamp */
1319 if (pkt->dts == AV_NOPTS_VALUE)
1320 pkt->dts = st->last_IP_pts;
1321 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1322 if (pkt->dts == AV_NOPTS_VALUE)
1323 pkt->dts = st->cur_dts;
1325 /* This is tricky: the dts must be incremented by the duration
1326 * of the frame we are displaying, i.e. the last I- or P-frame. */
1327 if (st->last_IP_duration == 0 && (uint64_t)pkt->duration <= INT32_MAX)
1328 st->last_IP_duration = pkt->duration;
1329 if (pkt->dts != AV_NOPTS_VALUE)
1330 st->cur_dts = av_sat_add64(pkt->dts, st->last_IP_duration);
1331 if (pkt->dts != AV_NOPTS_VALUE &&
1332 pkt->pts == AV_NOPTS_VALUE &&
1333 st->last_IP_duration > 0 &&
1334 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1335 next_dts != next_pts &&
1336 next_pts != AV_NOPTS_VALUE)
1337 pkt->pts = next_dts;
1339 if ((uint64_t)pkt->duration <= INT32_MAX)
1340 st->last_IP_duration = pkt->duration;
1341 st->last_IP_pts = pkt->pts;
1342 /* Cannot compute PTS if not present (we can compute it only
1343 * by knowing the future. */
1344 } else if (pkt->pts != AV_NOPTS_VALUE ||
1345 pkt->dts != AV_NOPTS_VALUE ||
1346 pkt->duration > 0 ) {
1348 /* presentation is not delayed : PTS and DTS are the same */
1349 if (pkt->pts == AV_NOPTS_VALUE)
1350 pkt->pts = pkt->dts;
1351 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1353 if (pkt->pts == AV_NOPTS_VALUE)
1354 pkt->pts = st->cur_dts;
1355 pkt->dts = pkt->pts;
1356 if (pkt->pts != AV_NOPTS_VALUE && duration.num >= 0)
1357 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1361 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
1362 st->internal->pts_buffer[0] = pkt->pts;
1363 for (i = 0; i<delay && st->internal->pts_buffer[i] > st->internal->pts_buffer[i + 1]; i++)
1364 FFSWAP(int64_t, st->internal->pts_buffer[i], st->internal->pts_buffer[i + 1]);
1366 if(has_decode_delay_been_guessed(st))
1367 pkt->dts = select_from_pts_buffer(st, st->internal->pts_buffer, pkt->dts);
1369 // We skipped it above so we try here.
1371 // This should happen on the first packet
1372 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1373 if (pkt->dts > st->cur_dts)
1374 st->cur_dts = pkt->dts;
1376 if (s->debug & FF_FDEBUG_TS)
1377 av_log(s, AV_LOG_DEBUG, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s st:%d (%d)\n",
1378 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), st->index, st->id);
1381 if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || ff_is_intra_only(st->codecpar->codec_id))
1382 pkt->flags |= AV_PKT_FLAG_KEY;
1383 #if FF_API_CONVERGENCE_DURATION
1384 FF_DISABLE_DEPRECATION_WARNINGS
1386 pkt->convergence_duration = pc->convergence_duration;
1387 FF_ENABLE_DEPRECATION_WARNINGS
1392 * Parse a packet, add all split parts to parse_queue.
1394 * @param pkt Packet to parse; must not be NULL.
1395 * @param flush Indicates whether to flush. If set, pkt must be blank.
1397 static int parse_packet(AVFormatContext *s, AVPacket *pkt,
1398 int stream_index, int flush)
1401 AVStream *st = s->streams[stream_index];
1402 uint8_t *data = pkt->data;
1403 int size = pkt->size;
1404 int ret = 0, got_output = flush;
1406 if (size || flush) {
1407 av_init_packet(&out_pkt);
1408 } else if (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1409 // preserve 0-size sync packets
1410 compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1413 while (size > 0 || (flush && got_output)) {
1415 int64_t next_pts = pkt->pts;
1416 int64_t next_dts = pkt->dts;
1418 len = av_parser_parse2(st->parser, st->internal->avctx,
1419 &out_pkt.data, &out_pkt.size, data, size,
1420 pkt->pts, pkt->dts, pkt->pos);
1422 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1424 /* increment read pointer */
1428 got_output = !!out_pkt.size;
1433 if (pkt->buf && out_pkt.data == pkt->data) {
1434 /* reference pkt->buf only when out_pkt.data is guaranteed to point
1435 * to data in it and not in the parser's internal buffer. */
1436 /* XXX: Ensure this is the case with all parsers when st->parser->flags
1437 * is PARSER_FLAG_COMPLETE_FRAMES and check for that instead? */
1438 out_pkt.buf = av_buffer_ref(pkt->buf);
1440 ret = AVERROR(ENOMEM);
1444 ret = av_packet_make_refcounted(&out_pkt);
1449 if (pkt->side_data) {
1450 out_pkt.side_data = pkt->side_data;
1451 out_pkt.side_data_elems = pkt->side_data_elems;
1452 pkt->side_data = NULL;
1453 pkt->side_data_elems = 0;
1456 /* set the duration */
1457 out_pkt.duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1458 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1459 if (st->internal->avctx->sample_rate > 0) {
1461 av_rescale_q_rnd(st->parser->duration,
1462 (AVRational) { 1, st->internal->avctx->sample_rate },
1468 out_pkt.stream_index = st->index;
1469 out_pkt.pts = st->parser->pts;
1470 out_pkt.dts = st->parser->dts;
1471 out_pkt.pos = st->parser->pos;
1472 out_pkt.flags |= pkt->flags & AV_PKT_FLAG_DISCARD;
1474 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1475 out_pkt.pos = st->parser->frame_offset;
1477 if (st->parser->key_frame == 1 ||
1478 (st->parser->key_frame == -1 &&
1479 st->parser->pict_type == AV_PICTURE_TYPE_I))
1480 out_pkt.flags |= AV_PKT_FLAG_KEY;
1482 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1483 out_pkt.flags |= AV_PKT_FLAG_KEY;
1485 compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);
1487 ret = avpriv_packet_list_put(&s->internal->parse_queue,
1488 &s->internal->parse_queue_end,
1491 av_packet_unref(&out_pkt);
1496 /* end of the stream => close and free the parser */
1498 av_parser_close(st->parser);
1503 av_packet_unref(pkt);
1507 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1509 return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
1512 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1514 int ret, i, got_packet = 0;
1515 AVDictionary *metadata = NULL;
1517 while (!got_packet && !s->internal->parse_queue) {
1520 /* read next packet */
1521 ret = ff_read_packet(s, pkt);
1523 if (ret == AVERROR(EAGAIN))
1525 /* flush the parsers */
1526 for (i = 0; i < s->nb_streams; i++) {
1528 if (st->parser && st->need_parsing)
1529 parse_packet(s, pkt, st->index, 1);
1531 /* all remaining packets are now in parse_queue =>
1532 * really terminate parsing */
1536 st = s->streams[pkt->stream_index];
1538 st->event_flags |= AVSTREAM_EVENT_FLAG_NEW_PACKETS;
1540 /* update context if required */
1541 if (st->internal->need_context_update) {
1542 if (avcodec_is_open(st->internal->avctx)) {
1543 av_log(s, AV_LOG_DEBUG, "Demuxer context update while decoder is open, closing and trying to re-open\n");
1544 avcodec_close(st->internal->avctx);
1545 st->internal->info->found_decoder = 0;
1548 /* close parser, because it depends on the codec */
1549 if (st->parser && st->internal->avctx->codec_id != st->codecpar->codec_id) {
1550 av_parser_close(st->parser);
1554 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
1556 av_packet_unref(pkt);
1560 #if FF_API_LAVF_AVCTX
1561 FF_DISABLE_DEPRECATION_WARNINGS
1562 /* update deprecated public codec context */
1563 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
1565 av_packet_unref(pkt);
1568 FF_ENABLE_DEPRECATION_WARNINGS
1571 st->internal->need_context_update = 0;
1574 if (pkt->pts != AV_NOPTS_VALUE &&
1575 pkt->dts != AV_NOPTS_VALUE &&
1576 pkt->pts < pkt->dts) {
1577 av_log(s, AV_LOG_WARNING,
1578 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1580 av_ts2str(pkt->pts),
1581 av_ts2str(pkt->dts),
1584 if (s->debug & FF_FDEBUG_TS)
1585 av_log(s, AV_LOG_DEBUG,
1586 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1588 av_ts2str(pkt->pts),
1589 av_ts2str(pkt->dts),
1590 pkt->size, pkt->duration, pkt->flags);
1592 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1593 st->parser = av_parser_init(st->codecpar->codec_id);
1595 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1596 "%s, packets or times may be invalid.\n",
1597 avcodec_get_name(st->codecpar->codec_id));
1598 /* no parser available: just output the raw packets */
1599 st->need_parsing = AVSTREAM_PARSE_NONE;
1600 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1601 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1602 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1603 st->parser->flags |= PARSER_FLAG_ONCE;
1604 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1605 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1608 if (!st->need_parsing || !st->parser) {
1609 /* no parsing needed: we just output the packet as is */
1610 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1611 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1612 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1613 ff_reduce_index(s, st->index);
1614 av_add_index_entry(st, pkt->pos, pkt->dts,
1615 0, 0, AVINDEX_KEYFRAME);
1618 } else if (st->discard < AVDISCARD_ALL) {
1619 if ((ret = parse_packet(s, pkt, pkt->stream_index, 0)) < 0)
1621 st->codecpar->sample_rate = st->internal->avctx->sample_rate;
1622 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
1623 st->codecpar->channels = st->internal->avctx->channels;
1624 st->codecpar->channel_layout = st->internal->avctx->channel_layout;
1625 st->codecpar->codec_id = st->internal->avctx->codec_id;
1628 av_packet_unref(pkt);
1630 if (pkt->flags & AV_PKT_FLAG_KEY)
1631 st->internal->skip_to_keyframe = 0;
1632 if (st->internal->skip_to_keyframe) {
1633 av_packet_unref(pkt);
1638 if (!got_packet && s->internal->parse_queue)
1639 ret = avpriv_packet_list_get(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1642 AVStream *st = s->streams[pkt->stream_index];
1643 int discard_padding = 0;
1644 if (st->internal->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1645 int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1646 int64_t sample = ts_to_samples(st, pts);
1647 int duration = ts_to_samples(st, pkt->duration);
1648 int64_t end_sample = sample + duration;
1649 if (duration > 0 && end_sample >= st->internal->first_discard_sample &&
1650 sample < st->internal->last_discard_sample)
1651 discard_padding = FFMIN(end_sample - st->internal->first_discard_sample, duration);
1653 if (st->internal->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1654 st->internal->skip_samples = st->internal->start_skip_samples;
1655 if (st->internal->skip_samples || discard_padding) {
1656 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1658 AV_WL32(p, st->internal->skip_samples);
1659 AV_WL32(p + 4, discard_padding);
1660 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->internal->skip_samples, discard_padding);
1662 st->internal->skip_samples = 0;
1665 if (st->internal->inject_global_side_data) {
1666 for (i = 0; i < st->nb_side_data; i++) {
1667 AVPacketSideData *src_sd = &st->side_data[i];
1670 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1673 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1675 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1679 memcpy(dst_data, src_sd->data, src_sd->size);
1681 st->internal->inject_global_side_data = 0;
1685 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1687 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1688 av_dict_copy(&s->metadata, metadata, 0);
1689 av_dict_free(&metadata);
1690 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1693 #if FF_API_LAVF_AVCTX
1694 update_stream_avctx(s);
1697 if (s->debug & FF_FDEBUG_TS)
1698 av_log(s, AV_LOG_DEBUG,
1699 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1700 "size=%d, duration=%"PRId64", flags=%d\n",
1702 av_ts2str(pkt->pts),
1703 av_ts2str(pkt->dts),
1704 pkt->size, pkt->duration, pkt->flags);
1706 /* A demuxer might have returned EOF because of an IO error, let's
1707 * propagate this back to the user. */
1708 if (ret == AVERROR_EOF && s->pb && s->pb->error < 0 && s->pb->error != AVERROR(EAGAIN))
1714 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1716 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1722 ret = s->internal->packet_buffer
1723 ? avpriv_packet_list_get(&s->internal->packet_buffer,
1724 &s->internal->packet_buffer_end, pkt)
1725 : read_frame_internal(s, pkt);
1732 AVPacketList *pktl = s->internal->packet_buffer;
1735 AVPacket *next_pkt = &pktl->pkt;
1737 if (next_pkt->dts != AV_NOPTS_VALUE) {
1738 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1739 // last dts seen for this stream. if any of packets following
1740 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1741 int64_t last_dts = next_pkt->dts;
1742 av_assert2(wrap_bits <= 64);
1743 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1744 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1745 av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2ULL << (wrap_bits - 1)) < 0) {
1746 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2ULL << (wrap_bits - 1))) {
1748 next_pkt->pts = pktl->pkt.dts;
1750 if (last_dts != AV_NOPTS_VALUE) {
1751 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1752 last_dts = pktl->pkt.dts;
1757 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1758 // Fixing the last reference frame had none pts issue (For MXF etc).
1759 // We only do this when
1761 // 2. we are not able to resolve a pts value for current packet.
1762 // 3. the packets for this stream at the end of the files had valid dts.
1763 next_pkt->pts = last_dts + next_pkt->duration;
1765 pktl = s->internal->packet_buffer;
1768 /* read packet from packet buffer, if there is data */
1769 st = s->streams[next_pkt->stream_index];
1770 if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1771 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1772 ret = avpriv_packet_list_get(&s->internal->packet_buffer,
1773 &s->internal->packet_buffer_end, pkt);
1778 ret = read_frame_internal(s, pkt);
1780 if (pktl && ret != AVERROR(EAGAIN)) {
1787 ret = avpriv_packet_list_put(&s->internal->packet_buffer,
1788 &s->internal->packet_buffer_end,
1791 av_packet_unref(pkt);
1798 st = s->streams[pkt->stream_index];
1799 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1800 ff_reduce_index(s, st->index);
1801 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1804 if (is_relative(pkt->dts))
1805 pkt->dts -= RELATIVE_TS_BASE;
1806 if (is_relative(pkt->pts))
1807 pkt->pts -= RELATIVE_TS_BASE;
1812 /* XXX: suppress the packet queue */
1813 static void flush_packet_queue(AVFormatContext *s)
1817 avpriv_packet_list_free(&s->internal->parse_queue, &s->internal->parse_queue_end);
1818 avpriv_packet_list_free(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1819 avpriv_packet_list_free(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1821 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1824 /*******************************************************/
1827 int av_find_default_stream_index(AVFormatContext *s)
1831 int best_stream = 0;
1832 int best_score = INT_MIN;
1834 if (s->nb_streams <= 0)
1836 for (i = 0; i < s->nb_streams; i++) {
1839 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1840 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
1842 if (st->codecpar->width && st->codecpar->height)
1846 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
1847 if (st->codecpar->sample_rate)
1850 if (st->codec_info_nb_frames)
1853 if (st->discard != AVDISCARD_ALL)
1856 if (score > best_score) {
1864 /** Flush the frame reader. */
1865 void ff_read_frame_flush(AVFormatContext *s)
1870 flush_packet_queue(s);
1872 /* Reset read state for each stream. */
1873 for (i = 0; i < s->nb_streams; i++) {
1877 av_parser_close(st->parser);
1880 st->last_IP_pts = AV_NOPTS_VALUE;
1881 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
1882 if (st->first_dts == AV_NOPTS_VALUE)
1883 st->cur_dts = RELATIVE_TS_BASE;
1885 /* We set the current DTS to an unspecified origin. */
1886 st->cur_dts = AV_NOPTS_VALUE;
1888 st->probe_packets = s->max_probe_packets;
1890 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1891 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
1893 if (s->internal->inject_global_side_data)
1894 st->internal->inject_global_side_data = 1;
1896 st->internal->skip_samples = 0;
1900 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1904 for (i = 0; i < s->nb_streams; i++) {
1905 AVStream *st = s->streams[i];
1908 av_rescale(timestamp,
1909 st->time_base.den * (int64_t) ref_st->time_base.num,
1910 st->time_base.num * (int64_t) ref_st->time_base.den);
1914 void ff_reduce_index(AVFormatContext *s, int stream_index)
1916 AVStream *st = s->streams[stream_index];
1917 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1919 if ((unsigned) st->internal->nb_index_entries >= max_entries) {
1921 for (i = 0; 2 * i < st->internal->nb_index_entries; i++)
1922 st->internal->index_entries[i] = st->internal->index_entries[2 * i];
1923 st->internal->nb_index_entries = i;
1927 int ff_add_index_entry(AVIndexEntry **index_entries,
1928 int *nb_index_entries,
1929 unsigned int *index_entries_allocated_size,
1930 int64_t pos, int64_t timestamp,
1931 int size, int distance, int flags)
1933 AVIndexEntry *entries, *ie;
1936 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1939 if (timestamp == AV_NOPTS_VALUE)
1940 return AVERROR(EINVAL);
1942 if (size < 0 || size > 0x3FFFFFFF)
1943 return AVERROR(EINVAL);
1945 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1946 timestamp -= RELATIVE_TS_BASE;
1948 entries = av_fast_realloc(*index_entries,
1949 index_entries_allocated_size,
1950 (*nb_index_entries + 1) *
1951 sizeof(AVIndexEntry));
1955 *index_entries = entries;
1957 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1958 timestamp, AVSEEK_FLAG_ANY);
1961 index = (*nb_index_entries)++;
1962 ie = &entries[index];
1963 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1965 ie = &entries[index];
1966 if (ie->timestamp != timestamp) {
1967 if (ie->timestamp <= timestamp)
1969 memmove(entries + index + 1, entries + index,
1970 sizeof(AVIndexEntry) * (*nb_index_entries - index));
1971 (*nb_index_entries)++;
1972 } else if (ie->pos == pos && distance < ie->min_distance)
1973 // do not reduce the distance
1974 distance = ie->min_distance;
1978 ie->timestamp = timestamp;
1979 ie->min_distance = distance;
1986 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1987 int size, int distance, int flags)
1989 timestamp = wrap_timestamp(st, timestamp);
1990 return ff_add_index_entry(&st->internal->index_entries, &st->internal->nb_index_entries,
1991 &st->internal->index_entries_allocated_size, pos,
1992 timestamp, size, distance, flags);
1995 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1996 int64_t wanted_timestamp, int flags)
2004 // Optimize appending index entries at the end.
2005 if (b && entries[b - 1].timestamp < wanted_timestamp)
2011 // Search for the next non-discarded packet.
2012 while ((entries[m].flags & AVINDEX_DISCARD_FRAME) && m < b && m < nb_entries - 1) {
2014 if (m == b && entries[m].timestamp >= wanted_timestamp) {
2020 timestamp = entries[m].timestamp;
2021 if (timestamp >= wanted_timestamp)
2023 if (timestamp <= wanted_timestamp)
2026 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
2028 if (!(flags & AVSEEK_FLAG_ANY))
2029 while (m >= 0 && m < nb_entries &&
2030 !(entries[m].flags & AVINDEX_KEYFRAME))
2031 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
2033 if (m == nb_entries)
2038 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
2041 int64_t pos_delta = 0;
2043 //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
2044 const char *proto = avio_find_protocol_name(s->url);
2046 av_assert0(time_tolerance >= 0);
2049 av_log(s, AV_LOG_INFO,
2050 "Protocol name not provided, cannot determine if input is local or "
2051 "a network protocol, buffers and access patterns cannot be configured "
2052 "optimally without knowing the protocol\n");
2055 if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
2058 for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
2059 AVStream *st1 = s->streams[ist1];
2060 for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
2061 AVStream *st2 = s->streams[ist2];
2067 for (i1 = i2 = 0; i1 < st1->internal->nb_index_entries; i1++) {
2068 AVIndexEntry *e1 = &st1->internal->index_entries[i1];
2069 int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
2071 skip = FFMAX(skip, e1->size);
2072 for (; i2 < st2->internal->nb_index_entries; i2++) {
2073 AVIndexEntry *e2 = &st2->internal->index_entries[i2];
2074 int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
2075 if (e2_pts < e1_pts || e2_pts - (uint64_t)e1_pts < time_tolerance)
2077 pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
2085 /* XXX This could be adjusted depending on protocol*/
2086 if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
2087 av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
2089 /* realloc the buffer and the original data will be retained */
2090 if (ffio_realloc_buf(s->pb, pos_delta)) {
2091 av_log(s, AV_LOG_ERROR, "Realloc buffer fail.\n");
2095 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
2098 if (skip < (1<<23)) {
2099 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
2103 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
2105 return ff_index_search_timestamp(st->internal->index_entries, st->internal->nb_index_entries,
2106 wanted_timestamp, flags);
2109 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
2110 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2112 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
2113 if (stream_index >= 0)
2114 ts = wrap_timestamp(s->streams[stream_index], ts);
2118 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
2119 int64_t target_ts, int flags)
2121 const AVInputFormat *avif = s->iformat;
2122 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
2123 int64_t ts_min, ts_max, ts;
2128 if (stream_index < 0)
2131 av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2134 ts_min = AV_NOPTS_VALUE;
2135 pos_limit = -1; // GCC falsely says it may be uninitialized.
2137 st = s->streams[stream_index];
2138 if (st->internal->index_entries) {
2141 /* FIXME: Whole function must be checked for non-keyframe entries in
2142 * index case, especially read_timestamp(). */
2143 index = av_index_search_timestamp(st, target_ts,
2144 flags | AVSEEK_FLAG_BACKWARD);
2145 index = FFMAX(index, 0);
2146 e = &st->internal->index_entries[index];
2148 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
2150 ts_min = e->timestamp;
2151 av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
2152 pos_min, av_ts2str(ts_min));
2154 av_assert1(index == 0);
2157 index = av_index_search_timestamp(st, target_ts,
2158 flags & ~AVSEEK_FLAG_BACKWARD);
2159 av_assert0(index < st->internal->nb_index_entries);
2161 e = &st->internal->index_entries[index];
2162 av_assert1(e->timestamp >= target_ts);
2164 ts_max = e->timestamp;
2165 pos_limit = pos_max - e->min_distance;
2166 av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
2167 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
2171 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
2172 ts_min, ts_max, flags, &ts, avif->read_timestamp);
2177 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
2180 ff_read_frame_flush(s);
2181 ff_update_cur_dts(s, st, ts);
2186 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
2187 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
2189 int64_t step = 1024;
2190 int64_t limit, ts_max;
2191 int64_t filesize = avio_size(s->pb);
2192 int64_t pos_max = filesize - 1;
2195 pos_max = FFMAX(0, (pos_max) - step);
2196 ts_max = ff_read_timestamp(s, stream_index,
2197 &pos_max, limit, read_timestamp);
2199 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
2200 if (ts_max == AV_NOPTS_VALUE)
2204 int64_t tmp_pos = pos_max + 1;
2205 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
2206 &tmp_pos, INT64_MAX, read_timestamp);
2207 if (tmp_ts == AV_NOPTS_VALUE)
2209 av_assert0(tmp_pos > pos_max);
2212 if (tmp_pos >= filesize)
2224 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
2225 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
2226 int64_t ts_min, int64_t ts_max,
2227 int flags, int64_t *ts_ret,
2228 int64_t (*read_timestamp)(struct AVFormatContext *, int,
2229 int64_t *, int64_t))
2236 av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
2238 if (ts_min == AV_NOPTS_VALUE) {
2239 pos_min = s->internal->data_offset;
2240 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2241 if (ts_min == AV_NOPTS_VALUE)
2245 if (ts_min >= target_ts) {
2250 if (ts_max == AV_NOPTS_VALUE) {
2251 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2253 pos_limit = pos_max;
2256 if (ts_max <= target_ts) {
2261 av_assert0(ts_min < ts_max);
2264 while (pos_min < pos_limit) {
2265 av_log(s, AV_LOG_TRACE,
2266 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2267 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2268 av_assert0(pos_limit <= pos_max);
2270 if (no_change == 0) {
2271 int64_t approximate_keyframe_distance = pos_max - pos_limit;
2272 // interpolate position (better than dichotomy)
2273 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2275 pos_min - approximate_keyframe_distance;
2276 } else if (no_change == 1) {
2277 // bisection if interpolation did not change min / max pos last time
2278 pos = (pos_min + pos_limit) >> 1;
2280 /* linear search if bisection failed, can only happen if there
2281 * are very few or no keyframes between min/max */
2286 else if (pos > pos_limit)
2290 // May pass pos_limit instead of -1.
2291 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2296 av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2297 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2298 pos_min, pos, pos_max,
2299 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2300 pos_limit, start_pos, no_change);
2301 if (ts == AV_NOPTS_VALUE) {
2302 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2305 if (target_ts <= ts) {
2306 pos_limit = start_pos - 1;
2310 if (target_ts >= ts) {
2316 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2317 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2320 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2322 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2323 av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2324 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2330 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2331 int64_t pos, int flags)
2333 int64_t pos_min, pos_max;
2335 pos_min = s->internal->data_offset;
2336 pos_max = avio_size(s->pb) - 1;
2340 else if (pos > pos_max)
2343 avio_seek(s->pb, pos, SEEK_SET);
2345 s->io_repositioned = 1;
2350 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2351 int64_t timestamp, int flags)
2358 st = s->streams[stream_index];
2360 index = av_index_search_timestamp(st, timestamp, flags);
2362 if (index < 0 && st->internal->nb_index_entries &&
2363 timestamp < st->internal->index_entries[0].timestamp)
2366 if (index < 0 || index == st->internal->nb_index_entries - 1) {
2370 if (st->internal->nb_index_entries) {
2371 av_assert0(st->internal->index_entries);
2372 ie = &st->internal->index_entries[st->internal->nb_index_entries - 1];
2373 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2375 ff_update_cur_dts(s, st, ie->timestamp);
2377 if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2383 read_status = av_read_frame(s, &pkt);
2384 } while (read_status == AVERROR(EAGAIN));
2385 if (read_status < 0)
2387 if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2388 if (pkt.flags & AV_PKT_FLAG_KEY) {
2389 av_packet_unref(&pkt);
2392 if (nonkey++ > 1000 && st->codecpar->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2393 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);
2394 av_packet_unref(&pkt);
2398 av_packet_unref(&pkt);
2400 index = av_index_search_timestamp(st, timestamp, flags);
2405 ff_read_frame_flush(s);
2406 if (s->iformat->read_seek)
2407 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2409 ie = &st->internal->index_entries[index];
2410 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2412 ff_update_cur_dts(s, st, ie->timestamp);
2417 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2418 int64_t timestamp, int flags)
2423 if (flags & AVSEEK_FLAG_BYTE) {
2424 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2426 ff_read_frame_flush(s);
2427 return seek_frame_byte(s, stream_index, timestamp, flags);
2430 if (stream_index < 0) {
2431 stream_index = av_find_default_stream_index(s);
2432 if (stream_index < 0)
2435 st = s->streams[stream_index];
2436 /* timestamp for default must be expressed in AV_TIME_BASE units */
2437 timestamp = av_rescale(timestamp, st->time_base.den,
2438 AV_TIME_BASE * (int64_t) st->time_base.num);
2441 /* first, we try the format specific seek */
2442 if (s->iformat->read_seek) {
2443 ff_read_frame_flush(s);
2444 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2450 if (s->iformat->read_timestamp &&
2451 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2452 ff_read_frame_flush(s);
2453 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2454 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2455 ff_read_frame_flush(s);
2456 return seek_frame_generic(s, stream_index, timestamp, flags);
2461 int av_seek_frame(AVFormatContext *s, int stream_index,
2462 int64_t timestamp, int flags)
2466 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2467 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2468 if ((flags & AVSEEK_FLAG_BACKWARD))
2472 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2473 flags & ~AVSEEK_FLAG_BACKWARD);
2476 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2479 ret = avformat_queue_attached_pictures(s);
2484 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2485 int64_t ts, int64_t max_ts, int flags)
2487 if (min_ts > ts || max_ts < ts)
2489 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2490 return AVERROR(EINVAL);
2493 flags |= AVSEEK_FLAG_ANY;
2494 flags &= ~AVSEEK_FLAG_BACKWARD;
2496 if (s->iformat->read_seek2) {
2498 ff_read_frame_flush(s);
2500 if (stream_index == -1 && s->nb_streams == 1) {
2501 AVRational time_base = s->streams[0]->time_base;
2502 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2503 min_ts = av_rescale_rnd(min_ts, time_base.den,
2504 time_base.num * (int64_t)AV_TIME_BASE,
2505 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2506 max_ts = av_rescale_rnd(max_ts, time_base.den,
2507 time_base.num * (int64_t)AV_TIME_BASE,
2508 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2512 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2516 ret = avformat_queue_attached_pictures(s);
2520 if (s->iformat->read_timestamp) {
2521 // try to seek via read_timestamp()
2524 // Fall back on old API if new is not implemented but old is.
2525 // Note the old API has somewhat different semantics.
2526 if (s->iformat->read_seek || 1) {
2527 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2528 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2529 if (ret<0 && ts != min_ts && max_ts != ts) {
2530 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2532 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2537 // try some generic seek like seek_frame_generic() but with new ts semantics
2538 return -1; //unreachable
2541 int avformat_flush(AVFormatContext *s)
2543 ff_read_frame_flush(s);
2547 /*******************************************************/
2550 * Return TRUE if the stream has accurate duration in any stream.
2552 * @return TRUE if the stream has accurate duration for at least one component.
2554 static int has_duration(AVFormatContext *ic)
2559 for (i = 0; i < ic->nb_streams; i++) {
2560 st = ic->streams[i];
2561 if (st->duration != AV_NOPTS_VALUE)
2564 if (ic->duration != AV_NOPTS_VALUE)
2570 * Estimate the stream timings from the one of each components.
2572 * Also computes the global bitrate if possible.
2574 static void update_stream_timings(AVFormatContext *ic)
2576 int64_t start_time, start_time1, start_time_text, end_time, end_time1, end_time_text;
2577 int64_t duration, duration1, duration_text, filesize;
2581 start_time = INT64_MAX;
2582 start_time_text = INT64_MAX;
2583 end_time = INT64_MIN;
2584 end_time_text = INT64_MIN;
2585 duration = INT64_MIN;
2586 duration_text = INT64_MIN;
2588 for (i = 0; i < ic->nb_streams; i++) {
2589 AVStream *st = ic->streams[i];
2590 int is_text = st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ||
2591 st->codecpar->codec_type == AVMEDIA_TYPE_DATA;
2592 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2593 start_time1 = av_rescale_q(st->start_time, st->time_base,
2596 start_time_text = FFMIN(start_time_text, start_time1);
2598 start_time = FFMIN(start_time, start_time1);
2599 end_time1 = av_rescale_q_rnd(st->duration, st->time_base,
2601 AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
2602 if (end_time1 != AV_NOPTS_VALUE && (end_time1 > 0 ? start_time1 <= INT64_MAX - end_time1 : start_time1 >= INT64_MIN - end_time1)) {
2603 end_time1 += start_time1;
2605 end_time_text = FFMAX(end_time_text, end_time1);
2607 end_time = FFMAX(end_time, end_time1);
2609 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2610 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2611 p->start_time = start_time1;
2612 if (p->end_time < end_time1)
2613 p->end_time = end_time1;
2616 if (st->duration != AV_NOPTS_VALUE) {
2617 duration1 = av_rescale_q(st->duration, st->time_base,
2620 duration_text = FFMAX(duration_text, duration1);
2622 duration = FFMAX(duration, duration1);
2625 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - (uint64_t)start_time_text < AV_TIME_BASE))
2626 start_time = start_time_text;
2627 else if (start_time > start_time_text)
2628 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2630 if (end_time == INT64_MIN || (end_time < end_time_text && end_time_text - (uint64_t)end_time < AV_TIME_BASE))
2631 end_time = end_time_text;
2632 else if (end_time < end_time_text)
2633 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream endtime %f\n", end_time_text / (float)AV_TIME_BASE);
2635 if (duration == INT64_MIN || (duration < duration_text && duration_text - duration < AV_TIME_BASE))
2636 duration = duration_text;
2637 else if (duration < duration_text)
2638 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream duration %f\n", duration_text / (float)AV_TIME_BASE);
2640 if (start_time != INT64_MAX) {
2641 ic->start_time = start_time;
2642 if (end_time != INT64_MIN) {
2643 if (ic->nb_programs > 1) {
2644 for (i = 0; i < ic->nb_programs; i++) {
2645 p = ic->programs[i];
2646 if (p->start_time != AV_NOPTS_VALUE &&
2647 p->end_time > p->start_time &&
2648 p->end_time - (uint64_t)p->start_time <= INT64_MAX)
2649 duration = FFMAX(duration, p->end_time - p->start_time);
2651 } else if (end_time >= start_time && end_time - (uint64_t)start_time <= INT64_MAX) {
2652 duration = FFMAX(duration, end_time - start_time);
2656 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2657 ic->duration = duration;
2659 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration > 0) {
2660 /* compute the bitrate */
2661 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2662 (double) ic->duration;
2663 if (bitrate >= 0 && bitrate <= INT64_MAX)
2664 ic->bit_rate = bitrate;
2668 static void fill_all_stream_timings(AVFormatContext *ic)
2673 update_stream_timings(ic);
2674 for (i = 0; i < ic->nb_streams; i++) {
2675 st = ic->streams[i];
2676 if (st->start_time == AV_NOPTS_VALUE) {
2677 if (ic->start_time != AV_NOPTS_VALUE)
2678 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2680 if (ic->duration != AV_NOPTS_VALUE)
2681 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2687 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2689 int64_t filesize, duration;
2690 int i, show_warning = 0;
2693 /* if bit_rate is already set, we believe it */
2694 if (ic->bit_rate <= 0) {
2695 int64_t bit_rate = 0;
2696 for (i = 0; i < ic->nb_streams; i++) {
2697 st = ic->streams[i];
2698 if (st->codecpar->bit_rate <= 0 && st->internal->avctx->bit_rate > 0)
2699 st->codecpar->bit_rate = st->internal->avctx->bit_rate;
2700 if (st->codecpar->bit_rate > 0) {
2701 if (INT64_MAX - st->codecpar->bit_rate < bit_rate) {
2705 bit_rate += st->codecpar->bit_rate;
2706 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2707 // If we have a videostream with packets but without a bitrate
2708 // then consider the sum not known
2713 ic->bit_rate = bit_rate;
2716 /* if duration is already set, we believe it */
2717 if (ic->duration == AV_NOPTS_VALUE &&
2718 ic->bit_rate != 0) {
2719 filesize = ic->pb ? avio_size(ic->pb) : 0;
2720 if (filesize > ic->internal->data_offset) {
2721 filesize -= ic->internal->data_offset;
2722 for (i = 0; i < ic->nb_streams; i++) {
2723 st = ic->streams[i];
2724 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2725 && st->duration == AV_NOPTS_VALUE) {
2726 duration = av_rescale(filesize, 8LL * st->time_base.den,
2728 (int64_t) st->time_base.num);
2729 st->duration = duration;
2736 av_log(ic, AV_LOG_WARNING,
2737 "Estimating duration from bitrate, this may be inaccurate\n");
2740 #define DURATION_MAX_READ_SIZE 250000LL
2741 #define DURATION_MAX_RETRY 6
2743 /* only usable for MPEG-PS streams */
2744 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2746 AVPacket pkt1, *pkt = &pkt1;
2748 int num, den, read_size, i, ret;
2749 int found_duration = 0;
2751 int64_t filesize, offset, duration;
2754 /* flush packet queue */
2755 flush_packet_queue(ic);
2757 for (i = 0; i < ic->nb_streams; i++) {
2758 st = ic->streams[i];
2759 if (st->start_time == AV_NOPTS_VALUE &&
2760 st->first_dts == AV_NOPTS_VALUE &&
2761 st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN)
2762 av_log(ic, AV_LOG_WARNING,
2763 "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2766 av_parser_close(st->parser);
2771 if (ic->skip_estimate_duration_from_pts) {
2772 av_log(ic, AV_LOG_INFO, "Skipping duration calculation in estimate_timings_from_pts\n");
2773 goto skip_duration_calc;
2776 av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2777 /* estimate the end time (duration) */
2778 /* XXX: may need to support wrapping */
2779 filesize = ic->pb ? avio_size(ic->pb) : 0;
2781 is_end = found_duration;
2782 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2786 avio_seek(ic->pb, offset, SEEK_SET);
2789 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2793 ret = ff_read_packet(ic, pkt);
2794 } while (ret == AVERROR(EAGAIN));
2797 read_size += pkt->size;
2798 st = ic->streams[pkt->stream_index];
2799 if (pkt->pts != AV_NOPTS_VALUE &&
2800 (st->start_time != AV_NOPTS_VALUE ||
2801 st->first_dts != AV_NOPTS_VALUE)) {
2802 if (pkt->duration == 0) {
2803 ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2805 pkt->duration = av_rescale_rnd(1,
2806 num * (int64_t) st->time_base.den,
2807 den * (int64_t) st->time_base.num,
2811 duration = pkt->pts + pkt->duration;
2813 if (st->start_time != AV_NOPTS_VALUE)
2814 duration -= st->start_time;
2816 duration -= st->first_dts;
2818 if (st->duration == AV_NOPTS_VALUE || st->internal->info->last_duration<= 0 ||
2819 (st->duration < duration && FFABS(duration - st->internal->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2820 st->duration = duration;
2821 st->internal->info->last_duration = duration;
2824 av_packet_unref(pkt);
2827 /* check if all audio/video streams have valid duration */
2830 for (i = 0; i < ic->nb_streams; i++) {
2831 st = ic->streams[i];
2832 switch (st->codecpar->codec_type) {
2833 case AVMEDIA_TYPE_VIDEO:
2834 case AVMEDIA_TYPE_AUDIO:
2835 if (st->duration == AV_NOPTS_VALUE)
2842 ++retry <= DURATION_MAX_RETRY);
2844 av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2846 /* warn about audio/video streams which duration could not be estimated */
2847 for (i = 0; i < ic->nb_streams; i++) {
2848 st = ic->streams[i];
2849 if (st->duration == AV_NOPTS_VALUE) {
2850 switch (st->codecpar->codec_type) {
2851 case AVMEDIA_TYPE_VIDEO:
2852 case AVMEDIA_TYPE_AUDIO:
2853 if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2854 av_log(ic, AV_LOG_WARNING, "stream %d : no PTS found at end of file, duration not set\n", i);
2856 av_log(ic, AV_LOG_WARNING, "stream %d : no TS found at start of file, duration not set\n", i);
2861 fill_all_stream_timings(ic);
2863 avio_seek(ic->pb, old_offset, SEEK_SET);
2864 for (i = 0; i < ic->nb_streams; i++) {
2867 st = ic->streams[i];
2868 st->cur_dts = st->first_dts;
2869 st->last_IP_pts = AV_NOPTS_VALUE;
2870 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
2871 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2872 st->internal->pts_buffer[j] = AV_NOPTS_VALUE;
2876 /* 1:1 map to AVDurationEstimationMethod */
2877 static const char *const duration_name[] = {
2878 [AVFMT_DURATION_FROM_PTS] = "pts",
2879 [AVFMT_DURATION_FROM_STREAM] = "stream",
2880 [AVFMT_DURATION_FROM_BITRATE] = "bit rate",
2883 static const char *duration_estimate_name(enum AVDurationEstimationMethod method)
2885 return duration_name[method];
2888 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2892 /* get the file size, if possible */
2893 if (ic->iformat->flags & AVFMT_NOFILE) {
2896 file_size = avio_size(ic->pb);
2897 file_size = FFMAX(0, file_size);
2900 if ((!strcmp(ic->iformat->name, "mpeg") ||
2901 !strcmp(ic->iformat->name, "mpegts")) &&
2902 file_size && (ic->pb->seekable & AVIO_SEEKABLE_NORMAL)) {
2903 /* get accurate estimate from the PTSes */
2904 estimate_timings_from_pts(ic, old_offset);
2905 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2906 } else if (has_duration(ic)) {
2907 /* at least one component has timings - we use them for all
2909 fill_all_stream_timings(ic);
2910 /* nut demuxer estimate the duration from PTS */
2911 if(!strcmp(ic->iformat->name, "nut"))
2912 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2914 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2916 /* less precise: use bitrate info */
2917 estimate_timings_from_bit_rate(ic);
2918 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2920 update_stream_timings(ic);
2924 AVStream av_unused *st;
2925 for (i = 0; i < ic->nb_streams; i++) {
2926 st = ic->streams[i];
2927 if (st->time_base.den)
2928 av_log(ic, AV_LOG_TRACE, "stream %d: start_time: %s duration: %s\n", i,
2929 av_ts2timestr(st->start_time, &st->time_base),
2930 av_ts2timestr(st->duration, &st->time_base));
2932 av_log(ic, AV_LOG_TRACE,
2933 "format: start_time: %s duration: %s (estimate from %s) bitrate=%"PRId64" kb/s\n",
2934 av_ts2timestr(ic->start_time, &AV_TIME_BASE_Q),
2935 av_ts2timestr(ic->duration, &AV_TIME_BASE_Q),
2936 duration_estimate_name(ic->duration_estimation_method),
2937 (int64_t)ic->bit_rate / 1000);
2941 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2943 AVCodecContext *avctx = st->internal->avctx;
2945 #define FAIL(errmsg) do { \
2947 *errmsg_ptr = errmsg; \
2951 if ( avctx->codec_id == AV_CODEC_ID_NONE
2952 && avctx->codec_type != AVMEDIA_TYPE_DATA)
2953 FAIL("unknown codec");
2954 switch (avctx->codec_type) {
2955 case AVMEDIA_TYPE_AUDIO:
2956 if (!avctx->frame_size && determinable_frame_size(avctx))
2957 FAIL("unspecified frame size");
2958 if (st->internal->info->found_decoder >= 0 &&
2959 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2960 FAIL("unspecified sample format");
2961 if (!avctx->sample_rate)
2962 FAIL("unspecified sample rate");
2963 if (!avctx->channels)
2964 FAIL("unspecified number of channels");
2965 if (st->internal->info->found_decoder >= 0 && !st->internal->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2966 FAIL("no decodable DTS frames");
2968 case AVMEDIA_TYPE_VIDEO:
2970 FAIL("unspecified size");
2971 if (st->internal->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2972 FAIL("unspecified pixel format");
2973 if (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)
2974 if (!st->sample_aspect_ratio.num && !st->codecpar->sample_aspect_ratio.num && !st->codec_info_nb_frames)
2975 FAIL("no frame in rv30/40 and no sar");
2977 case AVMEDIA_TYPE_SUBTITLE:
2978 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2979 FAIL("unspecified size");
2981 case AVMEDIA_TYPE_DATA:
2982 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2988 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2989 static int try_decode_frame(AVFormatContext *s, AVStream *st,
2990 const AVPacket *avpkt, AVDictionary **options)
2992 AVCodecContext *avctx = st->internal->avctx;
2993 const AVCodec *codec;
2994 int got_picture = 1, ret = 0;
2995 AVFrame *frame = av_frame_alloc();
2996 AVSubtitle subtitle;
2997 AVPacket pkt = *avpkt;
2998 int do_skip_frame = 0;
2999 enum AVDiscard skip_frame;
3002 return AVERROR(ENOMEM);
3004 if (!avcodec_is_open(avctx) &&
3005 st->internal->info->found_decoder <= 0 &&
3006 (st->codecpar->codec_id != -st->internal->info->found_decoder || !st->codecpar->codec_id)) {
3007 AVDictionary *thread_opt = NULL;
3009 codec = find_probe_decoder(s, st, st->codecpar->codec_id);
3012 st->internal->info->found_decoder = -st->codecpar->codec_id;
3017 /* Force thread count to 1 since the H.264 decoder will not extract
3018 * SPS and PPS to extradata during multi-threaded decoding. */
3019 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
3020 if (s->codec_whitelist)
3021 av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
3022 ret = avcodec_open2(avctx, codec, options ? options : &thread_opt);
3024 av_dict_free(&thread_opt);
3026 st->internal->info->found_decoder = -avctx->codec_id;
3029 st->internal->info->found_decoder = 1;
3030 } else if (!st->internal->info->found_decoder)
3031 st->internal->info->found_decoder = 1;
3033 if (st->internal->info->found_decoder < 0) {
3038 if (avpriv_codec_get_cap_skip_frame_fill_param(avctx->codec)) {
3040 skip_frame = avctx->skip_frame;
3041 avctx->skip_frame = AVDISCARD_ALL;
3044 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
3046 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
3047 (!st->codec_info_nb_frames &&
3048 (avctx->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
3050 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3051 avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
3052 ret = avcodec_send_packet(avctx, &pkt);
3053 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3057 ret = avcodec_receive_frame(avctx, frame);
3060 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
3062 } else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3063 ret = avcodec_decode_subtitle2(avctx, &subtitle,
3064 &got_picture, &pkt);
3066 avsubtitle_free(&subtitle);
3072 st->internal->nb_decoded_frames++;
3077 if (!pkt.data && !got_picture)
3081 if (do_skip_frame) {
3082 avctx->skip_frame = skip_frame;
3085 av_frame_free(&frame);
3089 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
3091 while (tags->id != AV_CODEC_ID_NONE) {
3099 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
3102 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3103 if (tag == tags[i].tag)
3105 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
3106 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
3108 return AV_CODEC_ID_NONE;
3111 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
3113 if (bps <= 0 || bps > 64)
3114 return AV_CODEC_ID_NONE;
3119 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
3121 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
3123 return AV_CODEC_ID_NONE;
3128 if (sflags & (1 << (bps - 1))) {
3131 return AV_CODEC_ID_PCM_S8;
3133 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
3135 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
3137 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
3139 return be ? AV_CODEC_ID_PCM_S64BE : AV_CODEC_ID_PCM_S64LE;
3141 return AV_CODEC_ID_NONE;
3146 return AV_CODEC_ID_PCM_U8;
3148 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
3150 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
3152 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
3154 return AV_CODEC_ID_NONE;
3160 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
3163 if (!av_codec_get_tag2(tags, id, &tag))
3168 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
3172 for (i = 0; tags && tags[i]; i++) {
3173 const AVCodecTag *codec_tags = tags[i];
3174 while (codec_tags->id != AV_CODEC_ID_NONE) {
3175 if (codec_tags->id == id) {
3176 *tag = codec_tags->tag;
3185 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
3188 for (i = 0; tags && tags[i]; i++) {
3189 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
3190 if (id != AV_CODEC_ID_NONE)
3193 return AV_CODEC_ID_NONE;
3196 static int chapter_start_cmp(const void *p1, const void *p2)
3198 AVChapter *ch1 = *(AVChapter**)p1;
3199 AVChapter *ch2 = *(AVChapter**)p2;
3200 int delta = av_compare_ts(ch1->start, ch1->time_base, ch2->start, ch2->time_base);
3203 return (ch1 > ch2) - (ch1 < ch2);
3206 static int compute_chapters_end(AVFormatContext *s)
3209 int64_t max_time = 0;
3210 AVChapter **timetable = av_malloc(s->nb_chapters * sizeof(*timetable));
3213 return AVERROR(ENOMEM);
3215 if (s->duration > 0 && s->start_time < INT64_MAX - s->duration)
3216 max_time = s->duration +
3217 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
3219 for (i = 0; i < s->nb_chapters; i++)
3220 timetable[i] = s->chapters[i];
3221 qsort(timetable, s->nb_chapters, sizeof(*timetable), chapter_start_cmp);
3223 for (i = 0; i < s->nb_chapters; i++)
3224 if (timetable[i]->end == AV_NOPTS_VALUE) {
3225 AVChapter *ch = timetable[i];
3226 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
3230 if (i + 1 < s->nb_chapters) {
3231 AVChapter *ch1 = timetable[i + 1];
3232 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
3234 if (next_start > ch->start && next_start < end)
3237 ch->end = (end == INT64_MAX || end < ch->start) ? ch->start : end;
3243 static int get_std_framerate(int i)
3246 return (i + 1) * 1001;
3250 return (i + 31) * 1001 * 12;
3254 return ((const int[]) { 80, 120, 240})[i] * 1001 * 12;
3258 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
3261 /* Is the time base unreliable?
3262 * This is a heuristic to balance between quick acceptance of the values in
3263 * the headers vs. some extra checks.
3264 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
3265 * MPEG-2 commonly misuses field repeat flags to store different framerates.
3266 * And there are "variable" fps files this needs to detect as well. */
3267 static int tb_unreliable(AVCodecContext *c)
3269 if (c->time_base.den >= 101LL * c->time_base.num ||
3270 c->time_base.den < 5LL * c->time_base.num ||
3271 // c->codec_tag == AV_RL32("DIVX") ||
3272 // c->codec_tag == AV_RL32("XVID") ||
3273 c->codec_tag == AV_RL32("mp4v") ||
3274 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
3275 c->codec_id == AV_CODEC_ID_GIF ||
3276 c->codec_id == AV_CODEC_ID_HEVC ||
3277 c->codec_id == AV_CODEC_ID_H264)
3282 int ff_alloc_extradata(AVCodecParameters *par, int size)
3284 av_freep(&par->extradata);
3285 par->extradata_size = 0;
3287 if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
3288 return AVERROR(EINVAL);
3290 par->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
3291 if (!par->extradata)
3292 return AVERROR(ENOMEM);
3294 memset(par->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3295 par->extradata_size = size;
3300 int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
3302 int ret = ff_alloc_extradata(par, size);
3305 ret = avio_read(pb, par->extradata, size);
3307 av_freep(&par->extradata);
3308 par->extradata_size = 0;
3309 av_log(s, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
3310 return ret < 0 ? ret : AVERROR_INVALIDDATA;
3316 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
3319 int64_t last = st->internal->info->last_dts;
3321 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
3322 && ts - (uint64_t)last < INT64_MAX) {
3323 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
3324 int64_t duration = ts - last;
3326 if (!st->internal->info->duration_error)
3327 st->internal->info->duration_error = av_mallocz(sizeof(st->internal->info->duration_error[0])*2);
3328 if (!st->internal->info->duration_error)
3329 return AVERROR(ENOMEM);
3331 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3332 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
3333 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3334 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3335 int framerate = get_std_framerate(i);
3336 double sdts = dts*framerate/(1001*12);
3337 for (j= 0; j<2; j++) {
3338 int64_t ticks = llrint(sdts+j*0.5);
3339 double error= sdts - ticks + j*0.5;
3340 st->internal->info->duration_error[j][0][i] += error;
3341 st->internal->info->duration_error[j][1][i] += error*error;
3345 if (st->internal->info->rfps_duration_sum <= INT64_MAX - duration) {
3346 st->internal->info->duration_count++;
3347 st->internal->info->rfps_duration_sum += duration;
3350 if (st->internal->info->duration_count % 10 == 0) {
3351 int n = st->internal->info->duration_count;
3352 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3353 if (st->internal->info->duration_error[0][1][i] < 1e10) {
3354 double a0 = st->internal->info->duration_error[0][0][i] / n;
3355 double error0 = st->internal->info->duration_error[0][1][i] / n - a0*a0;
3356 double a1 = st->internal->info->duration_error[1][0][i] / n;
3357 double error1 = st->internal->info->duration_error[1][1][i] / n - a1*a1;
3358 if (error0 > 0.04 && error1 > 0.04) {
3359 st->internal->info->duration_error[0][1][i] = 2e10;
3360 st->internal->info->duration_error[1][1][i] = 2e10;
3366 // ignore the first 4 values, they might have some random jitter
3367 if (st->internal->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3368 st->internal->info->duration_gcd = av_gcd(st->internal->info->duration_gcd, duration);
3370 if (ts != AV_NOPTS_VALUE)
3371 st->internal->info->last_dts = ts;
3376 void ff_rfps_calculate(AVFormatContext *ic)
3380 for (i = 0; i < ic->nb_streams; i++) {
3381 AVStream *st = ic->streams[i];
3383 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
3385 // the check for tb_unreliable() is not completely correct, since this is not about handling
3386 // an unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3387 // ipmovie.c produces.
3388 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)
3389 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);
3390 if (st->internal->info->duration_count>1 && !st->r_frame_rate.num
3391 && tb_unreliable(st->internal->avctx)) {
3393 double best_error= 0.01;
3394 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3396 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3399 if (st->internal->info->codec_info_duration &&
3400 st->internal->info->codec_info_duration*av_q2d(st->time_base) < (1001*11.5)/get_std_framerate(j))
3402 if (!st->internal->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3405 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))
3408 for (k= 0; k<2; k++) {
3409 int n = st->internal->info->duration_count;
3410 double a= st->internal->info->duration_error[k][0][j] / n;
3411 double error= st->internal->info->duration_error[k][1][j]/n - a*a;
3413 if (error < best_error && best_error> 0.000000001) {
3415 num = get_std_framerate(j);
3418 av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3421 // do not increase frame rate by more than 1 % in order to match a standard rate.
3422 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3423 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3425 if ( !st->avg_frame_rate.num
3426 && st->r_frame_rate.num && st->internal->info->rfps_duration_sum
3427 && st->internal->info->codec_info_duration <= 0
3428 && st->internal->info->duration_count > 2
3429 && 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
3431 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3432 st->avg_frame_rate = st->r_frame_rate;
3435 av_freep(&st->internal->info->duration_error);
3436 st->internal->info->last_dts = AV_NOPTS_VALUE;
3437 st->internal->info->duration_count = 0;
3438 st->internal->info->rfps_duration_sum = 0;
3442 static int extract_extradata_check(AVStream *st)
3444 const AVBitStreamFilter *f;
3446 f = av_bsf_get_by_name("extract_extradata");
3451 const enum AVCodecID *ids;
3452 for (ids = f->codec_ids; *ids != AV_CODEC_ID_NONE; ids++)
3453 if (*ids == st->codecpar->codec_id)
3460 static int extract_extradata_init(AVStream *st)
3462 AVStreamInternal *sti = st->internal;
3463 const AVBitStreamFilter *f;
3466 f = av_bsf_get_by_name("extract_extradata");
3470 /* check that the codec id is supported */
3471 ret = extract_extradata_check(st);
3475 sti->extract_extradata.pkt = av_packet_alloc();
3476 if (!sti->extract_extradata.pkt)
3477 return AVERROR(ENOMEM);
3479 ret = av_bsf_alloc(f, &sti->extract_extradata.bsf);
3483 ret = avcodec_parameters_copy(sti->extract_extradata.bsf->par_in,
3488 sti->extract_extradata.bsf->time_base_in = st->time_base;
3490 ret = av_bsf_init(sti->extract_extradata.bsf);
3495 sti->extract_extradata.inited = 1;
3499 av_bsf_free(&sti->extract_extradata.bsf);
3500 av_packet_free(&sti->extract_extradata.pkt);
3504 static int extract_extradata(AVStream *st, const AVPacket *pkt)
3506 AVStreamInternal *sti = st->internal;
3510 if (!sti->extract_extradata.inited) {
3511 ret = extract_extradata_init(st);
3516 if (sti->extract_extradata.inited && !sti->extract_extradata.bsf)
3519 pkt_ref = sti->extract_extradata.pkt;
3520 ret = av_packet_ref(pkt_ref, pkt);
3524 ret = av_bsf_send_packet(sti->extract_extradata.bsf, pkt_ref);
3526 av_packet_unref(pkt_ref);
3530 while (ret >= 0 && !sti->avctx->extradata) {
3531 ret = av_bsf_receive_packet(sti->extract_extradata.bsf, pkt_ref);
3533 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
3538 for (int i = 0; i < pkt_ref->side_data_elems; i++) {
3539 AVPacketSideData *side_data = &pkt_ref->side_data[i];
3540 if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) {
3541 sti->avctx->extradata = side_data->data;
3542 sti->avctx->extradata_size = side_data->size;
3543 side_data->data = NULL;
3544 side_data->size = 0;
3548 av_packet_unref(pkt_ref);
3554 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
3558 for (i = 0; i < avctx->nb_coded_side_data; i++) {
3559 const AVPacketSideData *sd_src = &avctx->coded_side_data[i];
3561 dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
3563 return AVERROR(ENOMEM);
3564 memcpy(dst_data, sd_src->data, sd_src->size);
3569 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3571 int i, count = 0, ret = 0, j;
3574 AVCodecContext *avctx;
3576 int64_t old_offset = avio_tell(ic->pb);
3577 // new streams might appear, no options for those
3578 int orig_nb_streams = ic->nb_streams;
3580 int64_t max_analyze_duration = ic->max_analyze_duration;
3581 int64_t max_stream_analyze_duration;
3582 int64_t max_subtitle_analyze_duration;
3583 int64_t probesize = ic->probesize;
3584 int eof_reached = 0;
3585 int *missing_streams = av_opt_ptr(ic->iformat->priv_class, ic->priv_data, "missing_streams");
3587 flush_codecs = probesize > 0;
3589 av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3591 max_stream_analyze_duration = max_analyze_duration;
3592 max_subtitle_analyze_duration = max_analyze_duration;
3593 if (!max_analyze_duration) {
3594 max_stream_analyze_duration =
3595 max_analyze_duration = 5*AV_TIME_BASE;
3596 max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3597 if (!strcmp(ic->iformat->name, "flv"))
3598 max_stream_analyze_duration = 90*AV_TIME_BASE;
3599 if (!strcmp(ic->iformat->name, "mpeg") || !strcmp(ic->iformat->name, "mpegts"))
3600 max_stream_analyze_duration = 7*AV_TIME_BASE;
3604 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
3605 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
3607 for (i = 0; i < ic->nb_streams; i++) {
3608 const AVCodec *codec;
3609 AVDictionary *thread_opt = NULL;
3610 st = ic->streams[i];
3611 avctx = st->internal->avctx;
3613 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3614 st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3615 /* if (!st->time_base.num)
3617 if (!avctx->time_base.num)
3618 avctx->time_base = st->time_base;
3621 /* check if the caller has overridden the codec id */
3622 #if FF_API_LAVF_AVCTX
3623 FF_DISABLE_DEPRECATION_WARNINGS
3624 if (st->codec->codec_id != st->internal->orig_codec_id) {
3625 st->codecpar->codec_id = st->codec->codec_id;
3626 st->codecpar->codec_type = st->codec->codec_type;
3627 st->internal->orig_codec_id = st->codec->codec_id;
3629 FF_ENABLE_DEPRECATION_WARNINGS
3631 // only for the split stuff
3632 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE) && st->internal->request_probe <= 0) {
3633 st->parser = av_parser_init(st->codecpar->codec_id);
3635 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3636 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3637 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3638 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3640 } else if (st->need_parsing) {
3641 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3642 "%s, packets or times may be invalid.\n",
3643 avcodec_get_name(st->codecpar->codec_id));
3647 if (st->codecpar->codec_id != st->internal->orig_codec_id)
3648 st->internal->orig_codec_id = st->codecpar->codec_id;
3650 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3652 goto find_stream_info_err;
3653 if (st->internal->request_probe <= 0)
3654 st->internal->avctx_inited = 1;
3656 codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3658 /* Force thread count to 1 since the H.264 decoder will not extract
3659 * SPS and PPS to extradata during multi-threaded decoding. */
3660 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3662 if (ic->codec_whitelist)
3663 av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3665 /* Ensure that subtitle_header is properly set. */
3666 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE
3667 && codec && !avctx->codec) {
3668 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3669 av_log(ic, AV_LOG_WARNING,
3670 "Failed to open codec in %s\n",__FUNCTION__);
3673 // Try to just open decoders, in case this is enough to get parameters.
3674 if (!has_codec_parameters(st, NULL) && st->internal->request_probe <= 0) {
3675 if (codec && !avctx->codec)
3676 if (avcodec_open2(avctx, codec, options ? &options[i] : &thread_opt) < 0)
3677 av_log(ic, AV_LOG_WARNING,
3678 "Failed to open codec in %s\n",__FUNCTION__);
3681 av_dict_free(&thread_opt);
3684 for (i = 0; i < ic->nb_streams; i++) {
3685 #if FF_API_R_FRAME_RATE
3686 ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
3688 ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
3689 ic->streams[i]->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3694 const AVPacket *pkt;
3695 int analyzed_all_streams;
3696 if (ff_check_interrupt(&ic->interrupt_callback)) {
3698 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3702 /* check if one codec still needs to be handled */
3703 for (i = 0; i < ic->nb_streams; i++) {
3704 int fps_analyze_framecount = 20;
3707 st = ic->streams[i];
3708 if (!has_codec_parameters(st, NULL))
3710 /* If the timebase is coarse (like the usual millisecond precision
3711 * of mkv), we need to analyze more frames to reliably arrive at
3712 * the correct fps. */
3713 if (av_q2d(st->time_base) > 0.0005)
3714 fps_analyze_framecount *= 2;
3715 if (!tb_unreliable(st->internal->avctx))
3716 fps_analyze_framecount = 0;
3717 if (ic->fps_probe_size >= 0)
3718 fps_analyze_framecount = ic->fps_probe_size;
3719 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3720 fps_analyze_framecount = 0;
3721 /* variable fps and no guess at the real fps */
3722 count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3723 st->internal->info->codec_info_duration_fields/2 :
3724 st->internal->info->duration_count;
3725 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3726 st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3727 if (count < fps_analyze_framecount)
3730 // Look at the first 3 frames if there is evidence of frame delay
3731 // but the decoder delay is not set.
3732 if (st->internal->info->frame_delay_evidence && count < 2 && st->internal->avctx->has_b_frames == 0)
3734 if (!st->internal->avctx->extradata &&
3735 (!st->internal->extract_extradata.inited ||
3736 st->internal->extract_extradata.bsf) &&
3737 extract_extradata_check(st))
3739 if (st->first_dts == AV_NOPTS_VALUE &&
3740 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3741 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
3742 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3743 st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
3746 analyzed_all_streams = 0;
3747 if (!missing_streams || !*missing_streams)
3748 if (i == ic->nb_streams) {
3749 analyzed_all_streams = 1;
3750 /* NOTE: If the format has no header, then we need to read some
3751 * packets to get most of the streams, so we cannot stop here. */
3752 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3753 /* If we found the info for all the codecs, we can stop. */
3755 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3760 /* We did not get all the codec info, but we read too much data. */
3761 if (read_size >= probesize) {
3763 av_log(ic, AV_LOG_DEBUG,
3764 "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3765 for (i = 0; i < ic->nb_streams; i++)
3766 if (!ic->streams[i]->r_frame_rate.num &&
3767 ic->streams[i]->internal->info->duration_count <= 1 &&
3768 ic->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3769 strcmp(ic->iformat->name, "image2"))
3770 av_log(ic, AV_LOG_WARNING,
3771 "Stream #%d: not enough frames to estimate rate; "
3772 "consider increasing probesize\n", i);
3776 /* NOTE: A new stream can be added there if no header in file
3777 * (AVFMTCTX_NOHEADER). */
3778 ret = read_frame_internal(ic, &pkt1);
3779 if (ret == AVERROR(EAGAIN))
3788 if (!(ic->flags & AVFMT_FLAG_NOBUFFER)) {
3789 ret = avpriv_packet_list_put(&ic->internal->packet_buffer,
3790 &ic->internal->packet_buffer_end,
3793 goto unref_then_goto_end;
3795 pkt = &ic->internal->packet_buffer_end->pkt;
3800 st = ic->streams[pkt->stream_index];
3801 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3802 read_size += pkt->size;
3804 avctx = st->internal->avctx;
3805 if (!st->internal->avctx_inited) {
3806 ret = avcodec_parameters_to_context(avctx, st->codecpar);
3808 goto unref_then_goto_end;
3809 st->internal->avctx_inited = 1;
3812 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3813 /* check for non-increasing dts */
3814 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3815 st->internal->info->fps_last_dts >= pkt->dts) {
3816 av_log(ic, AV_LOG_DEBUG,
3817 "Non-increasing DTS in stream %d: packet %d with DTS "
3818 "%"PRId64", packet %d with DTS %"PRId64"\n",
3819 st->index, st->internal->info->fps_last_dts_idx,
3820 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3822 st->internal->info->fps_first_dts =
3823 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3825 /* Check for a discontinuity in dts. If the difference in dts
3826 * is more than 1000 times the average packet duration in the
3827 * sequence, we treat it as a discontinuity. */
3828 if (st->internal->info->fps_last_dts != AV_NOPTS_VALUE &&
3829 st->internal->info->fps_last_dts_idx > st->internal->info->fps_first_dts_idx &&
3830 (pkt->dts - (uint64_t)st->internal->info->fps_last_dts) / 1000 >
3831 (st->internal->info->fps_last_dts - (uint64_t)st->internal->info->fps_first_dts) /
3832 (st->internal->info->fps_last_dts_idx - st->internal->info->fps_first_dts_idx)) {
3833 av_log(ic, AV_LOG_WARNING,
3834 "DTS discontinuity in stream %d: packet %d with DTS "
3835 "%"PRId64", packet %d with DTS %"PRId64"\n",
3836 st->index, st->internal->info->fps_last_dts_idx,
3837 st->internal->info->fps_last_dts, st->codec_info_nb_frames,
3839 st->internal->info->fps_first_dts =
3840 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
3843 /* update stored dts values */
3844 if (st->internal->info->fps_first_dts == AV_NOPTS_VALUE) {
3845 st->internal->info->fps_first_dts = pkt->dts;
3846 st->internal->info->fps_first_dts_idx = st->codec_info_nb_frames;
3848 st->internal->info->fps_last_dts = pkt->dts;
3849 st->internal->info->fps_last_dts_idx = st->codec_info_nb_frames;
3851 if (st->codec_info_nb_frames>1) {
3855 if (st->time_base.den > 0)
3856 t = av_rescale_q(st->internal->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3857 if (st->avg_frame_rate.num > 0)
3858 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3861 && st->codec_info_nb_frames>30
3862 && st->internal->info->fps_first_dts != AV_NOPTS_VALUE
3863 && st->internal->info->fps_last_dts != AV_NOPTS_VALUE)
3864 t = FFMAX(t, av_rescale_q(st->internal->info->fps_last_dts - st->internal->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));
3866 if (analyzed_all_streams) limit = max_analyze_duration;
3867 else if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3868 else limit = max_stream_analyze_duration;
3871 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3873 t, pkt->stream_index);
3874 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3875 av_packet_unref(&pkt1);
3878 if (pkt->duration) {
3879 if (avctx->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && st->start_time != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3880 st->internal->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->internal->info->codec_info_duration + pkt->duration);
3882 st->internal->info->codec_info_duration += pkt->duration;
3883 st->internal->info->codec_info_duration_fields += st->parser && st->need_parsing && avctx->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3886 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3887 #if FF_API_R_FRAME_RATE
3888 ff_rfps_add_frame(ic, st, pkt->dts);
3890 if (pkt->dts != pkt->pts && pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
3891 st->internal->info->frame_delay_evidence = 1;
3893 if (!st->internal->avctx->extradata) {
3894 ret = extract_extradata(st, pkt);
3896 goto unref_then_goto_end;
3899 /* If still no information, we try to open the codec and to
3900 * decompress the frame. We try to avoid that in most cases as
3901 * it takes longer and uses more memory. For MPEG-4, we need to
3902 * decompress for QuickTime.
3904 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3905 * least one frame of codec data, this makes sure the codec initializes
3906 * the channel configuration and does not only trust the values from
3908 try_decode_frame(ic, st, pkt,
3909 (options && i < orig_nb_streams) ? &options[i] : NULL);
3911 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3912 av_packet_unref(&pkt1);
3914 st->codec_info_nb_frames++;
3920 for (stream_index = 0; stream_index < ic->nb_streams; stream_index++) {
3921 st = ic->streams[stream_index];
3922 avctx = st->internal->avctx;
3923 if (!has_codec_parameters(st, NULL)) {
3924 const AVCodec *codec = find_probe_decoder(ic, st, st->codecpar->codec_id);
3925 if (codec && !avctx->codec) {
3926 AVDictionary *opts = NULL;
3927 if (ic->codec_whitelist)
3928 av_dict_set(&opts, "codec_whitelist", ic->codec_whitelist, 0);
3929 if (avcodec_open2(avctx, codec, (options && stream_index < orig_nb_streams) ? &options[stream_index] : &opts) < 0)
3930 av_log(ic, AV_LOG_WARNING,
3931 "Failed to open codec in %s\n",__FUNCTION__);
3932 av_dict_free(&opts);
3936 // EOF already reached while reading the stream above.
3937 // So continue with reoordering DTS with whatever delay we have.
3938 if (ic->internal->packet_buffer && !has_decode_delay_been_guessed(st)) {
3939 update_dts_from_pts(ic, stream_index, ic->internal->packet_buffer);
3945 AVPacket empty_pkt = { 0 };
3947 av_init_packet(&empty_pkt);
3949 for (i = 0; i < ic->nb_streams; i++) {
3951 st = ic->streams[i];
3953 /* flush the decoders */
3954 if (st->internal->info->found_decoder == 1) {
3956 err = try_decode_frame(ic, st, &empty_pkt,
3957 (options && i < orig_nb_streams)
3958 ? &options[i] : NULL);
3959 } while (err > 0 && !has_codec_parameters(st, NULL));
3962 av_log(ic, AV_LOG_INFO,
3963 "decoding for stream %d failed\n", st->index);
3969 ff_rfps_calculate(ic);
3971 for (i = 0; i < ic->nb_streams; i++) {
3972 st = ic->streams[i];
3973 avctx = st->internal->avctx;
3974 if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3975 if (avctx->codec_id == AV_CODEC_ID_RAWVIDEO && !avctx->codec_tag && !avctx->bits_per_coded_sample) {
3976 uint32_t tag= avcodec_pix_fmt_to_codec_tag(avctx->pix_fmt);
3977 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == avctx->pix_fmt)
3978 avctx->codec_tag= tag;
3981 /* estimate average framerate if not set by demuxer */
3982 if (st->internal->info->codec_info_duration_fields &&
3983 !st->avg_frame_rate.num &&
3984 st->internal->info->codec_info_duration) {
3986 double best_error = 0.01;
3987 AVRational codec_frame_rate = avctx->framerate;
3989 if (st->internal->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3990 st->internal->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3991 st->internal->info->codec_info_duration < 0)
3993 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3994 st->internal->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3995 st->internal->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3997 /* Round guessed framerate to a "standard" framerate if it's
3998 * within 1% of the original estimate. */
3999 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
4000 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
4001 double error = fabs(av_q2d(st->avg_frame_rate) /
4002 av_q2d(std_fps) - 1);
4004 if (error < best_error) {
4006 best_fps = std_fps.num;
4009 if (ic->internal->prefer_codec_framerate && codec_frame_rate.num > 0 && codec_frame_rate.den > 0) {
4010 error = fabs(av_q2d(codec_frame_rate) /
4011 av_q2d(std_fps) - 1);
4012 if (error < best_error) {
4014 best_fps = std_fps.num;
4019 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4020 best_fps, 12 * 1001, INT_MAX);
4023 if (!st->r_frame_rate.num) {
4024 if ( avctx->time_base.den * (int64_t) st->time_base.num
4025 <= avctx->time_base.num * avctx->ticks_per_frame * (uint64_t) st->time_base.den) {
4026 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4027 avctx->time_base.den, (int64_t)avctx->time_base.num * avctx->ticks_per_frame, INT_MAX);
4029 st->r_frame_rate.num = st->time_base.den;
4030 st->r_frame_rate.den = st->time_base.num;
4033 if (st->internal->display_aspect_ratio.num && st->internal->display_aspect_ratio.den) {
4034 AVRational hw_ratio = { avctx->height, avctx->width };
4035 st->sample_aspect_ratio = av_mul_q(st->internal->display_aspect_ratio,
4038 } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
4039 if (!avctx->bits_per_coded_sample)
4040 avctx->bits_per_coded_sample =
4041 av_get_bits_per_sample(avctx->codec_id);
4042 // set stream disposition based on audio service type
4043 switch (avctx->audio_service_type) {
4044 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
4045 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
4047 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
4048 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
4050 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
4051 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
4053 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
4054 st->disposition = AV_DISPOSITION_COMMENT;
4056 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
4057 st->disposition = AV_DISPOSITION_KARAOKE;
4064 estimate_timings(ic, old_offset);
4066 av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
4068 if (ret >= 0 && ic->nb_streams)
4069 /* We could not have all the codec parameters before EOF. */
4071 for (i = 0; i < ic->nb_streams; i++) {
4073 st = ic->streams[i];
4075 /* if no packet was ever seen, update context now for has_codec_parameters */
4076 if (!st->internal->avctx_inited) {
4077 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
4078 st->codecpar->format == AV_SAMPLE_FMT_NONE)
4079 st->codecpar->format = st->internal->avctx->sample_fmt;
4080 ret = avcodec_parameters_to_context(st->internal->avctx, st->codecpar);
4082 goto find_stream_info_err;
4084 if (!has_codec_parameters(st, &errmsg)) {
4086 avcodec_string(buf, sizeof(buf), st->internal->avctx, 0);
4087 av_log(ic, AV_LOG_WARNING,
4088 "Could not find codec parameters for stream %d (%s): %s\n"
4089 "Consider increasing the value for the 'analyzeduration' (%"PRId64") and 'probesize' (%"PRId64") options\n",
4090 i, buf, errmsg, ic->max_analyze_duration, ic->probesize);
4096 ret = compute_chapters_end(ic);
4098 goto find_stream_info_err;
4100 /* update the stream parameters from the internal codec contexts */
4101 for (i = 0; i < ic->nb_streams; i++) {
4102 st = ic->streams[i];
4104 if (st->internal->avctx_inited) {
4105 int orig_w = st->codecpar->width;
4106 int orig_h = st->codecpar->height;
4107 ret = avcodec_parameters_from_context(st->codecpar, st->internal->avctx);
4109 goto find_stream_info_err;
4110 ret = add_coded_side_data(st, st->internal->avctx);
4112 goto find_stream_info_err;
4114 // The decoder might reduce the video size by the lowres factor.
4115 if (st->internal->avctx->lowres && orig_w) {
4116 st->codecpar->width = orig_w;
4117 st->codecpar->height = orig_h;
4122 #if FF_API_LAVF_AVCTX
4123 FF_DISABLE_DEPRECATION_WARNINGS
4124 ret = avcodec_parameters_to_context(st->codec, st->codecpar);
4126 goto find_stream_info_err;
4129 // The old API (AVStream.codec) "requires" the resolution to be adjusted
4130 // by the lowres factor.
4131 if (st->internal->avctx->lowres && st->internal->avctx->width) {
4132 st->codec->lowres = st->internal->avctx->lowres;
4133 st->codec->width = st->internal->avctx->width;
4134 st->codec->height = st->internal->avctx->height;
4138 if (st->codec->codec_tag != MKTAG('t','m','c','d')) {
4139 st->codec->time_base = st->internal->avctx->time_base;
4140 st->codec->ticks_per_frame = st->internal->avctx->ticks_per_frame;
4142 st->codec->framerate = st->avg_frame_rate;
4144 if (st->internal->avctx->subtitle_header) {
4145 st->codec->subtitle_header = av_malloc(st->internal->avctx->subtitle_header_size);
4146 if (!st->codec->subtitle_header)
4147 goto find_stream_info_err;
4148 st->codec->subtitle_header_size = st->internal->avctx->subtitle_header_size;
4149 memcpy(st->codec->subtitle_header, st->internal->avctx->subtitle_header,
4150 st->codec->subtitle_header_size);
4153 // Fields unavailable in AVCodecParameters
4154 st->codec->coded_width = st->internal->avctx->coded_width;
4155 st->codec->coded_height = st->internal->avctx->coded_height;
4156 st->codec->properties = st->internal->avctx->properties;
4157 FF_ENABLE_DEPRECATION_WARNINGS
4160 st->internal->avctx_inited = 0;
4163 find_stream_info_err:
4164 for (i = 0; i < ic->nb_streams; i++) {
4165 st = ic->streams[i];
4166 if (st->internal->info)
4167 av_freep(&st->internal->info->duration_error);
4168 avcodec_close(ic->streams[i]->internal->avctx);
4169 av_freep(&ic->streams[i]->internal->info);
4170 av_bsf_free(&ic->streams[i]->internal->extract_extradata.bsf);
4171 av_packet_free(&ic->streams[i]->internal->extract_extradata.pkt);
4174 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
4175 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
4178 unref_then_goto_end:
4179 av_packet_unref(&pkt1);
4180 goto find_stream_info_err;
4183 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
4187 for (i = 0; i < ic->nb_programs; i++) {
4188 if (ic->programs[i] == last) {
4192 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
4193 if (ic->programs[i]->stream_index[j] == s)
4194 return ic->programs[i];
4200 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
4201 int wanted_stream_nb, int related_stream,
4202 AVCodec **decoder_ret, int flags)
4204 int i, nb_streams = ic->nb_streams;
4205 int ret = AVERROR_STREAM_NOT_FOUND;
4206 int best_count = -1, best_multiframe = -1, best_disposition = -1;
4207 int count, multiframe, disposition;
4208 int64_t best_bitrate = -1;
4210 unsigned *program = NULL;
4211 const AVCodec *decoder = NULL, *best_decoder = NULL;
4213 if (related_stream >= 0 && wanted_stream_nb < 0) {
4214 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
4216 program = p->stream_index;
4217 nb_streams = p->nb_stream_indexes;
4220 for (i = 0; i < nb_streams; i++) {
4221 int real_stream_index = program ? program[i] : i;
4222 AVStream *st = ic->streams[real_stream_index];
4223 AVCodecParameters *par = st->codecpar;
4224 if (par->codec_type != type)
4226 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
4228 if (type == AVMEDIA_TYPE_AUDIO && !(par->channels && par->sample_rate))
4231 decoder = find_decoder(ic, st, par->codec_id);
4234 ret = AVERROR_DECODER_NOT_FOUND;
4238 disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
4239 + !! (st->disposition & AV_DISPOSITION_DEFAULT);
4240 count = st->codec_info_nb_frames;
4241 bitrate = par->bit_rate;
4242 multiframe = FFMIN(5, count);
4243 if ((best_disposition > disposition) ||
4244 (best_disposition == disposition && best_multiframe > multiframe) ||
4245 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate > bitrate) ||
4246 (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
4248 best_disposition = disposition;
4250 best_bitrate = bitrate;
4251 best_multiframe = multiframe;
4252 ret = real_stream_index;
4253 best_decoder = decoder;
4254 if (program && i == nb_streams - 1 && ret < 0) {
4256 nb_streams = ic->nb_streams;
4257 /* no related stream found, try again with everything */
4262 *decoder_ret = (AVCodec*)best_decoder;
4266 /*******************************************************/
4268 int av_read_play(AVFormatContext *s)
4270 if (s->iformat->read_play)
4271 return s->iformat->read_play(s);
4273 return avio_pause(s->pb, 0);
4274 return AVERROR(ENOSYS);
4277 int av_read_pause(AVFormatContext *s)
4279 if (s->iformat->read_pause)
4280 return s->iformat->read_pause(s);
4282 return avio_pause(s->pb, 1);
4283 return AVERROR(ENOSYS);
4286 int ff_stream_encode_params_copy(AVStream *dst, const AVStream *src)
4291 dst->time_base = src->time_base;
4292 dst->nb_frames = src->nb_frames;
4293 dst->disposition = src->disposition;
4294 dst->sample_aspect_ratio = src->sample_aspect_ratio;
4295 dst->avg_frame_rate = src->avg_frame_rate;
4296 dst->r_frame_rate = src->r_frame_rate;
4298 av_dict_free(&dst->metadata);
4299 ret = av_dict_copy(&dst->metadata, src->metadata, 0);
4303 ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
4307 /* Free existing side data*/
4308 for (i = 0; i < dst->nb_side_data; i++)
4309 av_free(dst->side_data[i].data);
4310 av_freep(&dst->side_data);
4311 dst->nb_side_data = 0;
4313 /* Copy side data if present */
4314 if (src->nb_side_data) {
4315 dst->side_data = av_mallocz_array(src->nb_side_data,
4316 sizeof(AVPacketSideData));
4317 if (!dst->side_data)
4318 return AVERROR(ENOMEM);
4319 dst->nb_side_data = src->nb_side_data;
4321 for (i = 0; i < src->nb_side_data; i++) {
4322 uint8_t *data = av_memdup(src->side_data[i].data,
4323 src->side_data[i].size);
4325 return AVERROR(ENOMEM);
4326 dst->side_data[i].type = src->side_data[i].type;
4327 dst->side_data[i].size = src->side_data[i].size;
4328 dst->side_data[i].data = data;
4332 #if FF_API_LAVF_FFSERVER
4333 FF_DISABLE_DEPRECATION_WARNINGS
4334 av_freep(&dst->recommended_encoder_configuration);
4335 if (src->recommended_encoder_configuration) {
4336 const char *conf_str = src->recommended_encoder_configuration;
4337 dst->recommended_encoder_configuration = av_strdup(conf_str);
4338 if (!dst->recommended_encoder_configuration)
4339 return AVERROR(ENOMEM);
4341 FF_ENABLE_DEPRECATION_WARNINGS
4347 static void free_stream(AVStream **pst)
4349 AVStream *st = *pst;
4355 for (i = 0; i < st->nb_side_data; i++)
4356 av_freep(&st->side_data[i].data);
4357 av_freep(&st->side_data);
4360 av_parser_close(st->parser);
4362 if (st->attached_pic.data)
4363 av_packet_unref(&st->attached_pic);
4366 avcodec_free_context(&st->internal->avctx);
4367 av_bsf_free(&st->internal->bsfc);
4368 av_freep(&st->internal->priv_pts);
4369 av_freep(&st->internal->index_entries);
4370 av_freep(&st->internal->probe_data.buf);
4372 av_bsf_free(&st->internal->extract_extradata.bsf);
4373 av_packet_free(&st->internal->extract_extradata.pkt);
4375 if (st->internal->info)
4376 av_freep(&st->internal->info->duration_error);
4377 av_freep(&st->internal->info);
4379 av_freep(&st->internal);
4381 av_dict_free(&st->metadata);
4382 avcodec_parameters_free(&st->codecpar);
4383 #if FF_API_LAVF_AVCTX
4384 FF_DISABLE_DEPRECATION_WARNINGS
4385 avcodec_free_context(&st->codec);
4386 FF_ENABLE_DEPRECATION_WARNINGS
4388 av_freep(&st->priv_data);
4389 #if FF_API_LAVF_FFSERVER
4390 FF_DISABLE_DEPRECATION_WARNINGS
4391 av_freep(&st->recommended_encoder_configuration);
4392 FF_ENABLE_DEPRECATION_WARNINGS
4398 void ff_free_stream(AVFormatContext *s, AVStream *st)
4400 av_assert0(s->nb_streams>0);
4401 av_assert0(s->streams[ s->nb_streams - 1 ] == st);
4403 free_stream(&s->streams[ --s->nb_streams ]);
4406 void avformat_free_context(AVFormatContext *s)
4413 if (s->oformat && s->oformat->deinit && s->internal->initialized)
4414 s->oformat->deinit(s);
4417 if (s->iformat && s->iformat->priv_class && s->priv_data)
4418 av_opt_free(s->priv_data);
4419 if (s->oformat && s->oformat->priv_class && s->priv_data)
4420 av_opt_free(s->priv_data);
4422 for (i = 0; i < s->nb_streams; i++)
4423 free_stream(&s->streams[i]);
4426 for (i = 0; i < s->nb_programs; i++) {
4427 av_dict_free(&s->programs[i]->metadata);
4428 av_freep(&s->programs[i]->stream_index);
4429 av_freep(&s->programs[i]);
4433 av_freep(&s->programs);
4434 av_freep(&s->priv_data);
4435 while (s->nb_chapters--) {
4436 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
4437 av_freep(&s->chapters[s->nb_chapters]);
4439 av_freep(&s->chapters);
4440 av_dict_free(&s->metadata);
4441 av_dict_free(&s->internal->id3v2_meta);
4442 av_freep(&s->streams);
4443 flush_packet_queue(s);
4444 av_freep(&s->internal);
4449 void avformat_close_input(AVFormatContext **ps)
4460 if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
4461 (s->flags & AVFMT_FLAG_CUSTOM_IO))
4464 flush_packet_queue(s);
4467 if (s->iformat->read_close)
4468 s->iformat->read_close(s);
4470 avformat_free_context(s);
4477 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
4483 if (s->nb_streams >= FFMIN(s->max_streams, INT_MAX/sizeof(*streams))) {
4484 if (s->max_streams < INT_MAX/sizeof(*streams))
4485 av_log(s, AV_LOG_ERROR, "Number of streams exceeds max_streams parameter (%d), see the documentation if you wish to increase it\n", s->max_streams);
4488 streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
4491 s->streams = streams;
4493 st = av_mallocz(sizeof(AVStream));
4497 #if FF_API_LAVF_AVCTX
4498 FF_DISABLE_DEPRECATION_WARNINGS
4499 st->codec = avcodec_alloc_context3(c);
4504 FF_ENABLE_DEPRECATION_WARNINGS
4507 st->internal = av_mallocz(sizeof(*st->internal));
4511 st->internal->info = av_mallocz(sizeof(*st->internal->info));
4512 if (!st->internal->info)
4514 st->internal->info->last_dts = AV_NOPTS_VALUE;
4516 st->codecpar = avcodec_parameters_alloc();
4520 st->internal->avctx = avcodec_alloc_context3(NULL);
4521 if (!st->internal->avctx)
4525 #if FF_API_LAVF_AVCTX
4526 FF_DISABLE_DEPRECATION_WARNINGS
4527 /* no default bitrate if decoding */
4528 st->codec->bit_rate = 0;
4529 FF_ENABLE_DEPRECATION_WARNINGS
4532 /* default pts setting is MPEG-like */
4533 avpriv_set_pts_info(st, 33, 1, 90000);
4534 /* we set the current DTS to 0 so that formats without any timestamps
4535 * but durations get some timestamps, formats with some unknown
4536 * timestamps have their first few packets buffered and the
4537 * timestamps corrected before they are returned to the user */
4538 st->cur_dts = RELATIVE_TS_BASE;
4540 st->cur_dts = AV_NOPTS_VALUE;
4543 st->index = s->nb_streams;
4544 st->start_time = AV_NOPTS_VALUE;
4545 st->duration = AV_NOPTS_VALUE;
4546 st->first_dts = AV_NOPTS_VALUE;
4547 st->probe_packets = s->max_probe_packets;
4548 st->internal->pts_wrap_reference = AV_NOPTS_VALUE;
4549 st->internal->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4551 st->last_IP_pts = AV_NOPTS_VALUE;
4552 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
4553 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
4554 st->internal->pts_buffer[i] = AV_NOPTS_VALUE;
4556 st->sample_aspect_ratio = (AVRational) { 0, 1 };
4558 #if FF_API_R_FRAME_RATE
4559 st->internal->info->last_dts = AV_NOPTS_VALUE;
4561 st->internal->info->fps_first_dts = AV_NOPTS_VALUE;
4562 st->internal->info->fps_last_dts = AV_NOPTS_VALUE;
4564 st->internal->inject_global_side_data = s->internal->inject_global_side_data;
4566 st->internal->need_context_update = 1;
4568 s->streams[s->nb_streams++] = st;
4575 AVProgram *av_new_program(AVFormatContext *ac, int id)
4577 AVProgram *program = NULL;
4580 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
4582 for (i = 0; i < ac->nb_programs; i++)
4583 if (ac->programs[i]->id == id)
4584 program = ac->programs[i];
4587 program = av_mallocz(sizeof(AVProgram));
4590 dynarray_add(&ac->programs, &ac->nb_programs, program);
4591 program->discard = AVDISCARD_NONE;
4592 program->pmt_version = -1;
4594 program->pts_wrap_reference = AV_NOPTS_VALUE;
4595 program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
4596 program->start_time =
4597 program->end_time = AV_NOPTS_VALUE;
4602 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
4603 int64_t start, int64_t end, const char *title)
4605 AVChapter *chapter = NULL;
4608 if (end != AV_NOPTS_VALUE && start > end) {
4609 av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
4613 for (i = 0; i < s->nb_chapters; i++)
4614 if (s->chapters[i]->id == id)
4615 chapter = s->chapters[i];
4618 chapter = av_mallocz(sizeof(AVChapter));
4621 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
4623 av_dict_set(&chapter->metadata, "title", title, 0);
4625 chapter->time_base = time_base;
4626 chapter->start = start;
4632 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
4635 AVProgram *program = NULL;
4638 if (idx >= ac->nb_streams) {
4639 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
4643 for (i = 0; i < ac->nb_programs; i++) {
4644 if (ac->programs[i]->id != progid)
4646 program = ac->programs[i];
4647 for (j = 0; j < program->nb_stream_indexes; j++)
4648 if (program->stream_index[j] == idx)
4651 tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
4654 program->stream_index = tmp;
4655 program->stream_index[program->nb_stream_indexes++] = idx;
4660 uint64_t ff_ntp_time(void)
4662 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
4665 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us)
4667 uint64_t ntp_ts, frac_part, sec;
4670 //current ntp time in seconds and micro seconds
4671 sec = ntp_time_us / 1000000;
4672 usec = ntp_time_us % 1000000;
4674 //encoding in ntp timestamp format
4675 frac_part = usec * 0xFFFFFFFFULL;
4676 frac_part /= 1000000;
4678 if (sec > 0xFFFFFFFFULL)
4679 av_log(NULL, AV_LOG_WARNING, "NTP time format roll over detected\n");
4682 ntp_ts |= frac_part;
4687 int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags)
4690 char *q, buf1[20], c;
4691 int nd, len, percentd_found;
4703 while (av_isdigit(*p))
4704 nd = nd * 10 + *p++ - '0';
4706 } while (av_isdigit(c));
4712 if (!(flags & AV_FRAME_FILENAME_FLAGS_MULTIPLE) && percentd_found)
4717 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
4719 if ((q - buf + len) > buf_size - 1)
4721 memcpy(q, buf1, len);
4729 if ((q - buf) < buf_size - 1)
4733 if (!percentd_found)
4742 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
4744 return av_get_frame_filename2(buf, buf_size, path, number, 0);
4747 void av_url_split(char *proto, int proto_size,
4748 char *authorization, int authorization_size,
4749 char *hostname, int hostname_size,
4750 int *port_ptr, char *path, int path_size, const char *url)
4752 const char *p, *ls, *at, *at2, *col, *brk;
4758 if (authorization_size > 0)
4759 authorization[0] = 0;
4760 if (hostname_size > 0)
4765 /* parse protocol */
4766 if ((p = strchr(url, ':'))) {
4767 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
4774 /* no protocol means plain filename */
4775 av_strlcpy(path, url, path_size);
4779 /* separate path from hostname */
4780 ls = p + strcspn(p, "/?#");
4781 av_strlcpy(path, ls, path_size);
4783 /* the rest is hostname, use that to parse auth/port */
4785 /* authorization (user[:pass]@hostname) */
4787 while ((at = strchr(p, '@')) && at < ls) {
4788 av_strlcpy(authorization, at2,
4789 FFMIN(authorization_size, at + 1 - at2));
4790 p = at + 1; /* skip '@' */
4793 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4795 av_strlcpy(hostname, p + 1,
4796 FFMIN(hostname_size, brk - p));
4797 if (brk[1] == ':' && port_ptr)
4798 *port_ptr = atoi(brk + 2);
4799 } else if ((col = strchr(p, ':')) && col < ls) {
4800 av_strlcpy(hostname, p,
4801 FFMIN(col + 1 - p, hostname_size));
4803 *port_ptr = atoi(col + 1);
4805 av_strlcpy(hostname, p,
4806 FFMIN(ls + 1 - p, hostname_size));
4810 int ff_mkdir_p(const char *path)
4813 char *temp = av_strdup(path);
4817 if (!path || !temp) {
4821 if (!av_strncasecmp(temp, "/", 1) || !av_strncasecmp(temp, "\\", 1)) {
4823 } else if (!av_strncasecmp(temp, "./", 2) || !av_strncasecmp(temp, ".\\", 2)) {
4827 for ( ; *pos != '\0'; ++pos) {
4828 if (*pos == '/' || *pos == '\\') {
4831 ret = mkdir(temp, 0755);
4836 if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
4837 ret = mkdir(temp, 0755);
4844 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4847 static const char hex_table_uc[16] = { '0', '1', '2', '3',
4850 'C', 'D', 'E', 'F' };
4851 static const char hex_table_lc[16] = { '0', '1', '2', '3',
4854 'c', 'd', 'e', 'f' };
4855 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4857 for (i = 0; i < s; i++) {
4858 buff[i * 2] = hex_table[src[i] >> 4];
4859 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4865 int ff_hex_to_data(uint8_t *data, const char *p)
4872 p += strspn(p, SPACE_CHARS);
4875 c = av_toupper((unsigned char) *p++);
4876 if (c >= '0' && c <= '9')
4878 else if (c >= 'A' && c <= 'F')
4893 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4894 unsigned int pts_num, unsigned int pts_den)
4897 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4898 if (new_tb.num != pts_num)
4899 av_log(NULL, AV_LOG_DEBUG,
4900 "st:%d removing common factor %d from timebase\n",
4901 s->index, pts_num / new_tb.num);
4903 av_log(NULL, AV_LOG_WARNING,
4904 "st:%d has too large timebase, reducing\n", s->index);
4906 if (new_tb.num <= 0 || new_tb.den <= 0) {
4907 av_log(NULL, AV_LOG_ERROR,
4908 "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4909 new_tb.num, new_tb.den,
4913 s->time_base = new_tb;
4914 #if FF_API_LAVF_AVCTX
4915 FF_DISABLE_DEPRECATION_WARNINGS
4916 s->codec->pkt_timebase = new_tb;
4917 FF_ENABLE_DEPRECATION_WARNINGS
4919 s->internal->avctx->pkt_timebase = new_tb;
4920 s->pts_wrap_bits = pts_wrap_bits;
4923 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4926 const char *ptr = str;
4928 /* Parse key=value pairs. */
4931 char *dest = NULL, *dest_end;
4932 int key_len, dest_len = 0;
4934 /* Skip whitespace and potential commas. */
4935 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4942 if (!(ptr = strchr(key, '=')))
4945 key_len = ptr - key;
4947 callback_get_buf(context, key, key_len, &dest, &dest_len);
4948 dest_end = dest + dest_len - 1;
4952 while (*ptr && *ptr != '\"') {
4956 if (dest && dest < dest_end)
4960 if (dest && dest < dest_end)
4968 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4969 if (dest && dest < dest_end)
4977 int ff_find_stream_index(AVFormatContext *s, int id)
4980 for (i = 0; i < s->nb_streams; i++)
4981 if (s->streams[i]->id == id)
4986 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
4990 unsigned int codec_tag;
4991 if (ofmt->query_codec)
4992 return ofmt->query_codec(codec_id, std_compliance);
4993 else if (ofmt->codec_tag)
4994 return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
4995 else if (codec_id == ofmt->video_codec ||
4996 codec_id == ofmt->audio_codec ||
4997 codec_id == ofmt->subtitle_codec ||
4998 codec_id == ofmt->data_codec)
5001 return AVERROR_PATCHWELCOME;
5004 int avformat_network_init(void)
5008 if ((ret = ff_network_init()) < 0)
5010 if ((ret = ff_tls_init()) < 0)
5016 int avformat_network_deinit(void)
5025 int ff_add_param_change(AVPacket *pkt, int32_t channels,
5026 uint64_t channel_layout, int32_t sample_rate,
5027 int32_t width, int32_t height)
5033 return AVERROR(EINVAL);
5036 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
5038 if (channel_layout) {
5040 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
5044 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
5046 if (width || height) {
5048 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
5050 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
5052 return AVERROR(ENOMEM);
5053 bytestream_put_le32(&data, flags);
5055 bytestream_put_le32(&data, channels);
5057 bytestream_put_le64(&data, channel_layout);
5059 bytestream_put_le32(&data, sample_rate);
5060 if (width || height) {
5061 bytestream_put_le32(&data, width);
5062 bytestream_put_le32(&data, height);
5067 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
5069 AVRational undef = {0, 1};
5070 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
5071 AVRational codec_sample_aspect_ratio = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
5072 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
5074 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
5075 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
5076 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
5077 stream_sample_aspect_ratio = undef;
5079 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
5080 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
5081 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
5082 frame_sample_aspect_ratio = undef;
5084 if (stream_sample_aspect_ratio.num)
5085 return stream_sample_aspect_ratio;
5087 return frame_sample_aspect_ratio;
5090 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
5092 AVRational fr = st->r_frame_rate;
5093 AVRational codec_fr = st->internal->avctx->framerate;
5094 AVRational avg_fr = st->avg_frame_rate;
5096 if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
5097 av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
5102 if (st->internal->avctx->ticks_per_frame > 1) {
5103 if ( codec_fr.num > 0 && codec_fr.den > 0 &&
5104 (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))
5112 * Matches a stream specifier (but ignores requested index).
5114 * @param indexptr set to point to the requested stream index if there is one
5116 * @return <0 on error
5117 * 0 if st is NOT a matching stream
5118 * >0 if st is a matching stream
5120 static int match_stream_specifier(AVFormatContext *s, AVStream *st,
5121 const char *spec, const char **indexptr, AVProgram **p)
5123 int match = 1; /* Stores if the specifier matches so far. */
5125 if (*spec <= '9' && *spec >= '0') { /* opt:index */
5129 } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
5130 *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
5131 enum AVMediaType type;
5135 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
5136 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
5137 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
5138 case 'd': type = AVMEDIA_TYPE_DATA; break;
5139 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
5140 case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
5141 default: av_assert0(0);
5143 if (*spec && *spec++ != ':') /* If we are not at the end, then another specifier must follow. */
5144 return AVERROR(EINVAL);
5146 #if FF_API_LAVF_AVCTX
5147 FF_DISABLE_DEPRECATION_WARNINGS
5148 if (type != st->codecpar->codec_type
5149 && (st->codecpar->codec_type != AVMEDIA_TYPE_UNKNOWN || st->codec->codec_type != type))
5151 FF_ENABLE_DEPRECATION_WARNINGS
5153 if (type != st->codecpar->codec_type)
5156 if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
5158 } else if (*spec == 'p' && *(spec + 1) == ':') {
5163 prog_id = strtol(spec, &endptr, 0);
5164 /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
5165 if (spec == endptr || (*endptr && *endptr++ != ':'))
5166 return AVERROR(EINVAL);
5169 for (i = 0; i < s->nb_programs; i++) {
5170 if (s->programs[i]->id != prog_id)
5173 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
5174 if (st->index == s->programs[i]->stream_index[j]) {
5177 *p = s->programs[i];
5186 } else if (*spec == '#' ||
5187 (*spec == 'i' && *(spec + 1) == ':')) {
5190 spec += 1 + (*spec == 'i');
5191 stream_id = strtol(spec, &endptr, 0);
5192 if (spec == endptr || *endptr) /* Disallow empty id and make sure we are at the end. */
5193 return AVERROR(EINVAL);
5194 return match && (stream_id == st->id);
5195 } else if (*spec == 'm' && *(spec + 1) == ':') {
5196 AVDictionaryEntry *tag;
5202 val = strchr(spec, ':');
5204 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
5206 return AVERROR(ENOMEM);
5208 tag = av_dict_get(st->metadata, key, NULL, 0);
5210 if (!val || !strcmp(tag->value, val + 1))
5219 return match && ret;
5220 } else if (*spec == 'u' && *(spec + 1) == '\0') {
5221 AVCodecParameters *par = st->codecpar;
5222 #if FF_API_LAVF_AVCTX
5223 FF_DISABLE_DEPRECATION_WARNINGS
5224 AVCodecContext *codec = st->codec;
5225 FF_ENABLE_DEPRECATION_WARNINGS
5228 switch (par->codec_type) {
5229 case AVMEDIA_TYPE_AUDIO:
5230 val = par->sample_rate && par->channels;
5231 #if FF_API_LAVF_AVCTX
5232 val = val || (codec->sample_rate && codec->channels);
5234 if (par->format == AV_SAMPLE_FMT_NONE
5235 #if FF_API_LAVF_AVCTX
5236 && codec->sample_fmt == AV_SAMPLE_FMT_NONE
5241 case AVMEDIA_TYPE_VIDEO:
5242 val = par->width && par->height;
5243 #if FF_API_LAVF_AVCTX
5244 val = val || (codec->width && codec->height);
5246 if (par->format == AV_PIX_FMT_NONE
5247 #if FF_API_LAVF_AVCTX
5248 && codec->pix_fmt == AV_PIX_FMT_NONE
5253 case AVMEDIA_TYPE_UNKNOWN:
5260 #if FF_API_LAVF_AVCTX
5261 return match && ((par->codec_id != AV_CODEC_ID_NONE || codec->codec_id != AV_CODEC_ID_NONE) && val != 0);
5263 return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
5266 return AVERROR(EINVAL);
5274 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
5279 const char *indexptr = NULL;
5280 AVProgram *p = NULL;
5283 ret = match_stream_specifier(s, st, spec, &indexptr, &p);
5290 index = strtol(indexptr, &endptr, 0);
5291 if (*endptr) { /* We can't have anything after the requested index. */
5292 ret = AVERROR(EINVAL);
5296 /* This is not really needed but saves us a loop for simple stream index specifiers. */
5297 if (spec == indexptr)
5298 return (index == st->index);
5300 /* If we requested a matching stream index, we have to ensure st is that. */
5301 nb_streams = p ? p->nb_stream_indexes : s->nb_streams;
5302 for (int i = 0; i < nb_streams && index >= 0; i++) {
5303 AVStream *candidate = p ? s->streams[p->stream_index[i]] : s->streams[i];
5304 ret = match_stream_specifier(s, candidate, spec, NULL, NULL);
5307 if (ret > 0 && index-- == 0 && st == candidate)
5313 if (ret == AVERROR(EINVAL))
5314 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
5318 int ff_generate_avci_extradata(AVStream *st)
5320 static const uint8_t avci100_1080p_extradata[] = {
5322 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5323 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5324 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5325 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
5326 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
5327 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
5328 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
5329 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
5330 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
5332 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5335 static const uint8_t avci100_1080i_extradata[] = {
5337 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5338 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
5339 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
5340 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
5341 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
5342 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
5343 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
5344 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
5345 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
5346 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
5347 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
5349 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
5352 static const uint8_t avci50_1080p_extradata[] = {
5354 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5355 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5356 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5357 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5358 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5359 0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
5360 0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
5361 0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
5362 0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
5364 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5367 static const uint8_t avci50_1080i_extradata[] = {
5369 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
5370 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5371 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5372 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
5373 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
5374 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
5375 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
5376 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
5377 0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
5378 0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
5379 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
5381 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5384 static const uint8_t avci100_720p_extradata[] = {
5386 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
5387 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
5388 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
5389 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
5390 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
5391 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
5392 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
5393 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
5394 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
5395 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
5397 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
5400 static const uint8_t avci50_720p_extradata[] = {
5402 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
5403 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
5404 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
5405 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
5406 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
5407 0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
5408 0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
5409 0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
5410 0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
5412 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
5416 const uint8_t *data = NULL;
5419 if (st->codecpar->width == 1920) {
5420 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5421 data = avci100_1080p_extradata;
5422 size = sizeof(avci100_1080p_extradata);
5424 data = avci100_1080i_extradata;
5425 size = sizeof(avci100_1080i_extradata);
5427 } else if (st->codecpar->width == 1440) {
5428 if (st->codecpar->field_order == AV_FIELD_PROGRESSIVE) {
5429 data = avci50_1080p_extradata;
5430 size = sizeof(avci50_1080p_extradata);
5432 data = avci50_1080i_extradata;
5433 size = sizeof(avci50_1080i_extradata);
5435 } else if (st->codecpar->width == 1280) {
5436 data = avci100_720p_extradata;
5437 size = sizeof(avci100_720p_extradata);
5438 } else if (st->codecpar->width == 960) {
5439 data = avci50_720p_extradata;
5440 size = sizeof(avci50_720p_extradata);
5446 if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
5448 memcpy(st->codecpar->extradata, data, size);
5453 uint8_t *av_stream_get_side_data(const AVStream *st,
5454 enum AVPacketSideDataType type, int *size)
5458 for (i = 0; i < st->nb_side_data; i++) {
5459 if (st->side_data[i].type == type) {
5461 *size = st->side_data[i].size;
5462 return st->side_data[i].data;
5470 int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
5471 uint8_t *data, size_t size)
5473 AVPacketSideData *sd, *tmp;
5476 for (i = 0; i < st->nb_side_data; i++) {
5477 sd = &st->side_data[i];
5479 if (sd->type == type) {
5480 av_freep(&sd->data);
5487 if ((unsigned)st->nb_side_data + 1 >= INT_MAX / sizeof(*st->side_data))
5488 return AVERROR(ERANGE);
5490 tmp = av_realloc(st->side_data, (st->nb_side_data + 1) * sizeof(*tmp));
5492 return AVERROR(ENOMEM);
5495 st->side_data = tmp;
5498 sd = &st->side_data[st->nb_side_data - 1];
5506 uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
5510 uint8_t *data = av_malloc(size);
5515 ret = av_stream_add_side_data(st, type, data, size);
5524 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
5527 const AVBitStreamFilter *bsf;
5530 av_assert0(!st->internal->bsfc);
5532 if (!(bsf = av_bsf_get_by_name(name))) {
5533 av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
5534 return AVERROR_BSF_NOT_FOUND;
5537 if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
5540 bsfc->time_base_in = st->time_base;
5541 if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
5546 if (args && bsfc->filter->priv_class) {
5547 const AVOption *opt = av_opt_next(bsfc->priv_data, NULL);
5548 const char * shorthand[2] = {NULL};
5551 shorthand[0] = opt->name;
5553 if ((ret = av_opt_set_from_string(bsfc->priv_data, args, shorthand, "=", ":")) < 0) {
5559 if ((ret = av_bsf_init(bsfc)) < 0) {
5564 st->internal->bsfc = bsfc;
5566 av_log(NULL, AV_LOG_VERBOSE,
5567 "Automatically inserted bitstream filter '%s'; args='%s'\n",
5568 name, args ? args : "");
5573 FF_DISABLE_DEPRECATION_WARNINGS
5574 int av_apply_bitstream_filters(AVCodecContext *codec, AVPacket *pkt,
5575 AVBitStreamFilterContext *bsfc)
5579 AVPacket new_pkt = *pkt;
5580 int a = av_bitstream_filter_filter(bsfc, codec, NULL,
5581 &new_pkt.data, &new_pkt.size,
5582 pkt->data, pkt->size,
5583 pkt->flags & AV_PKT_FLAG_KEY);
5584 if (a == 0 && new_pkt.size == 0 && new_pkt.side_data_elems == 0) {
5585 av_packet_unref(pkt);
5586 memset(pkt, 0, sizeof(*pkt));
5589 if(a == 0 && new_pkt.data != pkt->data) {
5590 uint8_t *t = av_malloc(new_pkt.size + AV_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
5592 memcpy(t, new_pkt.data, new_pkt.size);
5593 memset(t + new_pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
5598 a = AVERROR(ENOMEM);
5602 new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
5603 av_buffer_default_free, NULL, 0);
5605 pkt->side_data = NULL;
5606 pkt->side_data_elems = 0;
5607 av_packet_unref(pkt);
5609 av_freep(&new_pkt.data);
5610 a = AVERROR(ENOMEM);
5614 av_log(codec, AV_LOG_ERROR,
5615 "Failed to open bitstream filter %s for stream %d with codec %s",
5616 bsfc->filter->name, pkt->stream_index,
5617 codec->codec ? codec->codec->name : "copy");
5627 FF_ENABLE_DEPRECATION_WARNINGS
5630 int ff_format_output_open(AVFormatContext *s, const char *url, AVDictionary **options)
5633 return AVERROR(EINVAL);
5635 if (!(s->oformat->flags & AVFMT_NOFILE))
5636 return s->io_open(s, &s->pb, url, AVIO_FLAG_WRITE, options);
5640 void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
5643 s->io_close(s, *pb);
5647 int ff_is_http_proto(char *filename) {
5648 const char *proto = avio_find_protocol_name(filename);
5649 return proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
5652 int ff_parse_creation_time_metadata(AVFormatContext *s, int64_t *timestamp, int return_seconds)
5654 AVDictionaryEntry *entry;
5655 int64_t parsed_timestamp;
5657 if ((entry = av_dict_get(s->metadata, "creation_time", NULL, 0))) {
5658 if ((ret = av_parse_time(&parsed_timestamp, entry->value, 0)) >= 0) {
5659 *timestamp = return_seconds ? parsed_timestamp / 1000000 : parsed_timestamp;
5662 av_log(s, AV_LOG_WARNING, "Failed to parse creation_time %s\n", entry->value);
5669 int ff_standardize_creation_time(AVFormatContext *s)
5672 int ret = ff_parse_creation_time_metadata(s, ×tamp, 0);
5674 return avpriv_dict_set_timestamp(&s->metadata, "creation_time", timestamp);
5678 int ff_get_packet_palette(AVFormatContext *s, AVPacket *pkt, int ret, uint32_t *palette)
5683 side_data = av_packet_get_side_data(pkt, AV_PKT_DATA_PALETTE, &size);
5685 if (size != AVPALETTE_SIZE) {
5686 av_log(s, AV_LOG_ERROR, "Invalid palette side data\n");
5687 return AVERROR_INVALIDDATA;
5689 memcpy(palette, side_data, AVPALETTE_SIZE);
5693 if (ret == CONTAINS_PAL) {
5695 for (i = 0; i < AVPALETTE_COUNT; i++)
5696 palette[i] = AV_RL32(pkt->data + pkt->size - AVPALETTE_SIZE + i*4);
5703 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf)
5708 ret = av_bprint_finalize(buf, &str);
5711 if (!av_bprint_is_complete(buf)) {
5713 return AVERROR(ENOMEM);
5716 par->extradata = str;
5717 /* Note: the string is NUL terminated (so extradata can be read as a
5718 * string), but the ending character is not accounted in the size (in
5719 * binary formats you are likely not supposed to mux that character). When
5720 * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE
5722 par->extradata_size = buf->len;
5726 int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
5727 AVStream *ost, const AVStream *ist,
5728 enum AVTimebaseSource copy_tb)
5730 //TODO: use [io]st->internal->avctx
5731 const AVCodecContext *dec_ctx;
5732 AVCodecContext *enc_ctx;
5734 #if FF_API_LAVF_AVCTX
5735 FF_DISABLE_DEPRECATION_WARNINGS
5736 dec_ctx = ist->codec;
5737 enc_ctx = ost->codec;
5738 FF_ENABLE_DEPRECATION_WARNINGS
5740 dec_ctx = ist->internal->avctx;
5741 enc_ctx = ost->internal->avctx;
5744 enc_ctx->time_base = ist->time_base;
5746 * Avi is a special case here because it supports variable fps but
5747 * having the fps and timebase differe significantly adds quite some
5750 if (!strcmp(ofmt->name, "avi")) {
5751 #if FF_API_R_FRAME_RATE
5752 if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
5753 && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
5754 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
5755 && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx->time_base)
5756 && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
5757 || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
5758 enc_ctx->time_base.num = ist->r_frame_rate.den;
5759 enc_ctx->time_base.den = 2*ist->r_frame_rate.num;
5760 enc_ctx->ticks_per_frame = 2;
5763 if (copy_tb == AVFMT_TBCF_AUTO && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->time_base)
5764 && av_q2d(ist->time_base) < 1.0/500
5765 || copy_tb == AVFMT_TBCF_DECODER) {
5766 enc_ctx->time_base = dec_ctx->time_base;
5767 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5768 enc_ctx->time_base.den *= 2;
5769 enc_ctx->ticks_per_frame = 2;
5771 } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
5772 && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
5773 if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx->time_base.den
5774 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->time_base)
5775 && av_q2d(ist->time_base) < 1.0/500
5776 || copy_tb == AVFMT_TBCF_DECODER) {
5777 enc_ctx->time_base = dec_ctx->time_base;
5778 enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
5782 if ((enc_ctx->codec_tag == AV_RL32("tmcd") || ost->codecpar->codec_tag == AV_RL32("tmcd"))
5783 && dec_ctx->time_base.num < dec_ctx->time_base.den
5784 && dec_ctx->time_base.num > 0
5785 && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
5786 enc_ctx->time_base = dec_ctx->time_base;
5789 if (ost->avg_frame_rate.num)
5790 enc_ctx->time_base = av_inv_q(ost->avg_frame_rate);
5792 av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
5793 enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
5798 AVRational av_stream_get_codec_timebase(const AVStream *st)
5800 // See avformat_transfer_internal_stream_timing_info() TODO.
5801 #if FF_API_LAVF_AVCTX
5802 FF_DISABLE_DEPRECATION_WARNINGS
5803 return st->codec->time_base;
5804 FF_ENABLE_DEPRECATION_WARNINGS
5806 return st->internal->avctx->time_base;
5810 void ff_format_set_url(AVFormatContext *s, char *url)
5815 #if FF_API_FORMAT_FILENAME
5816 FF_DISABLE_DEPRECATION_WARNINGS
5817 av_strlcpy(s->filename, url, sizeof(s->filename));
5818 FF_ENABLE_DEPRECATION_WARNINGS