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
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/dict.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/time.h"
38 #include "libavutil/timestamp.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/internal.h"
42 #include "libavcodec/raw.h"
44 #include "audiointerleave.h"
46 #include "avio_internal.h"
56 #include "libavutil/ffversion.h"
57 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
61 * various utility functions for use within FFmpeg
64 unsigned avformat_version(void)
66 av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
67 return LIBAVFORMAT_VERSION_INT;
70 const char *avformat_configuration(void)
72 return FFMPEG_CONFIGURATION;
75 const char *avformat_license(void)
77 #define LICENSE_PREFIX "libavformat license: "
78 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
81 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
83 static int is_relative(int64_t ts) {
84 return ts > (RELATIVE_TS_BASE - (1LL<<48));
88 * Wrap a given time stamp, if there is an indication for an overflow
91 * @param timestamp the time stamp to wrap
92 * @return resulting time stamp
94 static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
96 if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE &&
97 st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
98 if (st->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
99 timestamp < st->pts_wrap_reference)
100 return timestamp + (1ULL << st->pts_wrap_bits);
101 else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
102 timestamp >= st->pts_wrap_reference)
103 return timestamp - (1ULL << st->pts_wrap_bits);
108 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
109 MAKE_ACCESSORS(AVStream, stream, char *, recommended_encoder_configuration)
110 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
111 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
112 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
113 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
114 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
115 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
116 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
118 int64_t av_stream_get_end_pts(const AVStream *st)
123 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
128 void av_format_inject_global_side_data(AVFormatContext *s)
131 s->internal->inject_global_side_data = 1;
132 for (i = 0; i < s->nb_streams; i++) {
133 AVStream *st = s->streams[i];
134 st->inject_global_side_data = 1;
138 int ff_copy_whitelists(AVFormatContext *dst, AVFormatContext *src)
140 av_assert0(!dst->codec_whitelist && !dst->format_whitelist);
141 dst-> codec_whitelist = av_strdup(src->codec_whitelist);
142 dst->format_whitelist = av_strdup(src->format_whitelist);
143 if ( (src-> codec_whitelist && !dst-> codec_whitelist)
144 || (src->format_whitelist && !dst->format_whitelist)) {
145 av_log(dst, AV_LOG_ERROR, "Failed to duplicate whitelist\n");
146 return AVERROR(ENOMEM);
151 static const AVCodec *find_decoder(AVFormatContext *s, AVStream *st, enum AVCodecID codec_id)
153 if (st->codec->codec)
154 return st->codec->codec;
156 switch (st->codec->codec_type) {
157 case AVMEDIA_TYPE_VIDEO:
158 if (s->video_codec) return s->video_codec;
160 case AVMEDIA_TYPE_AUDIO:
161 if (s->audio_codec) return s->audio_codec;
163 case AVMEDIA_TYPE_SUBTITLE:
164 if (s->subtitle_codec) return s->subtitle_codec;
168 return avcodec_find_decoder(codec_id);
171 int av_format_get_probe_score(const AVFormatContext *s)
173 return s->probe_score;
176 /* an arbitrarily chosen "sane" max packet size -- 50M */
177 #define SANE_CHUNK_SIZE (50000000)
179 int ffio_limit(AVIOContext *s, int size)
181 if (s->maxsize>= 0) {
182 int64_t remaining= s->maxsize - avio_tell(s);
183 if (remaining < size) {
184 int64_t newsize = avio_size(s);
185 if (!s->maxsize || s->maxsize<newsize)
186 s->maxsize = newsize - !newsize;
187 remaining= s->maxsize - avio_tell(s);
188 remaining= FFMAX(remaining, 0);
191 if (s->maxsize>= 0 && remaining+1 < size) {
192 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
199 /* Read the data in sane-sized chunks and append to pkt.
200 * Return the number of bytes read or an error. */
201 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
203 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
204 int orig_size = pkt->size;
208 int prev_size = pkt->size;
211 /* When the caller requests a lot of data, limit it to the amount
212 * left in file or SANE_CHUNK_SIZE when it is not known. */
214 if (read_size > SANE_CHUNK_SIZE/10) {
215 read_size = ffio_limit(s, read_size);
216 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
218 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
221 ret = av_grow_packet(pkt, read_size);
225 ret = avio_read(s, pkt->data + prev_size, read_size);
226 if (ret != read_size) {
227 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
234 pkt->flags |= AV_PKT_FLAG_CORRUPT;
239 return pkt->size > orig_size ? pkt->size - orig_size : ret;
242 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
247 pkt->pos = avio_tell(s);
249 return append_packet_chunked(s, pkt, size);
252 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
255 return av_get_packet(s, pkt, size);
256 return append_packet_chunked(s, pkt, size);
259 int av_filename_number_test(const char *filename)
263 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
266 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
269 static const struct {
272 enum AVMediaType type;
274 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
275 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
276 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
277 { "dvbsub", AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
278 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
279 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
280 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
281 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
282 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
283 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
284 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
288 AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
290 if (fmt && st->request_probe <= score) {
292 av_log(s, AV_LOG_DEBUG,
293 "Probe with size=%d, packets=%d detected %s with score=%d\n",
294 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
296 for (i = 0; fmt_id_type[i].name; i++) {
297 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
298 st->codec->codec_id = fmt_id_type[i].id;
299 st->codec->codec_type = fmt_id_type[i].type;
307 /************************************************************/
308 /* input media file */
310 int av_demuxer_open(AVFormatContext *ic) {
313 if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
314 av_log(ic, AV_LOG_ERROR, "Format not on whitelist\n");
315 return AVERROR(EINVAL);
318 if (ic->iformat->read_header) {
319 err = ic->iformat->read_header(ic);
324 if (ic->pb && !ic->data_offset)
325 ic->data_offset = avio_tell(ic->pb);
330 /* Open input file and probe the format if necessary. */
331 static int init_input(AVFormatContext *s, const char *filename,
332 AVDictionary **options)
335 AVProbeData pd = { filename, NULL, 0 };
336 int score = AVPROBE_SCORE_RETRY;
339 s->flags |= AVFMT_FLAG_CUSTOM_IO;
341 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
342 s, 0, s->format_probesize);
343 else if (s->iformat->flags & AVFMT_NOFILE)
344 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
345 "will be ignored with AVFMT_NOFILE format.\n");
349 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
350 (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
353 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
354 &s->interrupt_callback, options)) < 0)
358 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
359 s, 0, s->format_probesize);
362 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
363 AVPacketList **plast_pktl)
365 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
370 (*plast_pktl)->next = pktl;
372 *packet_buffer = pktl;
374 /* Add the packet in the buffered packet list. */
380 int avformat_queue_attached_pictures(AVFormatContext *s)
383 for (i = 0; i < s->nb_streams; i++)
384 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
385 s->streams[i]->discard < AVDISCARD_ALL) {
386 AVPacket copy = s->streams[i]->attached_pic;
387 if (copy.size <= 0) {
388 av_log(s, AV_LOG_WARNING,
389 "Attached picture on stream %d has invalid size, "
393 copy.buf = av_buffer_ref(copy.buf);
395 return AVERROR(ENOMEM);
397 add_to_pktbuf(&s->raw_packet_buffer, ©,
398 &s->raw_packet_buffer_end);
403 int avformat_open_input(AVFormatContext **ps, const char *filename,
404 AVInputFormat *fmt, AVDictionary **options)
406 AVFormatContext *s = *ps;
408 AVDictionary *tmp = NULL;
409 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
411 if (!s && !(s = avformat_alloc_context()))
412 return AVERROR(ENOMEM);
414 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
415 return AVERROR(EINVAL);
421 av_dict_copy(&tmp, *options, 0);
423 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
426 if ((ret = init_input(s, filename, &tmp)) < 0)
428 s->probe_score = ret;
430 if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
431 av_log(s, AV_LOG_ERROR, "Format not on whitelist\n");
432 ret = AVERROR(EINVAL);
436 avio_skip(s->pb, s->skip_initial_bytes);
438 /* Check filename in case an image number is expected. */
439 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
440 if (!av_filename_number_test(filename)) {
441 ret = AVERROR(EINVAL);
446 s->duration = s->start_time = AV_NOPTS_VALUE;
447 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
449 /* Allocate private data. */
450 if (s->iformat->priv_data_size > 0) {
451 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
452 ret = AVERROR(ENOMEM);
455 if (s->iformat->priv_class) {
456 *(const AVClass **) s->priv_data = s->iformat->priv_class;
457 av_opt_set_defaults(s->priv_data);
458 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
463 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
465 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, 0);
467 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
468 if ((ret = s->iformat->read_header(s)) < 0)
471 if (id3v2_extra_meta) {
472 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
473 !strcmp(s->iformat->name, "tta")) {
474 if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
477 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
479 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
481 if ((ret = avformat_queue_attached_pictures(s)) < 0)
484 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
485 s->data_offset = avio_tell(s->pb);
487 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
490 av_dict_free(options);
497 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
499 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
501 avformat_free_context(s);
506 /*******************************************************/
508 static void force_codec_ids(AVFormatContext *s, AVStream *st)
510 switch (st->codec->codec_type) {
511 case AVMEDIA_TYPE_VIDEO:
512 if (s->video_codec_id)
513 st->codec->codec_id = s->video_codec_id;
515 case AVMEDIA_TYPE_AUDIO:
516 if (s->audio_codec_id)
517 st->codec->codec_id = s->audio_codec_id;
519 case AVMEDIA_TYPE_SUBTITLE:
520 if (s->subtitle_codec_id)
521 st->codec->codec_id = s->subtitle_codec_id;
526 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
528 if (st->request_probe>0) {
529 AVProbeData *pd = &st->probe_data;
531 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
535 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
537 av_log(s, AV_LOG_WARNING,
538 "Failed to reallocate probe buffer for stream %d\n",
543 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
544 pd->buf_size += pkt->size;
545 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
548 st->probe_packets = 0;
550 av_log(s, AV_LOG_WARNING,
551 "nothing to probe for stream %d\n", st->index);
555 end= s->raw_packet_buffer_remaining_size <= 0
556 || st->probe_packets<= 0;
558 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
559 int score = set_codec_from_probe_data(s, st, pd);
560 if ( (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
564 st->request_probe = -1;
565 if (st->codec->codec_id != AV_CODEC_ID_NONE) {
566 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
568 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
570 force_codec_ids(s, st);
576 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
578 int64_t ref = pkt->dts;
579 int i, pts_wrap_behavior;
580 int64_t pts_wrap_reference;
581 AVProgram *first_program;
583 if (ref == AV_NOPTS_VALUE)
585 if (st->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
587 ref &= (1LL << st->pts_wrap_bits)-1;
589 // reference time stamp should be 60 s before first time stamp
590 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
591 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
592 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
593 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
594 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
596 first_program = av_find_program_from_stream(s, NULL, stream_index);
598 if (!first_program) {
599 int default_stream_index = av_find_default_stream_index(s);
600 if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {
601 for (i = 0; i < s->nb_streams; i++) {
602 if (av_find_program_from_stream(s, NULL, i))
604 s->streams[i]->pts_wrap_reference = pts_wrap_reference;
605 s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;
609 st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;
610 st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;
614 AVProgram *program = first_program;
616 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
617 pts_wrap_reference = program->pts_wrap_reference;
618 pts_wrap_behavior = program->pts_wrap_behavior;
621 program = av_find_program_from_stream(s, program, stream_index);
624 // update every program with differing pts_wrap_reference
625 program = first_program;
627 if (program->pts_wrap_reference != pts_wrap_reference) {
628 for (i = 0; i<program->nb_stream_indexes; i++) {
629 s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;
630 s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;
633 program->pts_wrap_reference = pts_wrap_reference;
634 program->pts_wrap_behavior = pts_wrap_behavior;
636 program = av_find_program_from_stream(s, program, stream_index);
642 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
648 AVPacketList *pktl = s->raw_packet_buffer;
652 st = s->streams[pkt->stream_index];
653 if (s->raw_packet_buffer_remaining_size <= 0)
654 if ((err = probe_codec(s, st, NULL)) < 0)
656 if (st->request_probe <= 0) {
657 s->raw_packet_buffer = pktl->next;
658 s->raw_packet_buffer_remaining_size += pkt->size;
667 ret = s->iformat->read_packet(s, pkt);
669 if (!pktl || ret == AVERROR(EAGAIN))
671 for (i = 0; i < s->nb_streams; i++) {
673 if (st->probe_packets)
674 if ((err = probe_codec(s, st, NULL)) < 0)
676 av_assert0(st->request_probe <= 0);
681 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
682 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
683 av_log(s, AV_LOG_WARNING,
684 "Dropped corrupted packet (stream = %d)\n",
690 if (pkt->stream_index >= (unsigned)s->nb_streams) {
691 av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
695 st = s->streams[pkt->stream_index];
697 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
698 // correct first time stamps to negative values
699 if (!is_relative(st->first_dts))
700 st->first_dts = wrap_timestamp(st, st->first_dts);
701 if (!is_relative(st->start_time))
702 st->start_time = wrap_timestamp(st, st->start_time);
703 if (!is_relative(st->cur_dts))
704 st->cur_dts = wrap_timestamp(st, st->cur_dts);
707 pkt->dts = wrap_timestamp(st, pkt->dts);
708 pkt->pts = wrap_timestamp(st, pkt->pts);
710 force_codec_ids(s, st);
712 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
713 if (s->use_wallclock_as_timestamps)
714 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
716 if (!pktl && st->request_probe <= 0)
719 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
720 s->raw_packet_buffer_remaining_size -= pkt->size;
722 if ((err = probe_codec(s, st, pkt)) < 0)
728 /**********************************************************/
730 static int determinable_frame_size(AVCodecContext *avctx)
732 if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
733 avctx->codec_id == AV_CODEC_ID_MP1 ||
734 avctx->codec_id == AV_CODEC_ID_MP2 ||
735 avctx->codec_id == AV_CODEC_ID_MP3/* ||
736 avctx->codec_id == AV_CODEC_ID_CELT*/)
742 * Return the frame duration in seconds. Return 0 if not available.
744 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
745 AVCodecParserContext *pc, AVPacket *pkt)
747 AVRational codec_framerate = s->iformat ? st->codec->framerate :
748 av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
753 switch (st->codec->codec_type) {
754 case AVMEDIA_TYPE_VIDEO:
755 if (st->r_frame_rate.num && !pc && s->iformat) {
756 *pnum = st->r_frame_rate.den;
757 *pden = st->r_frame_rate.num;
758 } else if (st->time_base.num * 1000LL > st->time_base.den) {
759 *pnum = st->time_base.num;
760 *pden = st->time_base.den;
761 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
762 av_assert0(st->codec->ticks_per_frame);
763 av_reduce(pnum, pden,
765 codec_framerate.num * (int64_t)st->codec->ticks_per_frame,
768 if (pc && pc->repeat_pict) {
769 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
770 av_reduce(pnum, pden,
771 (*pnum) * (1LL + pc->repeat_pict),
775 /* If this codec can be interlaced or progressive then we need
776 * a parser to compute duration of a packet. Thus if we have
777 * no parser in such case leave duration undefined. */
778 if (st->codec->ticks_per_frame > 1 && !pc)
782 case AVMEDIA_TYPE_AUDIO:
783 frame_size = av_get_audio_frame_duration(st->codec, pkt->size);
784 if (frame_size <= 0 || st->codec->sample_rate <= 0)
787 *pden = st->codec->sample_rate;
794 static int is_intra_only(AVCodecContext *enc) {
795 const AVCodecDescriptor *desc;
797 if (enc->codec_type != AVMEDIA_TYPE_VIDEO)
800 desc = av_codec_get_codec_descriptor(enc);
802 desc = avcodec_descriptor_get(enc->codec_id);
803 av_codec_set_codec_descriptor(enc, desc);
806 return !!(desc->props & AV_CODEC_PROP_INTRA_ONLY);
810 static int has_decode_delay_been_guessed(AVStream *st)
812 if (st->codec->codec_id != AV_CODEC_ID_H264) return 1;
813 if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
815 #if CONFIG_H264_DECODER
816 if (st->codec->has_b_frames &&
817 avpriv_h264_has_num_reorder_frames(st->codec) == st->codec->has_b_frames)
820 if (st->codec->has_b_frames<3)
821 return st->nb_decoded_frames >= 7;
822 else if (st->codec->has_b_frames<4)
823 return st->nb_decoded_frames >= 18;
825 return st->nb_decoded_frames >= 20;
828 static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
832 if (pktl == s->packet_buffer_end)
833 return s->parse_queue;
837 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
838 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
839 st->codec->codec_id != AV_CODEC_ID_HEVC;
842 int delay = st->codec->has_b_frames;
845 if (dts == AV_NOPTS_VALUE) {
846 int64_t best_score = INT64_MAX;
847 for (i = 0; i<delay; i++) {
848 if (st->pts_reorder_error_count[i]) {
849 int64_t score = st->pts_reorder_error[i] / st->pts_reorder_error_count[i];
850 if (score < best_score) {
857 for (i = 0; i<delay; i++) {
858 if (pts_buffer[i] != AV_NOPTS_VALUE) {
859 int64_t diff = FFABS(pts_buffer[i] - dts)
860 + (uint64_t)st->pts_reorder_error[i];
861 diff = FFMAX(diff, st->pts_reorder_error[i]);
862 st->pts_reorder_error[i] = diff;
863 st->pts_reorder_error_count[i]++;
864 if (st->pts_reorder_error_count[i] > 250) {
865 st->pts_reorder_error[i] >>= 1;
866 st->pts_reorder_error_count[i] >>= 1;
873 if (dts == AV_NOPTS_VALUE)
879 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
880 int64_t dts, int64_t pts, AVPacket *pkt)
882 AVStream *st = s->streams[stream_index];
883 AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
884 int64_t pts_buffer[MAX_REORDER_DELAY+1];
888 if (st->first_dts != AV_NOPTS_VALUE ||
889 dts == AV_NOPTS_VALUE ||
890 st->cur_dts == AV_NOPTS_VALUE ||
894 delay = st->codec->has_b_frames;
895 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
897 shift = st->first_dts - RELATIVE_TS_BASE;
899 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
900 pts_buffer[i] = AV_NOPTS_VALUE;
902 if (is_relative(pts))
905 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
906 if (pktl->pkt.stream_index != stream_index)
908 if (is_relative(pktl->pkt.pts))
909 pktl->pkt.pts += shift;
911 if (is_relative(pktl->pkt.dts))
912 pktl->pkt.dts += shift;
914 if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
915 st->start_time = pktl->pkt.pts;
917 if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
918 pts_buffer[0] = pktl->pkt.pts;
919 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
920 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
922 pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);
926 if (st->start_time == AV_NOPTS_VALUE)
927 st->start_time = pts;
930 static void update_initial_durations(AVFormatContext *s, AVStream *st,
931 int stream_index, int duration)
933 AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
934 int64_t cur_dts = RELATIVE_TS_BASE;
936 if (st->first_dts != AV_NOPTS_VALUE) {
937 if (st->update_initial_durations_done)
939 st->update_initial_durations_done = 1;
940 cur_dts = st->first_dts;
941 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
942 if (pktl->pkt.stream_index == stream_index) {
943 if (pktl->pkt.pts != pktl->pkt.dts ||
944 pktl->pkt.dts != AV_NOPTS_VALUE ||
950 if (pktl && pktl->pkt.dts != st->first_dts) {
951 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %d) in the queue\n",
952 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
956 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
959 pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
960 st->first_dts = cur_dts;
961 } else if (st->cur_dts != RELATIVE_TS_BASE)
964 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
965 if (pktl->pkt.stream_index != stream_index)
967 if (pktl->pkt.pts == pktl->pkt.dts &&
968 (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&
969 !pktl->pkt.duration) {
970 pktl->pkt.dts = cur_dts;
971 if (!st->codec->has_b_frames)
972 pktl->pkt.pts = cur_dts;
973 // if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
974 pktl->pkt.duration = duration;
977 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
980 st->cur_dts = cur_dts;
983 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
984 AVCodecParserContext *pc, AVPacket *pkt,
985 int64_t next_dts, int64_t next_pts)
987 int num, den, presentation_delayed, delay, i;
990 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
991 st->codec->codec_id != AV_CODEC_ID_HEVC;
993 if (s->flags & AVFMT_FLAG_NOFILLIN)
996 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
997 if (pkt->dts == pkt->pts && st->last_dts_for_order_check != AV_NOPTS_VALUE) {
998 if (st->last_dts_for_order_check <= pkt->dts) {
1001 av_log(s, st->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1002 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1004 st->last_dts_for_order_check);
1005 st->dts_misordered++;
1007 if (st->dts_ordered + st->dts_misordered > 250) {
1008 st->dts_ordered >>= 1;
1009 st->dts_misordered >>= 1;
1013 st->last_dts_for_order_check = pkt->dts;
1014 if (st->dts_ordered < 8*st->dts_misordered && pkt->dts == pkt->pts)
1015 pkt->dts = AV_NOPTS_VALUE;
1018 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1019 pkt->dts = AV_NOPTS_VALUE;
1021 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1022 && !st->codec->has_b_frames)
1023 //FIXME Set low_delay = 0 when has_b_frames = 1
1024 st->codec->has_b_frames = 1;
1026 /* do we have a video B-frame ? */
1027 delay = st->codec->has_b_frames;
1028 presentation_delayed = 0;
1030 /* XXX: need has_b_frame, but cannot get it if the codec is
1031 * not initialized */
1033 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1034 presentation_delayed = 1;
1036 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1037 st->pts_wrap_bits < 63 &&
1038 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1039 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1040 pkt->dts -= 1LL << st->pts_wrap_bits;
1042 pkt->pts += 1LL << st->pts_wrap_bits;
1045 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1046 * We take the conservative approach and discard both.
1047 * Note: If this is misbehaving for an H.264 file, then possibly
1048 * presentation_delayed is not set correctly. */
1049 if (delay == 1 && pkt->dts == pkt->pts &&
1050 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1051 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1052 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1053 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1054 pkt->dts = AV_NOPTS_VALUE;
1057 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1058 if (pkt->duration == 0) {
1059 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1061 duration = (AVRational) {num, den};
1062 pkt->duration = av_rescale_rnd(1,
1063 num * (int64_t) st->time_base.den,
1064 den * (int64_t) st->time_base.num,
1069 if (pkt->duration != 0 && (s->packet_buffer || s->parse_queue))
1070 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1072 /* Correct timestamps with byte offset if demuxers only have timestamps
1073 * on packet boundaries */
1074 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1075 /* this will estimate bitrate based on this frame's duration and size */
1076 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1077 if (pkt->pts != AV_NOPTS_VALUE)
1079 if (pkt->dts != AV_NOPTS_VALUE)
1083 /* This may be redundant, but it should not hurt. */
1084 if (pkt->dts != AV_NOPTS_VALUE &&
1085 pkt->pts != AV_NOPTS_VALUE &&
1086 pkt->pts > pkt->dts)
1087 presentation_delayed = 1;
1090 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%d delay:%d onein_oneout:%d\n",
1091 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1092 pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1093 /* Interpolate PTS and DTS if they are not present. We skip H264
1094 * currently because delay and has_b_frames are not reliably set. */
1095 if ((delay == 0 || (delay == 1 && pc)) &&
1097 if (presentation_delayed) {
1098 /* DTS = decompression timestamp */
1099 /* PTS = presentation timestamp */
1100 if (pkt->dts == AV_NOPTS_VALUE)
1101 pkt->dts = st->last_IP_pts;
1102 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1103 if (pkt->dts == AV_NOPTS_VALUE)
1104 pkt->dts = st->cur_dts;
1106 /* This is tricky: the dts must be incremented by the duration
1107 * of the frame we are displaying, i.e. the last I- or P-frame. */
1108 if (st->last_IP_duration == 0)
1109 st->last_IP_duration = pkt->duration;
1110 if (pkt->dts != AV_NOPTS_VALUE)
1111 st->cur_dts = pkt->dts + st->last_IP_duration;
1112 if (pkt->dts != AV_NOPTS_VALUE &&
1113 pkt->pts == AV_NOPTS_VALUE &&
1114 st->last_IP_duration > 0 &&
1115 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1116 next_dts != next_pts &&
1117 next_pts != AV_NOPTS_VALUE)
1118 pkt->pts = next_dts;
1120 st->last_IP_duration = pkt->duration;
1121 st->last_IP_pts = pkt->pts;
1122 /* Cannot compute PTS if not present (we can compute it only
1123 * by knowing the future. */
1124 } else if (pkt->pts != AV_NOPTS_VALUE ||
1125 pkt->dts != AV_NOPTS_VALUE ||
1128 /* presentation is not delayed : PTS and DTS are the same */
1129 if (pkt->pts == AV_NOPTS_VALUE)
1130 pkt->pts = pkt->dts;
1131 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1133 if (pkt->pts == AV_NOPTS_VALUE)
1134 pkt->pts = st->cur_dts;
1135 pkt->dts = pkt->pts;
1136 if (pkt->pts != AV_NOPTS_VALUE)
1137 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1141 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
1142 st->pts_buffer[0] = pkt->pts;
1143 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
1144 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
1146 pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1148 // We skipped it above so we try here.
1150 // This should happen on the first packet
1151 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1152 if (pkt->dts > st->cur_dts)
1153 st->cur_dts = pkt->dts;
1155 av_dlog(NULL, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
1156 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1159 if (is_intra_only(st->codec))
1160 pkt->flags |= AV_PKT_FLAG_KEY;
1162 pkt->convergence_duration = pc->convergence_duration;
1165 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1168 AVPacketList *pktl = *pkt_buf;
1169 *pkt_buf = pktl->next;
1170 av_free_packet(&pktl->pkt);
1173 *pkt_buf_end = NULL;
1177 * Parse a packet, add all split parts to parse_queue.
1179 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1181 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1183 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1184 AVStream *st = s->streams[stream_index];
1185 uint8_t *data = pkt ? pkt->data : NULL;
1186 int size = pkt ? pkt->size : 0;
1187 int ret = 0, got_output = 0;
1190 av_init_packet(&flush_pkt);
1193 } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1194 // preserve 0-size sync packets
1195 compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1198 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1200 int64_t next_pts = pkt->pts;
1201 int64_t next_dts = pkt->dts;
1203 av_init_packet(&out_pkt);
1204 len = av_parser_parse2(st->parser, st->codec,
1205 &out_pkt.data, &out_pkt.size, data, size,
1206 pkt->pts, pkt->dts, pkt->pos);
1208 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1210 /* increment read pointer */
1214 got_output = !!out_pkt.size;
1219 if (pkt->side_data) {
1220 out_pkt.side_data = pkt->side_data;
1221 out_pkt.side_data_elems = pkt->side_data_elems;
1222 pkt->side_data = NULL;
1223 pkt->side_data_elems = 0;
1226 /* set the duration */
1227 out_pkt.duration = 0;
1228 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1229 if (st->codec->sample_rate > 0) {
1231 av_rescale_q_rnd(st->parser->duration,
1232 (AVRational) { 1, st->codec->sample_rate },
1238 out_pkt.stream_index = st->index;
1239 out_pkt.pts = st->parser->pts;
1240 out_pkt.dts = st->parser->dts;
1241 out_pkt.pos = st->parser->pos;
1243 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1244 out_pkt.pos = st->parser->frame_offset;
1246 if (st->parser->key_frame == 1 ||
1247 (st->parser->key_frame == -1 &&
1248 st->parser->pict_type == AV_PICTURE_TYPE_I))
1249 out_pkt.flags |= AV_PKT_FLAG_KEY;
1251 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1252 out_pkt.flags |= AV_PKT_FLAG_KEY;
1254 compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);
1256 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1257 out_pkt.buf = pkt->buf;
1259 #if FF_API_DESTRUCT_PACKET
1260 FF_DISABLE_DEPRECATION_WARNINGS
1261 out_pkt.destruct = pkt->destruct;
1262 pkt->destruct = NULL;
1263 FF_ENABLE_DEPRECATION_WARNINGS
1266 if ((ret = av_dup_packet(&out_pkt)) < 0)
1269 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1270 av_free_packet(&out_pkt);
1271 ret = AVERROR(ENOMEM);
1276 /* end of the stream => close and free the parser */
1277 if (pkt == &flush_pkt) {
1278 av_parser_close(st->parser);
1283 av_free_packet(pkt);
1287 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1288 AVPacketList **pkt_buffer_end,
1292 av_assert0(*pkt_buffer);
1295 *pkt_buffer = pktl->next;
1297 *pkt_buffer_end = NULL;
1302 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1304 return av_rescale(ts, st->time_base.num * st->codec->sample_rate, st->time_base.den);
1307 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1309 int ret = 0, i, got_packet = 0;
1310 AVDictionary *metadata = NULL;
1312 av_init_packet(pkt);
1314 while (!got_packet && !s->parse_queue) {
1318 /* read next packet */
1319 ret = ff_read_packet(s, &cur_pkt);
1321 if (ret == AVERROR(EAGAIN))
1323 /* flush the parsers */
1324 for (i = 0; i < s->nb_streams; i++) {
1326 if (st->parser && st->need_parsing)
1327 parse_packet(s, NULL, st->index);
1329 /* all remaining packets are now in parse_queue =>
1330 * really terminate parsing */
1334 st = s->streams[cur_pkt.stream_index];
1336 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1337 cur_pkt.dts != AV_NOPTS_VALUE &&
1338 cur_pkt.pts < cur_pkt.dts) {
1339 av_log(s, AV_LOG_WARNING,
1340 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1341 cur_pkt.stream_index,
1342 av_ts2str(cur_pkt.pts),
1343 av_ts2str(cur_pkt.dts),
1346 if (s->debug & FF_FDEBUG_TS)
1347 av_log(s, AV_LOG_DEBUG,
1348 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
1349 cur_pkt.stream_index,
1350 av_ts2str(cur_pkt.pts),
1351 av_ts2str(cur_pkt.dts),
1352 cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1354 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1355 st->parser = av_parser_init(st->codec->codec_id);
1357 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1358 "%s, packets or times may be invalid.\n",
1359 avcodec_get_name(st->codec->codec_id));
1360 /* no parser available: just output the raw packets */
1361 st->need_parsing = AVSTREAM_PARSE_NONE;
1362 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1363 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1364 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1365 st->parser->flags |= PARSER_FLAG_ONCE;
1366 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1367 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1370 if (!st->need_parsing || !st->parser) {
1371 /* no parsing needed: we just output the packet as is */
1373 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1374 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1375 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1376 ff_reduce_index(s, st->index);
1377 av_add_index_entry(st, pkt->pos, pkt->dts,
1378 0, 0, AVINDEX_KEYFRAME);
1381 } else if (st->discard < AVDISCARD_ALL) {
1382 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1386 av_free_packet(&cur_pkt);
1388 if (pkt->flags & AV_PKT_FLAG_KEY)
1389 st->skip_to_keyframe = 0;
1390 if (st->skip_to_keyframe) {
1391 av_free_packet(&cur_pkt);
1399 if (!got_packet && s->parse_queue)
1400 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1403 AVStream *st = s->streams[pkt->stream_index];
1404 int discard_padding = 0;
1405 if (st->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1406 int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1407 int64_t sample = ts_to_samples(st, pts);
1408 int duration = ts_to_samples(st, pkt->duration);
1409 int64_t end_sample = sample + duration;
1410 if (duration > 0 && end_sample >= st->first_discard_sample &&
1411 sample < st->last_discard_sample)
1412 discard_padding = FFMIN(end_sample - st->first_discard_sample, duration);
1414 if (st->skip_samples || discard_padding) {
1415 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1417 AV_WL32(p, st->skip_samples);
1418 AV_WL32(p + 4, discard_padding);
1419 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d\n", st->skip_samples);
1421 st->skip_samples = 0;
1424 if (st->inject_global_side_data) {
1425 for (i = 0; i < st->nb_side_data; i++) {
1426 AVPacketSideData *src_sd = &st->side_data[i];
1429 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1432 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1434 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1438 memcpy(dst_data, src_sd->data, src_sd->size);
1440 st->inject_global_side_data = 0;
1443 if (!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
1444 av_packet_merge_side_data(pkt);
1447 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1449 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1450 av_dict_copy(&s->metadata, metadata, 0);
1451 av_dict_free(&metadata);
1452 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1455 if (s->debug & FF_FDEBUG_TS)
1456 av_log(s, AV_LOG_DEBUG,
1457 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1458 "size=%d, duration=%d, flags=%d\n",
1460 av_ts2str(pkt->pts),
1461 av_ts2str(pkt->dts),
1462 pkt->size, pkt->duration, pkt->flags);
1467 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1469 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1475 ret = s->packet_buffer
1476 ? read_from_packet_buffer(&s->packet_buffer,
1477 &s->packet_buffer_end, pkt)
1478 : read_frame_internal(s, pkt);
1485 AVPacketList *pktl = s->packet_buffer;
1488 AVPacket *next_pkt = &pktl->pkt;
1490 if (next_pkt->dts != AV_NOPTS_VALUE) {
1491 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1492 // last dts seen for this stream. if any of packets following
1493 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1494 int64_t last_dts = next_pkt->dts;
1495 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1496 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1497 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {
1498 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
1500 next_pkt->pts = pktl->pkt.dts;
1502 if (last_dts != AV_NOPTS_VALUE) {
1503 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1504 last_dts = pktl->pkt.dts;
1509 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1510 // Fixing the last reference frame had none pts issue (For MXF etc).
1511 // We only do this when
1513 // 2. we are not able to resolve a pts value for current packet.
1514 // 3. the packets for this stream at the end of the files had valid dts.
1515 next_pkt->pts = last_dts + next_pkt->duration;
1517 pktl = s->packet_buffer;
1520 /* read packet from packet buffer, if there is data */
1521 st = s->streams[next_pkt->stream_index];
1522 if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1523 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1524 ret = read_from_packet_buffer(&s->packet_buffer,
1525 &s->packet_buffer_end, pkt);
1530 ret = read_frame_internal(s, pkt);
1532 if (pktl && ret != AVERROR(EAGAIN)) {
1539 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1540 &s->packet_buffer_end)) < 0)
1541 return AVERROR(ENOMEM);
1546 st = s->streams[pkt->stream_index];
1547 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1548 ff_reduce_index(s, st->index);
1549 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1552 if (is_relative(pkt->dts))
1553 pkt->dts -= RELATIVE_TS_BASE;
1554 if (is_relative(pkt->pts))
1555 pkt->pts -= RELATIVE_TS_BASE;
1560 /* XXX: suppress the packet queue */
1561 static void flush_packet_queue(AVFormatContext *s)
1563 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1564 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1565 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1567 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1570 /*******************************************************/
1573 int av_find_default_stream_index(AVFormatContext *s)
1577 int best_stream = 0;
1578 int best_score = -1;
1580 if (s->nb_streams <= 0)
1582 for (i = 0; i < s->nb_streams; i++) {
1585 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1586 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1587 if (!st->codec->width && !st->codec->height && !st->codec_info_nb_frames)
1592 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1593 if (!st->codec->sample_rate && !st->codec_info_nb_frames)
1599 if (score > best_score) {
1607 /** Flush the frame reader. */
1608 void ff_read_frame_flush(AVFormatContext *s)
1613 flush_packet_queue(s);
1615 /* Reset read state for each stream. */
1616 for (i = 0; i < s->nb_streams; i++) {
1620 av_parser_close(st->parser);
1623 st->last_IP_pts = AV_NOPTS_VALUE;
1624 st->last_dts_for_order_check = AV_NOPTS_VALUE;
1625 if (st->first_dts == AV_NOPTS_VALUE)
1626 st->cur_dts = RELATIVE_TS_BASE;
1628 /* We set the current DTS to an unspecified origin. */
1629 st->cur_dts = AV_NOPTS_VALUE;
1631 st->probe_packets = MAX_PROBE_PACKETS;
1633 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1634 st->pts_buffer[j] = AV_NOPTS_VALUE;
1636 if (s->internal->inject_global_side_data)
1637 st->inject_global_side_data = 1;
1641 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1645 for (i = 0; i < s->nb_streams; i++) {
1646 AVStream *st = s->streams[i];
1649 av_rescale(timestamp,
1650 st->time_base.den * (int64_t) ref_st->time_base.num,
1651 st->time_base.num * (int64_t) ref_st->time_base.den);
1655 void ff_reduce_index(AVFormatContext *s, int stream_index)
1657 AVStream *st = s->streams[stream_index];
1658 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1660 if ((unsigned) st->nb_index_entries >= max_entries) {
1662 for (i = 0; 2 * i < st->nb_index_entries; i++)
1663 st->index_entries[i] = st->index_entries[2 * i];
1664 st->nb_index_entries = i;
1668 int ff_add_index_entry(AVIndexEntry **index_entries,
1669 int *nb_index_entries,
1670 unsigned int *index_entries_allocated_size,
1671 int64_t pos, int64_t timestamp,
1672 int size, int distance, int flags)
1674 AVIndexEntry *entries, *ie;
1677 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1680 if (timestamp == AV_NOPTS_VALUE)
1681 return AVERROR(EINVAL);
1683 if (size < 0 || size > 0x3FFFFFFF)
1684 return AVERROR(EINVAL);
1686 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1687 timestamp -= RELATIVE_TS_BASE;
1689 entries = av_fast_realloc(*index_entries,
1690 index_entries_allocated_size,
1691 (*nb_index_entries + 1) *
1692 sizeof(AVIndexEntry));
1696 *index_entries = entries;
1698 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1699 timestamp, AVSEEK_FLAG_ANY);
1702 index = (*nb_index_entries)++;
1703 ie = &entries[index];
1704 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1706 ie = &entries[index];
1707 if (ie->timestamp != timestamp) {
1708 if (ie->timestamp <= timestamp)
1710 memmove(entries + index + 1, entries + index,
1711 sizeof(AVIndexEntry) * (*nb_index_entries - index));
1712 (*nb_index_entries)++;
1713 } else if (ie->pos == pos && distance < ie->min_distance)
1714 // do not reduce the distance
1715 distance = ie->min_distance;
1719 ie->timestamp = timestamp;
1720 ie->min_distance = distance;
1727 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1728 int size, int distance, int flags)
1730 timestamp = wrap_timestamp(st, timestamp);
1731 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1732 &st->index_entries_allocated_size, pos,
1733 timestamp, size, distance, flags);
1736 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1737 int64_t wanted_timestamp, int flags)
1745 // Optimize appending index entries at the end.
1746 if (b && entries[b - 1].timestamp < wanted_timestamp)
1751 timestamp = entries[m].timestamp;
1752 if (timestamp >= wanted_timestamp)
1754 if (timestamp <= wanted_timestamp)
1757 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1759 if (!(flags & AVSEEK_FLAG_ANY))
1760 while (m >= 0 && m < nb_entries &&
1761 !(entries[m].flags & AVINDEX_KEYFRAME))
1762 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1764 if (m == nb_entries)
1769 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1771 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1772 wanted_timestamp, flags);
1775 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
1776 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1778 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
1779 if (stream_index >= 0)
1780 ts = wrap_timestamp(s->streams[stream_index], ts);
1784 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1785 int64_t target_ts, int flags)
1787 AVInputFormat *avif = s->iformat;
1788 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1789 int64_t ts_min, ts_max, ts;
1794 if (stream_index < 0)
1797 av_dlog(s, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1800 ts_min = AV_NOPTS_VALUE;
1801 pos_limit = -1; // GCC falsely says it may be uninitialized.
1803 st = s->streams[stream_index];
1804 if (st->index_entries) {
1807 /* FIXME: Whole function must be checked for non-keyframe entries in
1808 * index case, especially read_timestamp(). */
1809 index = av_index_search_timestamp(st, target_ts,
1810 flags | AVSEEK_FLAG_BACKWARD);
1811 index = FFMAX(index, 0);
1812 e = &st->index_entries[index];
1814 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1816 ts_min = e->timestamp;
1817 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
1818 pos_min, av_ts2str(ts_min));
1820 av_assert1(index == 0);
1823 index = av_index_search_timestamp(st, target_ts,
1824 flags & ~AVSEEK_FLAG_BACKWARD);
1825 av_assert0(index < st->nb_index_entries);
1827 e = &st->index_entries[index];
1828 av_assert1(e->timestamp >= target_ts);
1830 ts_max = e->timestamp;
1831 pos_limit = pos_max - e->min_distance;
1832 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1833 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
1837 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1838 ts_min, ts_max, flags, &ts, avif->read_timestamp);
1843 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1846 ff_read_frame_flush(s);
1847 ff_update_cur_dts(s, st, ts);
1852 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
1853 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1855 int64_t step = 1024;
1856 int64_t limit, ts_max;
1857 int64_t filesize = avio_size(s->pb);
1858 int64_t pos_max = filesize - 1;
1861 pos_max = FFMAX(0, (pos_max) - step);
1862 ts_max = ff_read_timestamp(s, stream_index,
1863 &pos_max, limit, read_timestamp);
1865 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
1866 if (ts_max == AV_NOPTS_VALUE)
1870 int64_t tmp_pos = pos_max + 1;
1871 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
1872 &tmp_pos, INT64_MAX, read_timestamp);
1873 if (tmp_ts == AV_NOPTS_VALUE)
1875 av_assert0(tmp_pos > pos_max);
1878 if (tmp_pos >= filesize)
1890 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1891 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1892 int64_t ts_min, int64_t ts_max,
1893 int flags, int64_t *ts_ret,
1894 int64_t (*read_timestamp)(struct AVFormatContext *, int,
1895 int64_t *, int64_t))
1902 av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1904 if (ts_min == AV_NOPTS_VALUE) {
1905 pos_min = s->data_offset;
1906 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1907 if (ts_min == AV_NOPTS_VALUE)
1911 if (ts_min >= target_ts) {
1916 if (ts_max == AV_NOPTS_VALUE) {
1917 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
1919 pos_limit = pos_max;
1922 if (ts_max <= target_ts) {
1927 av_assert0(ts_min < ts_max);
1930 while (pos_min < pos_limit) {
1932 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
1933 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
1934 av_assert0(pos_limit <= pos_max);
1936 if (no_change == 0) {
1937 int64_t approximate_keyframe_distance = pos_max - pos_limit;
1938 // interpolate position (better than dichotomy)
1939 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
1941 pos_min - approximate_keyframe_distance;
1942 } else if (no_change == 1) {
1943 // bisection if interpolation did not change min / max pos last time
1944 pos = (pos_min + pos_limit) >> 1;
1946 /* linear search if bisection failed, can only happen if there
1947 * are very few or no keyframes between min/max */
1952 else if (pos > pos_limit)
1956 // May pass pos_limit instead of -1.
1957 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
1962 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
1963 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
1964 pos_min, pos, pos_max,
1965 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
1966 pos_limit, start_pos, no_change);
1967 if (ts == AV_NOPTS_VALUE) {
1968 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1971 if (target_ts <= ts) {
1972 pos_limit = start_pos - 1;
1976 if (target_ts >= ts) {
1982 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1983 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1986 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1988 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1989 av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",
1990 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
1996 static int seek_frame_byte(AVFormatContext *s, int stream_index,
1997 int64_t pos, int flags)
1999 int64_t pos_min, pos_max;
2001 pos_min = s->data_offset;
2002 pos_max = avio_size(s->pb) - 1;
2006 else if (pos > pos_max)
2009 avio_seek(s->pb, pos, SEEK_SET);
2011 s->io_repositioned = 1;
2016 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2017 int64_t timestamp, int flags)
2024 st = s->streams[stream_index];
2026 index = av_index_search_timestamp(st, timestamp, flags);
2028 if (index < 0 && st->nb_index_entries &&
2029 timestamp < st->index_entries[0].timestamp)
2032 if (index < 0 || index == st->nb_index_entries - 1) {
2036 if (st->nb_index_entries) {
2037 av_assert0(st->index_entries);
2038 ie = &st->index_entries[st->nb_index_entries - 1];
2039 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2041 ff_update_cur_dts(s, st, ie->timestamp);
2043 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
2049 read_status = av_read_frame(s, &pkt);
2050 } while (read_status == AVERROR(EAGAIN));
2051 if (read_status < 0)
2053 av_free_packet(&pkt);
2054 if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2055 if (pkt.flags & AV_PKT_FLAG_KEY)
2057 if (nonkey++ > 1000 && st->codec->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2058 av_log(s, AV_LOG_ERROR,"seek_frame_generic failed as this stream seems to contain no keyframes after the target timestamp, %d non keyframes found\n", nonkey);
2063 index = av_index_search_timestamp(st, timestamp, flags);
2068 ff_read_frame_flush(s);
2069 if (s->iformat->read_seek)
2070 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2072 ie = &st->index_entries[index];
2073 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2075 ff_update_cur_dts(s, st, ie->timestamp);
2080 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2081 int64_t timestamp, int flags)
2086 if (flags & AVSEEK_FLAG_BYTE) {
2087 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2089 ff_read_frame_flush(s);
2090 return seek_frame_byte(s, stream_index, timestamp, flags);
2093 if (stream_index < 0) {
2094 stream_index = av_find_default_stream_index(s);
2095 if (stream_index < 0)
2098 st = s->streams[stream_index];
2099 /* timestamp for default must be expressed in AV_TIME_BASE units */
2100 timestamp = av_rescale(timestamp, st->time_base.den,
2101 AV_TIME_BASE * (int64_t) st->time_base.num);
2104 /* first, we try the format specific seek */
2105 if (s->iformat->read_seek) {
2106 ff_read_frame_flush(s);
2107 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2113 if (s->iformat->read_timestamp &&
2114 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2115 ff_read_frame_flush(s);
2116 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2117 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2118 ff_read_frame_flush(s);
2119 return seek_frame_generic(s, stream_index, timestamp, flags);
2124 int av_seek_frame(AVFormatContext *s, int stream_index,
2125 int64_t timestamp, int flags)
2129 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2130 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2131 if ((flags & AVSEEK_FLAG_BACKWARD))
2135 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2136 flags & ~AVSEEK_FLAG_BACKWARD);
2139 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2142 ret = avformat_queue_attached_pictures(s);
2147 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2148 int64_t ts, int64_t max_ts, int flags)
2150 if (min_ts > ts || max_ts < ts)
2152 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2153 return AVERROR(EINVAL);
2156 flags |= AVSEEK_FLAG_ANY;
2157 flags &= ~AVSEEK_FLAG_BACKWARD;
2159 if (s->iformat->read_seek2) {
2161 ff_read_frame_flush(s);
2163 if (stream_index == -1 && s->nb_streams == 1) {
2164 AVRational time_base = s->streams[0]->time_base;
2165 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2166 min_ts = av_rescale_rnd(min_ts, time_base.den,
2167 time_base.num * (int64_t)AV_TIME_BASE,
2168 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2169 max_ts = av_rescale_rnd(max_ts, time_base.den,
2170 time_base.num * (int64_t)AV_TIME_BASE,
2171 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2174 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2178 ret = avformat_queue_attached_pictures(s);
2182 if (s->iformat->read_timestamp) {
2183 // try to seek via read_timestamp()
2186 // Fall back on old API if new is not implemented but old is.
2187 // Note the old API has somewhat different semantics.
2188 if (s->iformat->read_seek || 1) {
2189 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2190 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2191 if (ret<0 && ts != min_ts && max_ts != ts) {
2192 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2194 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2199 // try some generic seek like seek_frame_generic() but with new ts semantics
2200 return -1; //unreachable
2203 /*******************************************************/
2206 * Return TRUE if the stream has accurate duration in any stream.
2208 * @return TRUE if the stream has accurate duration for at least one component.
2210 static int has_duration(AVFormatContext *ic)
2215 for (i = 0; i < ic->nb_streams; i++) {
2216 st = ic->streams[i];
2217 if (st->duration != AV_NOPTS_VALUE)
2220 if (ic->duration != AV_NOPTS_VALUE)
2226 * Estimate the stream timings from the one of each components.
2228 * Also computes the global bitrate if possible.
2230 static void update_stream_timings(AVFormatContext *ic)
2232 int64_t start_time, start_time1, start_time_text, end_time, end_time1;
2233 int64_t duration, duration1, filesize;
2238 start_time = INT64_MAX;
2239 start_time_text = INT64_MAX;
2240 end_time = INT64_MIN;
2241 duration = INT64_MIN;
2242 for (i = 0; i < ic->nb_streams; i++) {
2243 st = ic->streams[i];
2244 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2245 start_time1 = av_rescale_q(st->start_time, st->time_base,
2247 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA) {
2248 if (start_time1 < start_time_text)
2249 start_time_text = start_time1;
2251 start_time = FFMIN(start_time, start_time1);
2252 end_time1 = AV_NOPTS_VALUE;
2253 if (st->duration != AV_NOPTS_VALUE) {
2254 end_time1 = start_time1 +
2255 av_rescale_q(st->duration, st->time_base,
2257 end_time = FFMAX(end_time, end_time1);
2259 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2260 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2261 p->start_time = start_time1;
2262 if (p->end_time < end_time1)
2263 p->end_time = end_time1;
2266 if (st->duration != AV_NOPTS_VALUE) {
2267 duration1 = av_rescale_q(st->duration, st->time_base,
2269 duration = FFMAX(duration, duration1);
2272 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
2273 start_time = start_time_text;
2274 else if (start_time > start_time_text)
2275 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2277 if (start_time != INT64_MAX) {
2278 ic->start_time = start_time;
2279 if (end_time != INT64_MIN) {
2280 if (ic->nb_programs) {
2281 for (i = 0; i < ic->nb_programs; i++) {
2282 p = ic->programs[i];
2283 if (p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time)
2284 duration = FFMAX(duration, p->end_time - p->start_time);
2287 duration = FFMAX(duration, end_time - start_time);
2290 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2291 ic->duration = duration;
2293 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
2294 /* compute the bitrate */
2295 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2296 (double) ic->duration;
2297 if (bitrate >= 0 && bitrate <= INT_MAX)
2298 ic->bit_rate = bitrate;
2302 static void fill_all_stream_timings(AVFormatContext *ic)
2307 update_stream_timings(ic);
2308 for (i = 0; i < ic->nb_streams; i++) {
2309 st = ic->streams[i];
2310 if (st->start_time == AV_NOPTS_VALUE) {
2311 if (ic->start_time != AV_NOPTS_VALUE)
2312 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2314 if (ic->duration != AV_NOPTS_VALUE)
2315 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2321 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2323 int64_t filesize, duration;
2324 int i, show_warning = 0;
2327 /* if bit_rate is already set, we believe it */
2328 if (ic->bit_rate <= 0) {
2330 for (i = 0; i < ic->nb_streams; i++) {
2331 st = ic->streams[i];
2332 if (st->codec->bit_rate > 0) {
2333 if (INT_MAX - st->codec->bit_rate < bit_rate) {
2337 bit_rate += st->codec->bit_rate;
2338 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2339 // If we have a videostream with packets but without a bitrate
2340 // then consider the sum not known
2345 ic->bit_rate = bit_rate;
2348 /* if duration is already set, we believe it */
2349 if (ic->duration == AV_NOPTS_VALUE &&
2350 ic->bit_rate != 0) {
2351 filesize = ic->pb ? avio_size(ic->pb) : 0;
2352 if (filesize > ic->data_offset) {
2353 filesize -= ic->data_offset;
2354 for (i = 0; i < ic->nb_streams; i++) {
2355 st = ic->streams[i];
2356 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2357 && st->duration == AV_NOPTS_VALUE) {
2358 duration = av_rescale(8 * filesize, st->time_base.den,
2360 (int64_t) st->time_base.num);
2361 st->duration = duration;
2368 av_log(ic, AV_LOG_WARNING,
2369 "Estimating duration from bitrate, this may be inaccurate\n");
2372 #define DURATION_MAX_READ_SIZE 250000LL
2373 #define DURATION_MAX_RETRY 4
2375 /* only usable for MPEG-PS streams */
2376 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2378 AVPacket pkt1, *pkt = &pkt1;
2380 int num, den, read_size, i, ret;
2381 int found_duration = 0;
2383 int64_t filesize, offset, duration;
2386 /* flush packet queue */
2387 flush_packet_queue(ic);
2389 for (i = 0; i < ic->nb_streams; i++) {
2390 st = ic->streams[i];
2391 if (st->start_time == AV_NOPTS_VALUE &&
2392 st->first_dts == AV_NOPTS_VALUE &&
2393 st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN)
2394 av_log(st->codec, AV_LOG_WARNING,
2395 "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2398 av_parser_close(st->parser);
2403 av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2404 /* estimate the end time (duration) */
2405 /* XXX: may need to support wrapping */
2406 filesize = ic->pb ? avio_size(ic->pb) : 0;
2408 is_end = found_duration;
2409 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2413 avio_seek(ic->pb, offset, SEEK_SET);
2416 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2420 ret = ff_read_packet(ic, pkt);
2421 } while (ret == AVERROR(EAGAIN));
2424 read_size += pkt->size;
2425 st = ic->streams[pkt->stream_index];
2426 if (pkt->pts != AV_NOPTS_VALUE &&
2427 (st->start_time != AV_NOPTS_VALUE ||
2428 st->first_dts != AV_NOPTS_VALUE)) {
2429 if (pkt->duration == 0) {
2430 ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2432 pkt->duration = av_rescale_rnd(1,
2433 num * (int64_t) st->time_base.den,
2434 den * (int64_t) st->time_base.num,
2438 duration = pkt->pts + pkt->duration;
2440 if (st->start_time != AV_NOPTS_VALUE)
2441 duration -= st->start_time;
2443 duration -= st->first_dts;
2445 if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2446 (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2447 st->duration = duration;
2448 st->info->last_duration = duration;
2451 av_free_packet(pkt);
2454 /* check if all audio/video streams have valid duration */
2457 for (i = 0; i < ic->nb_streams; i++) {
2458 st = ic->streams[i];
2459 switch (st->codec->codec_type) {
2460 case AVMEDIA_TYPE_VIDEO:
2461 case AVMEDIA_TYPE_AUDIO:
2462 if (st->duration == AV_NOPTS_VALUE)
2469 ++retry <= DURATION_MAX_RETRY);
2471 av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2473 /* warn about audio/video streams which duration could not be estimated */
2474 for (i = 0; i < ic->nb_streams; i++) {
2475 st = ic->streams[i];
2476 if (st->duration == AV_NOPTS_VALUE) {
2477 switch (st->codec->codec_type) {
2478 case AVMEDIA_TYPE_VIDEO:
2479 case AVMEDIA_TYPE_AUDIO:
2480 if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2481 av_log(ic, AV_LOG_DEBUG, "stream %d : no PTS found at end of file, duration not set\n", i);
2483 av_log(ic, AV_LOG_DEBUG, "stream %d : no TS found at start of file, duration not set\n", i);
2487 fill_all_stream_timings(ic);
2489 avio_seek(ic->pb, old_offset, SEEK_SET);
2490 for (i = 0; i < ic->nb_streams; i++) {
2493 st = ic->streams[i];
2494 st->cur_dts = st->first_dts;
2495 st->last_IP_pts = AV_NOPTS_VALUE;
2496 st->last_dts_for_order_check = AV_NOPTS_VALUE;
2497 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2498 st->pts_buffer[j] = AV_NOPTS_VALUE;
2502 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2506 /* get the file size, if possible */
2507 if (ic->iformat->flags & AVFMT_NOFILE) {
2510 file_size = avio_size(ic->pb);
2511 file_size = FFMAX(0, file_size);
2514 if ((!strcmp(ic->iformat->name, "mpeg") ||
2515 !strcmp(ic->iformat->name, "mpegts")) &&
2516 file_size && ic->pb->seekable) {
2517 /* get accurate estimate from the PTSes */
2518 estimate_timings_from_pts(ic, old_offset);
2519 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2520 } else if (has_duration(ic)) {
2521 /* at least one component has timings - we use them for all
2523 fill_all_stream_timings(ic);
2524 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2526 /* less precise: use bitrate info */
2527 estimate_timings_from_bit_rate(ic);
2528 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2530 update_stream_timings(ic);
2534 AVStream av_unused *st;
2535 for (i = 0; i < ic->nb_streams; i++) {
2536 st = ic->streams[i];
2537 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2538 (double) st->start_time / AV_TIME_BASE,
2539 (double) st->duration / AV_TIME_BASE);
2542 "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2543 (double) ic->start_time / AV_TIME_BASE,
2544 (double) ic->duration / AV_TIME_BASE,
2545 ic->bit_rate / 1000);
2549 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2551 AVCodecContext *avctx = st->codec;
2553 #define FAIL(errmsg) do { \
2555 *errmsg_ptr = errmsg; \
2559 if ( avctx->codec_id == AV_CODEC_ID_NONE
2560 && avctx->codec_type != AVMEDIA_TYPE_DATA)
2561 FAIL("unknown codec");
2562 switch (avctx->codec_type) {
2563 case AVMEDIA_TYPE_AUDIO:
2564 if (!avctx->frame_size && determinable_frame_size(avctx))
2565 FAIL("unspecified frame size");
2566 if (st->info->found_decoder >= 0 &&
2567 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2568 FAIL("unspecified sample format");
2569 if (!avctx->sample_rate)
2570 FAIL("unspecified sample rate");
2571 if (!avctx->channels)
2572 FAIL("unspecified number of channels");
2573 if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2574 FAIL("no decodable DTS frames");
2576 case AVMEDIA_TYPE_VIDEO:
2578 FAIL("unspecified size");
2579 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2580 FAIL("unspecified pixel format");
2581 if (st->codec->codec_id == AV_CODEC_ID_RV30 || st->codec->codec_id == AV_CODEC_ID_RV40)
2582 if (!st->sample_aspect_ratio.num && !st->codec->sample_aspect_ratio.num && !st->codec_info_nb_frames)
2583 FAIL("no frame in rv30/40 and no sar");
2585 case AVMEDIA_TYPE_SUBTITLE:
2586 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2587 FAIL("unspecified size");
2589 case AVMEDIA_TYPE_DATA:
2590 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2596 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2597 static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
2598 AVDictionary **options)
2600 const AVCodec *codec;
2601 int got_picture = 1, ret = 0;
2602 AVFrame *frame = av_frame_alloc();
2603 AVSubtitle subtitle;
2604 AVPacket pkt = *avpkt;
2607 return AVERROR(ENOMEM);
2609 if (!avcodec_is_open(st->codec) &&
2610 st->info->found_decoder <= 0 &&
2611 (st->codec->codec_id != -st->info->found_decoder || !st->codec->codec_id)) {
2612 AVDictionary *thread_opt = NULL;
2614 codec = find_decoder(s, st, st->codec->codec_id);
2617 st->info->found_decoder = -st->codec->codec_id;
2622 /* Force thread count to 1 since the H.264 decoder will not extract
2623 * SPS and PPS to extradata during multi-threaded decoding. */
2624 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2625 if (s->codec_whitelist)
2626 av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
2627 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2629 av_dict_free(&thread_opt);
2631 st->info->found_decoder = -st->codec->codec_id;
2634 st->info->found_decoder = 1;
2635 } else if (!st->info->found_decoder)
2636 st->info->found_decoder = 1;
2638 if (st->info->found_decoder < 0) {
2643 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2645 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
2646 (!st->codec_info_nb_frames &&
2647 st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2649 switch (st->codec->codec_type) {
2650 case AVMEDIA_TYPE_VIDEO:
2651 ret = avcodec_decode_video2(st->codec, frame,
2652 &got_picture, &pkt);
2654 case AVMEDIA_TYPE_AUDIO:
2655 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2657 case AVMEDIA_TYPE_SUBTITLE:
2658 ret = avcodec_decode_subtitle2(st->codec, &subtitle,
2659 &got_picture, &pkt);
2667 st->nb_decoded_frames++;
2674 if (!pkt.data && !got_picture)
2678 av_frame_free(&frame);
2682 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2684 while (tags->id != AV_CODEC_ID_NONE) {
2692 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2695 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2696 if (tag == tags[i].tag)
2698 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2699 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2701 return AV_CODEC_ID_NONE;
2704 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2709 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2711 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2713 return AV_CODEC_ID_NONE;
2718 if (sflags & (1 << (bps - 1))) {
2721 return AV_CODEC_ID_PCM_S8;
2723 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2725 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2727 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2729 return AV_CODEC_ID_NONE;
2734 return AV_CODEC_ID_PCM_U8;
2736 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2738 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2740 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2742 return AV_CODEC_ID_NONE;
2748 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2751 if (!av_codec_get_tag2(tags, id, &tag))
2756 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
2760 for (i = 0; tags && tags[i]; i++) {
2761 const AVCodecTag *codec_tags = tags[i];
2762 while (codec_tags->id != AV_CODEC_ID_NONE) {
2763 if (codec_tags->id == id) {
2764 *tag = codec_tags->tag;
2773 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2776 for (i = 0; tags && tags[i]; i++) {
2777 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2778 if (id != AV_CODEC_ID_NONE)
2781 return AV_CODEC_ID_NONE;
2784 static void compute_chapters_end(AVFormatContext *s)
2787 int64_t max_time = s->duration +
2788 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2790 for (i = 0; i < s->nb_chapters; i++)
2791 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2792 AVChapter *ch = s->chapters[i];
2793 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2797 for (j = 0; j < s->nb_chapters; j++) {
2798 AVChapter *ch1 = s->chapters[j];
2799 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2801 if (j != i && next_start > ch->start && next_start < end)
2804 ch->end = (end == INT64_MAX) ? ch->start : end;
2808 static int get_std_framerate(int i)
2811 return (i + 1) * 1001;
2815 return ((const int[]) { 40, 48, 50, 60, 80, 120, 240})[i] * 1001 * 12;
2819 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
2822 /* Is the time base unreliable?
2823 * This is a heuristic to balance between quick acceptance of the values in
2824 * the headers vs. some extra checks.
2825 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2826 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2827 * And there are "variable" fps files this needs to detect as well. */
2828 static int tb_unreliable(AVCodecContext *c)
2830 if (c->time_base.den >= 101L * c->time_base.num ||
2831 c->time_base.den < 5L * c->time_base.num ||
2832 // c->codec_tag == AV_RL32("DIVX") ||
2833 // c->codec_tag == AV_RL32("XVID") ||
2834 c->codec_tag == AV_RL32("mp4v") ||
2835 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
2836 c->codec_id == AV_CODEC_ID_GIF ||
2837 c->codec_id == AV_CODEC_ID_H264)
2842 int ff_alloc_extradata(AVCodecContext *avctx, int size)
2846 if (size < 0 || size >= INT32_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
2847 avctx->extradata = NULL;
2848 avctx->extradata_size = 0;
2849 return AVERROR(EINVAL);
2851 avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2852 if (avctx->extradata) {
2853 memset(avctx->extradata + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2854 avctx->extradata_size = size;
2857 avctx->extradata_size = 0;
2858 ret = AVERROR(ENOMEM);
2863 int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
2865 int ret = ff_alloc_extradata(avctx, size);
2868 ret = avio_read(pb, avctx->extradata, size);
2870 av_freep(&avctx->extradata);
2871 avctx->extradata_size = 0;
2872 av_log(avctx, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
2873 return ret < 0 ? ret : AVERROR_INVALIDDATA;
2879 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
2882 int64_t last = st->info->last_dts;
2884 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
2885 && ts - (uint64_t)last < INT64_MAX) {
2886 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
2887 int64_t duration = ts - last;
2889 if (!st->info->duration_error)
2890 st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);
2891 if (!st->info->duration_error)
2892 return AVERROR(ENOMEM);
2894 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2895 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2896 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2897 if (st->info->duration_error[0][1][i] < 1e10) {
2898 int framerate = get_std_framerate(i);
2899 double sdts = dts*framerate/(1001*12);
2900 for (j= 0; j<2; j++) {
2901 int64_t ticks = llrint(sdts+j*0.5);
2902 double error= sdts - ticks + j*0.5;
2903 st->info->duration_error[j][0][i] += error;
2904 st->info->duration_error[j][1][i] += error*error;
2908 st->info->duration_count++;
2909 st->info->rfps_duration_sum += duration;
2911 if (st->info->duration_count % 10 == 0) {
2912 int n = st->info->duration_count;
2913 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2914 if (st->info->duration_error[0][1][i] < 1e10) {
2915 double a0 = st->info->duration_error[0][0][i] / n;
2916 double error0 = st->info->duration_error[0][1][i] / n - a0*a0;
2917 double a1 = st->info->duration_error[1][0][i] / n;
2918 double error1 = st->info->duration_error[1][1][i] / n - a1*a1;
2919 if (error0 > 0.04 && error1 > 0.04) {
2920 st->info->duration_error[0][1][i] = 2e10;
2921 st->info->duration_error[1][1][i] = 2e10;
2927 // ignore the first 4 values, they might have some random jitter
2928 if (st->info->duration_count > 3 && is_relative(ts) == is_relative(last))
2929 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2931 if (ts != AV_NOPTS_VALUE)
2932 st->info->last_dts = ts;
2937 void ff_rfps_calculate(AVFormatContext *ic)
2941 for (i = 0; i < ic->nb_streams; i++) {
2942 AVStream *st = ic->streams[i];
2944 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
2946 // the check for tb_unreliable() is not completely correct, since this is not about handling
2947 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2948 // ipmovie.c produces.
2949 if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
2950 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
2951 if (st->info->duration_count>1 && !st->r_frame_rate.num
2952 && tb_unreliable(st->codec)) {
2954 double best_error= 0.01;
2955 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
2957 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
2960 if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
2962 if (!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
2965 if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
2968 for (k= 0; k<2; k++) {
2969 int n = st->info->duration_count;
2970 double a= st->info->duration_error[k][0][j] / n;
2971 double error= st->info->duration_error[k][1][j]/n - a*a;
2973 if (error < best_error && best_error> 0.000000001) {
2975 num = get_std_framerate(j);
2978 av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
2981 // do not increase frame rate by more than 1 % in order to match a standard rate.
2982 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
2983 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2985 if ( !st->avg_frame_rate.num
2986 && st->r_frame_rate.num && st->info->rfps_duration_sum
2987 && st->info->codec_info_duration <= 0
2988 && st->info->duration_count > 2
2989 && fabs(1.0 / (av_q2d(st->r_frame_rate) * av_q2d(st->time_base)) - st->info->rfps_duration_sum / (double)st->info->duration_count) <= 1.0
2991 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
2992 st->avg_frame_rate = st->r_frame_rate;
2995 av_freep(&st->info->duration_error);
2996 st->info->last_dts = AV_NOPTS_VALUE;
2997 st->info->duration_count = 0;
2998 st->info->rfps_duration_sum = 0;
3002 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3004 int i, count, ret = 0, j;
3007 AVPacket pkt1, *pkt;
3008 int64_t old_offset = avio_tell(ic->pb);
3009 // new streams might appear, no options for those
3010 int orig_nb_streams = ic->nb_streams;
3012 int64_t max_analyze_duration = ic->max_analyze_duration2;
3013 int64_t max_stream_analyze_duration;
3014 int64_t probesize = ic->probesize2;
3016 if (!max_analyze_duration)
3017 max_analyze_duration = ic->max_analyze_duration;
3019 probesize = ic->probesize;
3020 flush_codecs = probesize > 0;
3022 av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3024 max_stream_analyze_duration = max_analyze_duration;
3025 if (!max_analyze_duration) {
3026 max_stream_analyze_duration =
3027 max_analyze_duration = 5*AV_TIME_BASE;
3028 if (!strcmp(ic->iformat->name, "flv"))
3029 max_stream_analyze_duration = 30*AV_TIME_BASE;
3033 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d\n",
3034 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count);
3036 for (i = 0; i < ic->nb_streams; i++) {
3037 const AVCodec *codec;
3038 AVDictionary *thread_opt = NULL;
3039 st = ic->streams[i];
3041 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3042 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3043 /* if (!st->time_base.num)
3045 if (!st->codec->time_base.num)
3046 st->codec->time_base = st->time_base;
3048 // only for the split stuff
3049 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
3050 st->parser = av_parser_init(st->codec->codec_id);
3052 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3053 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3054 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3055 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3057 } else if (st->need_parsing) {
3058 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3059 "%s, packets or times may be invalid.\n",
3060 avcodec_get_name(st->codec->codec_id));
3063 codec = find_decoder(ic, st, st->codec->codec_id);
3065 /* Force thread count to 1 since the H.264 decoder will not extract
3066 * SPS and PPS to extradata during multi-threaded decoding. */
3067 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3069 if (ic->codec_whitelist)
3070 av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3072 /* Ensure that subtitle_header is properly set. */
3073 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
3074 && codec && !st->codec->codec) {
3075 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3076 av_log(ic, AV_LOG_WARNING,
3077 "Failed to open codec in av_find_stream_info\n");
3080 // Try to just open decoders, in case this is enough to get parameters.
3081 if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3082 if (codec && !st->codec->codec)
3083 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3084 av_log(ic, AV_LOG_WARNING,
3085 "Failed to open codec in av_find_stream_info\n");
3088 av_dict_free(&thread_opt);
3091 for (i = 0; i < ic->nb_streams; i++) {
3092 #if FF_API_R_FRAME_RATE
3093 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3095 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
3096 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
3102 int analyzed_all_streams;
3103 if (ff_check_interrupt(&ic->interrupt_callback)) {
3105 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3109 /* check if one codec still needs to be handled */
3110 for (i = 0; i < ic->nb_streams; i++) {
3111 int fps_analyze_framecount = 20;
3113 st = ic->streams[i];
3114 if (!has_codec_parameters(st, NULL))
3116 /* If the timebase is coarse (like the usual millisecond precision
3117 * of mkv), we need to analyze more frames to reliably arrive at
3118 * the correct fps. */
3119 if (av_q2d(st->time_base) > 0.0005)
3120 fps_analyze_framecount *= 2;
3121 if (!tb_unreliable(st->codec))
3122 fps_analyze_framecount = 0;
3123 if (ic->fps_probe_size >= 0)
3124 fps_analyze_framecount = ic->fps_probe_size;
3125 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3126 fps_analyze_framecount = 0;
3127 /* variable fps and no guess at the real fps */
3128 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3129 st->info->duration_count < fps_analyze_framecount &&
3130 st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3132 if (st->parser && st->parser->parser->split &&
3133 !st->codec->extradata)
3135 if (st->first_dts == AV_NOPTS_VALUE &&
3136 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3137 st->codec_info_nb_frames < ic->max_ts_probe &&
3138 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3139 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
3142 analyzed_all_streams = 0;
3143 if (i == ic->nb_streams) {
3144 analyzed_all_streams = 1;
3145 /* NOTE: If the format has no header, then we need to read some
3146 * packets to get most of the streams, so we cannot stop here. */
3147 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3148 /* If we found the info for all the codecs, we can stop. */
3150 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3155 /* We did not get all the codec info, but we read too much data. */
3156 if (read_size >= probesize) {
3158 av_log(ic, AV_LOG_DEBUG,
3159 "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3160 for (i = 0; i < ic->nb_streams; i++)
3161 if (!ic->streams[i]->r_frame_rate.num &&
3162 ic->streams[i]->info->duration_count <= 1 &&
3163 ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3164 strcmp(ic->iformat->name, "image2"))
3165 av_log(ic, AV_LOG_WARNING,
3166 "Stream #%d: not enough frames to estimate rate; "
3167 "consider increasing probesize\n", i);
3171 /* NOTE: A new stream can be added there if no header in file
3172 * (AVFMTCTX_NOHEADER). */
3173 ret = read_frame_internal(ic, &pkt1);
3174 if (ret == AVERROR(EAGAIN))
3182 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3183 free_packet_buffer(&ic->packet_buffer, &ic->packet_buffer_end);
3185 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
3186 &ic->packet_buffer_end);
3188 ret = AVERROR(ENOMEM);
3189 goto find_stream_info_err;
3191 if ((ret = av_dup_packet(pkt)) < 0)
3192 goto find_stream_info_err;
3195 st = ic->streams[pkt->stream_index];
3196 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3197 read_size += pkt->size;
3199 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3200 /* check for non-increasing dts */
3201 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3202 st->info->fps_last_dts >= pkt->dts) {
3203 av_log(ic, AV_LOG_DEBUG,
3204 "Non-increasing DTS in stream %d: packet %d with DTS "
3205 "%"PRId64", packet %d with DTS %"PRId64"\n",
3206 st->index, st->info->fps_last_dts_idx,
3207 st->info->fps_last_dts, st->codec_info_nb_frames,
3209 st->info->fps_first_dts =
3210 st->info->fps_last_dts = AV_NOPTS_VALUE;
3212 /* Check for a discontinuity in dts. If the difference in dts
3213 * is more than 1000 times the average packet duration in the
3214 * sequence, we treat it as a discontinuity. */
3215 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3216 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
3217 (pkt->dts - st->info->fps_last_dts) / 1000 >
3218 (st->info->fps_last_dts - st->info->fps_first_dts) /
3219 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
3220 av_log(ic, AV_LOG_WARNING,
3221 "DTS discontinuity in stream %d: packet %d with DTS "
3222 "%"PRId64", packet %d with DTS %"PRId64"\n",
3223 st->index, st->info->fps_last_dts_idx,
3224 st->info->fps_last_dts, st->codec_info_nb_frames,
3226 st->info->fps_first_dts =
3227 st->info->fps_last_dts = AV_NOPTS_VALUE;
3230 /* update stored dts values */
3231 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
3232 st->info->fps_first_dts = pkt->dts;
3233 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
3235 st->info->fps_last_dts = pkt->dts;
3236 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
3238 if (st->codec_info_nb_frames>1) {
3241 if (st->time_base.den > 0)
3242 t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3243 if (st->avg_frame_rate.num > 0)
3244 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3247 && st->codec_info_nb_frames>30
3248 && st->info->fps_first_dts != AV_NOPTS_VALUE
3249 && st->info->fps_last_dts != AV_NOPTS_VALUE)
3250 t = FFMAX(t, av_rescale_q(st->info->fps_last_dts - st->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));
3252 if (t >= (analyzed_all_streams ? max_analyze_duration : max_stream_analyze_duration)) {
3253 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds\n",
3254 max_analyze_duration,
3256 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3257 av_packet_unref(pkt);
3260 if (pkt->duration) {
3261 st->info->codec_info_duration += pkt->duration;
3262 st->info->codec_info_duration_fields += st->parser && st->need_parsing && st->codec->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3265 #if FF_API_R_FRAME_RATE
3266 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3267 ff_rfps_add_frame(ic, st, pkt->dts);
3269 if (st->parser && st->parser->parser->split && !st->codec->extradata) {
3270 int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
3271 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
3272 if (ff_alloc_extradata(st->codec, i))
3273 return AVERROR(ENOMEM);
3274 memcpy(st->codec->extradata, pkt->data,
3275 st->codec->extradata_size);
3279 /* If still no information, we try to open the codec and to
3280 * decompress the frame. We try to avoid that in most cases as
3281 * it takes longer and uses more memory. For MPEG-4, we need to
3282 * decompress for QuickTime.
3284 * If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3285 * least one frame of codec data, this makes sure the codec initializes
3286 * the channel configuration and does not only trust the values from
3288 try_decode_frame(ic, st, pkt,
3289 (options && i < orig_nb_streams) ? &options[i] : NULL);
3291 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3292 av_packet_unref(pkt);
3294 st->codec_info_nb_frames++;
3299 AVPacket empty_pkt = { 0 };
3301 av_init_packet(&empty_pkt);
3303 for (i = 0; i < ic->nb_streams; i++) {
3305 st = ic->streams[i];
3307 /* flush the decoders */
3308 if (st->info->found_decoder == 1) {
3310 err = try_decode_frame(ic, st, &empty_pkt,
3311 (options && i < orig_nb_streams)
3312 ? &options[i] : NULL);
3313 } while (err > 0 && !has_codec_parameters(st, NULL));
3316 av_log(ic, AV_LOG_INFO,
3317 "decoding for stream %d failed\n", st->index);
3323 // close codecs which were opened in try_decode_frame()
3324 for (i = 0; i < ic->nb_streams; i++) {
3325 st = ic->streams[i];
3326 avcodec_close(st->codec);
3329 ff_rfps_calculate(ic);
3331 for (i = 0; i < ic->nb_streams; i++) {
3332 st = ic->streams[i];
3333 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3334 if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample) {
3335 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
3336 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == st->codec->pix_fmt)
3337 st->codec->codec_tag= tag;
3340 /* estimate average framerate if not set by demuxer */
3341 if (st->info->codec_info_duration_fields &&
3342 !st->avg_frame_rate.num &&
3343 st->info->codec_info_duration) {
3345 double best_error = 0.01;
3347 if (st->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3348 st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3349 st->info->codec_info_duration < 0)
3351 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3352 st->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3353 st->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3355 /* Round guessed framerate to a "standard" framerate if it's
3356 * within 1% of the original estimate. */
3357 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3358 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3359 double error = fabs(av_q2d(st->avg_frame_rate) /
3360 av_q2d(std_fps) - 1);
3362 if (error < best_error) {
3364 best_fps = std_fps.num;
3368 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3369 best_fps, 12 * 1001, INT_MAX);
3372 if (!st->r_frame_rate.num) {
3373 if ( st->codec->time_base.den * (int64_t) st->time_base.num
3374 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t) st->time_base.den) {
3375 st->r_frame_rate.num = st->codec->time_base.den;
3376 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
3378 st->r_frame_rate.num = st->time_base.den;
3379 st->r_frame_rate.den = st->time_base.num;
3382 if (st->display_aspect_ratio.num && st->display_aspect_ratio.den) {
3383 AVRational hw_ratio = { st->codec->height, st->codec->width };
3384 st->sample_aspect_ratio = av_mul_q(st->display_aspect_ratio,
3387 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3388 if (!st->codec->bits_per_coded_sample)
3389 st->codec->bits_per_coded_sample =
3390 av_get_bits_per_sample(st->codec->codec_id);
3391 // set stream disposition based on audio service type
3392 switch (st->codec->audio_service_type) {
3393 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
3394 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
3396 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
3397 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
3399 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
3400 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
3402 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
3403 st->disposition = AV_DISPOSITION_COMMENT;
3405 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
3406 st->disposition = AV_DISPOSITION_KARAOKE;
3413 estimate_timings(ic, old_offset);
3415 av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
3417 if (ret >= 0 && ic->nb_streams)
3418 /* We could not have all the codec parameters before EOF. */
3420 for (i = 0; i < ic->nb_streams; i++) {
3422 st = ic->streams[i];
3423 if (!has_codec_parameters(st, &errmsg)) {
3425 avcodec_string(buf, sizeof(buf), st->codec, 0);
3426 av_log(ic, AV_LOG_WARNING,
3427 "Could not find codec parameters for stream %d (%s): %s\n"
3428 "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",
3435 compute_chapters_end(ic);
3437 find_stream_info_err:
3438 for (i = 0; i < ic->nb_streams; i++) {
3439 st = ic->streams[i];
3440 if (ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3441 ic->streams[i]->codec->thread_count = 0;
3443 av_freep(&st->info->duration_error);
3444 av_freep(&ic->streams[i]->info);
3447 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
3448 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
3452 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
3456 for (i = 0; i < ic->nb_programs; i++) {
3457 if (ic->programs[i] == last) {
3461 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
3462 if (ic->programs[i]->stream_index[j] == s)
3463 return ic->programs[i];
3469 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
3470 int wanted_stream_nb, int related_stream,
3471 AVCodec **decoder_ret, int flags)
3473 int i, nb_streams = ic->nb_streams;
3474 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
3475 unsigned *program = NULL;
3476 const AVCodec *decoder = NULL, *best_decoder = NULL;
3478 if (related_stream >= 0 && wanted_stream_nb < 0) {
3479 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
3481 program = p->stream_index;
3482 nb_streams = p->nb_stream_indexes;
3485 for (i = 0; i < nb_streams; i++) {
3486 int real_stream_index = program ? program[i] : i;
3487 AVStream *st = ic->streams[real_stream_index];
3488 AVCodecContext *avctx = st->codec;
3489 if (avctx->codec_type != type)
3491 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
3493 if (wanted_stream_nb != real_stream_index &&
3494 st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
3495 AV_DISPOSITION_VISUAL_IMPAIRED))
3497 if (type == AVMEDIA_TYPE_AUDIO && !avctx->channels)
3500 decoder = find_decoder(ic, st, st->codec->codec_id);
3503 ret = AVERROR_DECODER_NOT_FOUND;
3507 count = st->codec_info_nb_frames;
3508 bitrate = avctx->bit_rate;
3510 bitrate = avctx->rc_max_rate;
3511 multiframe = FFMIN(5, count);
3512 if ((best_multiframe > multiframe) ||
3513 (best_multiframe == multiframe && best_bitrate > bitrate) ||
3514 (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
3517 best_bitrate = bitrate;
3518 best_multiframe = multiframe;
3519 ret = real_stream_index;
3520 best_decoder = decoder;
3521 if (program && i == nb_streams - 1 && ret < 0) {
3523 nb_streams = ic->nb_streams;
3524 /* no related stream found, try again with everything */
3529 *decoder_ret = (AVCodec*)best_decoder;
3533 /*******************************************************/
3535 int av_read_play(AVFormatContext *s)
3537 if (s->iformat->read_play)
3538 return s->iformat->read_play(s);
3540 return avio_pause(s->pb, 0);
3541 return AVERROR(ENOSYS);
3544 int av_read_pause(AVFormatContext *s)
3546 if (s->iformat->read_pause)
3547 return s->iformat->read_pause(s);
3549 return avio_pause(s->pb, 1);
3550 return AVERROR(ENOSYS);
3553 void ff_free_stream(AVFormatContext *s, AVStream *st) {
3555 av_assert0(s->nb_streams>0);
3556 av_assert0(s->streams[ s->nb_streams - 1 ] == st);
3558 for (j = 0; j < st->nb_side_data; j++)
3559 av_freep(&st->side_data[j].data);
3560 av_freep(&st->side_data);
3561 st->nb_side_data = 0;
3564 av_parser_close(st->parser);
3566 if (st->attached_pic.data)
3567 av_free_packet(&st->attached_pic);
3568 av_dict_free(&st->metadata);
3569 av_freep(&st->probe_data.buf);
3570 av_freep(&st->index_entries);
3571 av_freep(&st->codec->extradata);
3572 av_freep(&st->codec->subtitle_header);
3573 av_freep(&st->codec);
3574 av_freep(&st->priv_data);
3576 av_freep(&st->info->duration_error);
3577 av_freep(&st->info);
3578 av_freep(&st->recommended_encoder_configuration);
3579 av_freep(&s->streams[ --s->nb_streams ]);
3582 void avformat_free_context(AVFormatContext *s)
3590 if (s->iformat && s->iformat->priv_class && s->priv_data)
3591 av_opt_free(s->priv_data);
3592 if (s->oformat && s->oformat->priv_class && s->priv_data)
3593 av_opt_free(s->priv_data);
3595 for (i = s->nb_streams - 1; i >= 0; i--) {
3596 ff_free_stream(s, s->streams[i]);
3598 for (i = s->nb_programs - 1; i >= 0; i--) {
3599 av_dict_free(&s->programs[i]->metadata);
3600 av_freep(&s->programs[i]->stream_index);
3601 av_freep(&s->programs[i]);
3603 av_freep(&s->programs);
3604 av_freep(&s->priv_data);
3605 while (s->nb_chapters--) {
3606 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
3607 av_freep(&s->chapters[s->nb_chapters]);
3609 av_freep(&s->chapters);
3610 av_dict_free(&s->metadata);
3611 av_freep(&s->streams);
3612 av_freep(&s->internal);
3613 flush_packet_queue(s);
3617 void avformat_close_input(AVFormatContext **ps)
3628 if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
3629 (s->flags & AVFMT_FLAG_CUSTOM_IO))
3632 flush_packet_queue(s);
3635 if (s->iformat->read_close)
3636 s->iformat->read_close(s);
3638 avformat_free_context(s);
3645 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
3651 if (s->nb_streams >= INT_MAX/sizeof(*streams))
3653 streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
3656 s->streams = streams;
3658 st = av_mallocz(sizeof(AVStream));
3661 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
3665 st->info->last_dts = AV_NOPTS_VALUE;
3667 st->codec = avcodec_alloc_context3(c);
3674 /* no default bitrate if decoding */
3675 st->codec->bit_rate = 0;
3677 /* default pts setting is MPEG-like */
3678 avpriv_set_pts_info(st, 33, 1, 90000);
3681 st->index = s->nb_streams;
3682 st->start_time = AV_NOPTS_VALUE;
3683 st->duration = AV_NOPTS_VALUE;
3684 /* we set the current DTS to 0 so that formats without any timestamps
3685 * but durations get some timestamps, formats with some unknown
3686 * timestamps have their first few packets buffered and the
3687 * timestamps corrected before they are returned to the user */
3688 st->cur_dts = s->iformat ? RELATIVE_TS_BASE : 0;
3689 st->first_dts = AV_NOPTS_VALUE;
3690 st->probe_packets = MAX_PROBE_PACKETS;
3691 st->pts_wrap_reference = AV_NOPTS_VALUE;
3692 st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3694 st->last_IP_pts = AV_NOPTS_VALUE;
3695 st->last_dts_for_order_check = AV_NOPTS_VALUE;
3696 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
3697 st->pts_buffer[i] = AV_NOPTS_VALUE;
3699 st->sample_aspect_ratio = (AVRational) { 0, 1 };
3701 #if FF_API_R_FRAME_RATE
3702 st->info->last_dts = AV_NOPTS_VALUE;
3704 st->info->fps_first_dts = AV_NOPTS_VALUE;
3705 st->info->fps_last_dts = AV_NOPTS_VALUE;
3707 st->inject_global_side_data = s->internal->inject_global_side_data;
3709 s->streams[s->nb_streams++] = st;
3713 AVProgram *av_new_program(AVFormatContext *ac, int id)
3715 AVProgram *program = NULL;
3718 av_dlog(ac, "new_program: id=0x%04x\n", id);
3720 for (i = 0; i < ac->nb_programs; i++)
3721 if (ac->programs[i]->id == id)
3722 program = ac->programs[i];
3725 program = av_mallocz(sizeof(AVProgram));
3728 dynarray_add(&ac->programs, &ac->nb_programs, program);
3729 program->discard = AVDISCARD_NONE;
3732 program->pts_wrap_reference = AV_NOPTS_VALUE;
3733 program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3735 program->start_time =
3736 program->end_time = AV_NOPTS_VALUE;
3741 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
3742 int64_t start, int64_t end, const char *title)
3744 AVChapter *chapter = NULL;
3747 if (end != AV_NOPTS_VALUE && start > end) {
3748 av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
3752 for (i = 0; i < s->nb_chapters; i++)
3753 if (s->chapters[i]->id == id)
3754 chapter = s->chapters[i];
3757 chapter = av_mallocz(sizeof(AVChapter));
3760 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
3762 av_dict_set(&chapter->metadata, "title", title, 0);
3764 chapter->time_base = time_base;
3765 chapter->start = start;
3771 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
3774 AVProgram *program = NULL;
3777 if (idx >= ac->nb_streams) {
3778 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3782 for (i = 0; i < ac->nb_programs; i++) {
3783 if (ac->programs[i]->id != progid)
3785 program = ac->programs[i];
3786 for (j = 0; j < program->nb_stream_indexes; j++)
3787 if (program->stream_index[j] == idx)
3790 tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
3793 program->stream_index = tmp;
3794 program->stream_index[program->nb_stream_indexes++] = idx;
3799 uint64_t ff_ntp_time(void)
3801 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3804 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
3807 char *q, buf1[20], c;
3808 int nd, len, percentd_found;
3820 while (av_isdigit(*p))
3821 nd = nd * 10 + *p++ - '0';
3823 } while (av_isdigit(c));
3832 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3834 if ((q - buf + len) > buf_size - 1)
3836 memcpy(q, buf1, len);
3844 if ((q - buf) < buf_size - 1)
3848 if (!percentd_found)
3857 void av_url_split(char *proto, int proto_size,
3858 char *authorization, int authorization_size,
3859 char *hostname, int hostname_size,
3860 int *port_ptr, char *path, int path_size, const char *url)
3862 const char *p, *ls, *ls2, *at, *at2, *col, *brk;
3868 if (authorization_size > 0)
3869 authorization[0] = 0;
3870 if (hostname_size > 0)
3875 /* parse protocol */
3876 if ((p = strchr(url, ':'))) {
3877 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3884 /* no protocol means plain filename */
3885 av_strlcpy(path, url, path_size);
3889 /* separate path from hostname */
3890 ls = strchr(p, '/');
3891 ls2 = strchr(p, '?');
3895 ls = FFMIN(ls, ls2);
3897 av_strlcpy(path, ls, path_size);
3899 ls = &p[strlen(p)]; // XXX
3901 /* the rest is hostname, use that to parse auth/port */
3903 /* authorization (user[:pass]@hostname) */
3905 while ((at = strchr(p, '@')) && at < ls) {
3906 av_strlcpy(authorization, at2,
3907 FFMIN(authorization_size, at + 1 - at2));
3908 p = at + 1; /* skip '@' */
3911 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3913 av_strlcpy(hostname, p + 1,
3914 FFMIN(hostname_size, brk - p));
3915 if (brk[1] == ':' && port_ptr)
3916 *port_ptr = atoi(brk + 2);
3917 } else if ((col = strchr(p, ':')) && col < ls) {
3918 av_strlcpy(hostname, p,
3919 FFMIN(col + 1 - p, hostname_size));
3921 *port_ptr = atoi(col + 1);
3923 av_strlcpy(hostname, p,
3924 FFMIN(ls + 1 - p, hostname_size));
3928 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3931 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3934 'C', 'D', 'E', 'F' };
3935 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3938 'c', 'd', 'e', 'f' };
3939 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3941 for (i = 0; i < s; i++) {
3942 buff[i * 2] = hex_table[src[i] >> 4];
3943 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3949 int ff_hex_to_data(uint8_t *data, const char *p)
3956 p += strspn(p, SPACE_CHARS);
3959 c = av_toupper((unsigned char) *p++);
3960 if (c >= '0' && c <= '9')
3962 else if (c >= 'A' && c <= 'F')
3977 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3978 unsigned int pts_num, unsigned int pts_den)
3981 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
3982 if (new_tb.num != pts_num)
3983 av_log(NULL, AV_LOG_DEBUG,
3984 "st:%d removing common factor %d from timebase\n",
3985 s->index, pts_num / new_tb.num);
3987 av_log(NULL, AV_LOG_WARNING,
3988 "st:%d has too large timebase, reducing\n", s->index);
3990 if (new_tb.num <= 0 || new_tb.den <= 0) {
3991 av_log(NULL, AV_LOG_ERROR,
3992 "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
3993 new_tb.num, new_tb.den,
3997 s->time_base = new_tb;
3998 av_codec_set_pkt_timebase(s->codec, new_tb);
3999 s->pts_wrap_bits = pts_wrap_bits;
4002 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4005 const char *ptr = str;
4007 /* Parse key=value pairs. */
4010 char *dest = NULL, *dest_end;
4011 int key_len, dest_len = 0;
4013 /* Skip whitespace and potential commas. */
4014 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4021 if (!(ptr = strchr(key, '=')))
4024 key_len = ptr - key;
4026 callback_get_buf(context, key, key_len, &dest, &dest_len);
4027 dest_end = dest + dest_len - 1;
4031 while (*ptr && *ptr != '\"') {
4035 if (dest && dest < dest_end)
4039 if (dest && dest < dest_end)
4047 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4048 if (dest && dest < dest_end)
4056 int ff_find_stream_index(AVFormatContext *s, int id)
4059 for (i = 0; i < s->nb_streams; i++)
4060 if (s->streams[i]->id == id)
4065 int64_t ff_iso8601_to_unix_time(const char *datestr)
4067 struct tm time1 = { 0 }, time2 = { 0 };
4069 ret1 = av_small_strptime(datestr, "%Y - %m - %d %H:%M:%S", &time1);
4070 ret2 = av_small_strptime(datestr, "%Y - %m - %dT%H:%M:%S", &time2);
4072 return av_timegm(&time2);
4074 return av_timegm(&time1);
4077 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
4081 if (ofmt->query_codec)
4082 return ofmt->query_codec(codec_id, std_compliance);
4083 else if (ofmt->codec_tag)
4084 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
4085 else if (codec_id == ofmt->video_codec ||
4086 codec_id == ofmt->audio_codec ||
4087 codec_id == ofmt->subtitle_codec)
4090 return AVERROR_PATCHWELCOME;
4093 int avformat_network_init(void)
4097 ff_network_inited_globally = 1;
4098 if ((ret = ff_network_init()) < 0)
4105 int avformat_network_deinit(void)
4114 int ff_add_param_change(AVPacket *pkt, int32_t channels,
4115 uint64_t channel_layout, int32_t sample_rate,
4116 int32_t width, int32_t height)
4122 return AVERROR(EINVAL);
4125 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
4127 if (channel_layout) {
4129 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
4133 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
4135 if (width || height) {
4137 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
4139 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
4141 return AVERROR(ENOMEM);
4142 bytestream_put_le32(&data, flags);
4144 bytestream_put_le32(&data, channels);
4146 bytestream_put_le64(&data, channel_layout);
4148 bytestream_put_le32(&data, sample_rate);
4149 if (width || height) {
4150 bytestream_put_le32(&data, width);
4151 bytestream_put_le32(&data, height);
4156 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
4158 AVRational undef = {0, 1};
4159 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
4160 AVRational codec_sample_aspect_ratio = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
4161 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
4163 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
4164 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
4165 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
4166 stream_sample_aspect_ratio = undef;
4168 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
4169 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
4170 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
4171 frame_sample_aspect_ratio = undef;
4173 if (stream_sample_aspect_ratio.num)
4174 return stream_sample_aspect_ratio;
4176 return frame_sample_aspect_ratio;
4179 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
4181 AVRational fr = st->r_frame_rate;
4182 AVRational codec_fr = st->codec->framerate;
4183 AVRational avg_fr = st->avg_frame_rate;
4185 if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
4186 av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
4191 if (st->codec->ticks_per_frame > 1) {
4192 if ( codec_fr.num > 0 && codec_fr.den > 0 && av_q2d(codec_fr) < av_q2d(fr)*0.7
4193 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1)
4200 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
4203 if (*spec <= '9' && *spec >= '0') /* opt:index */
4204 return strtol(spec, NULL, 0) == st->index;
4205 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
4206 *spec == 't') { /* opt:[vasdt] */
4207 enum AVMediaType type;
4210 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
4211 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
4212 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
4213 case 'd': type = AVMEDIA_TYPE_DATA; break;
4214 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
4215 default: av_assert0(0);
4217 if (type != st->codec->codec_type)
4219 if (*spec++ == ':') { /* possibly followed by :index */
4220 int i, index = strtol(spec, NULL, 0);
4221 for (i = 0; i < s->nb_streams; i++)
4222 if (s->streams[i]->codec->codec_type == type && index-- == 0)
4223 return i == st->index;
4227 } else if (*spec == 'p' && *(spec + 1) == ':') {
4231 prog_id = strtol(spec, &endptr, 0);
4232 for (i = 0; i < s->nb_programs; i++) {
4233 if (s->programs[i]->id != prog_id)
4236 if (*endptr++ == ':') {
4237 int stream_idx = strtol(endptr, NULL, 0);
4238 return stream_idx >= 0 &&
4239 stream_idx < s->programs[i]->nb_stream_indexes &&
4240 st->index == s->programs[i]->stream_index[stream_idx];
4243 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
4244 if (st->index == s->programs[i]->stream_index[j])
4248 } else if (*spec == '#' ||
4249 (*spec == 'i' && *(spec + 1) == ':')) {
4252 spec += 1 + (*spec == 'i');
4253 stream_id = strtol(spec, &endptr, 0);
4255 return stream_id == st->id;
4256 } else if (*spec == 'm' && *(spec + 1) == ':') {
4257 AVDictionaryEntry *tag;
4262 val = strchr(spec, ':');
4264 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
4266 return AVERROR(ENOMEM);
4268 tag = av_dict_get(st->metadata, key, NULL, 0);
4270 if (!val || !strcmp(tag->value, val + 1))
4279 } else if (!*spec) /* empty specifier, matches everything */
4282 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
4283 return AVERROR(EINVAL);
4286 int ff_generate_avci_extradata(AVStream *st)
4288 static const uint8_t avci100_1080p_extradata[] = {
4290 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4291 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4292 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4293 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
4294 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
4295 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
4296 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
4297 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
4298 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4300 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4303 static const uint8_t avci100_1080i_extradata[] = {
4305 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4306 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4307 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4308 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
4309 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
4310 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
4311 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
4312 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
4313 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
4314 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
4315 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
4317 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4320 static const uint8_t avci50_1080p_extradata[] = {
4322 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4323 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4324 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4325 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4326 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4327 0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
4328 0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
4329 0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
4330 0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
4332 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4335 static const uint8_t avci50_1080i_extradata[] = {
4337 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4338 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4339 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4340 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
4341 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
4342 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
4343 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
4344 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
4345 0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
4346 0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
4347 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
4349 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4352 static const uint8_t avci100_720p_extradata[] = {
4354 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4355 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
4356 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
4357 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
4358 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
4359 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
4360 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
4361 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
4362 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
4363 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
4365 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
4368 static const uint8_t avci50_720p_extradata[] = {
4370 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
4371 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4372 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4373 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4374 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4375 0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
4376 0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
4377 0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
4378 0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
4380 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4384 const uint8_t *data = NULL;
4387 if (st->codec->width == 1920) {
4388 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4389 data = avci100_1080p_extradata;
4390 size = sizeof(avci100_1080p_extradata);
4392 data = avci100_1080i_extradata;
4393 size = sizeof(avci100_1080i_extradata);
4395 } else if (st->codec->width == 1440) {
4396 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4397 data = avci50_1080p_extradata;
4398 size = sizeof(avci50_1080p_extradata);
4400 data = avci50_1080i_extradata;
4401 size = sizeof(avci50_1080i_extradata);
4403 } else if (st->codec->width == 1280) {
4404 data = avci100_720p_extradata;
4405 size = sizeof(avci100_720p_extradata);
4406 } else if (st->codec->width == 960) {
4407 data = avci50_720p_extradata;
4408 size = sizeof(avci50_720p_extradata);
4414 av_freep(&st->codec->extradata);
4415 if (ff_alloc_extradata(st->codec, size))
4416 return AVERROR(ENOMEM);
4417 memcpy(st->codec->extradata, data, size);
4422 uint8_t *av_stream_get_side_data(AVStream *st, enum AVPacketSideDataType type,
4427 for (i = 0; i < st->nb_side_data; i++) {
4428 if (st->side_data[i].type == type) {
4430 *size = st->side_data[i].size;
4431 return st->side_data[i].data;
4437 uint8_t *ff_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
4440 AVPacketSideData *sd, *tmp;
4442 uint8_t *data = av_malloc(size);
4447 for (i = 0; i < st->nb_side_data; i++) {
4448 sd = &st->side_data[i];
4450 if (sd->type == type) {
4451 av_freep(&sd->data);
4458 tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));
4464 st->side_data = tmp;
4467 sd = &st->side_data[st->nb_side_data - 1];