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
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/parseutils.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/time.h"
36 #include "libavutil/timestamp.h"
38 #include "libavcodec/bytestream.h"
39 #include "libavcodec/internal.h"
40 #include "libavcodec/raw.h"
42 #include "audiointerleave.h"
44 #include "avio_internal.h"
54 #include "libavutil/ffversion.h"
55 const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
59 * various utility functions for use within FFmpeg
62 unsigned avformat_version(void)
64 av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
65 return LIBAVFORMAT_VERSION_INT;
68 const char *avformat_configuration(void)
70 return FFMPEG_CONFIGURATION;
73 const char *avformat_license(void)
75 #define LICENSE_PREFIX "libavformat license: "
76 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
79 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
81 static int is_relative(int64_t ts) {
82 return ts > (RELATIVE_TS_BASE - (1LL<<48));
86 * Wrap a given time stamp, if there is an indication for an overflow
89 * @param timestamp the time stamp to wrap
90 * @return resulting time stamp
92 static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
94 if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE &&
95 st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
96 if (st->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
97 timestamp < st->pts_wrap_reference)
98 return timestamp + (1ULL << st->pts_wrap_bits);
99 else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
100 timestamp >= st->pts_wrap_reference)
101 return timestamp - (1ULL << st->pts_wrap_bits);
106 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
107 MAKE_ACCESSORS(AVStream, stream, char *, recommended_encoder_configuration)
108 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
109 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
110 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
111 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, data_codec)
112 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
113 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
114 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
115 MAKE_ACCESSORS(AVFormatContext, format, AVOpenCallback, open_cb)
117 int64_t av_stream_get_end_pts(const AVStream *st)
120 return st->priv_pts->val;
122 return AV_NOPTS_VALUE;
125 struct AVCodecParserContext *av_stream_get_parser(const AVStream *st)
130 void av_format_inject_global_side_data(AVFormatContext *s)
133 s->internal->inject_global_side_data = 1;
134 for (i = 0; i < s->nb_streams; i++) {
135 AVStream *st = s->streams[i];
136 st->inject_global_side_data = 1;
140 int ff_copy_whitelists(AVFormatContext *dst, AVFormatContext *src)
142 av_assert0(!dst->codec_whitelist && !dst->format_whitelist);
143 dst-> codec_whitelist = av_strdup(src->codec_whitelist);
144 dst->format_whitelist = av_strdup(src->format_whitelist);
145 if ( (src-> codec_whitelist && !dst-> codec_whitelist)
146 || (src->format_whitelist && !dst->format_whitelist)) {
147 av_log(dst, AV_LOG_ERROR, "Failed to duplicate whitelist\n");
148 return AVERROR(ENOMEM);
153 static const AVCodec *find_decoder(AVFormatContext *s, AVStream *st, enum AVCodecID codec_id)
155 if (st->codec->codec)
156 return st->codec->codec;
158 switch (st->codec->codec_type) {
159 case AVMEDIA_TYPE_VIDEO:
160 if (s->video_codec) return s->video_codec;
162 case AVMEDIA_TYPE_AUDIO:
163 if (s->audio_codec) return s->audio_codec;
165 case AVMEDIA_TYPE_SUBTITLE:
166 if (s->subtitle_codec) return s->subtitle_codec;
170 return avcodec_find_decoder(codec_id);
173 int av_format_get_probe_score(const AVFormatContext *s)
175 return s->probe_score;
178 /* an arbitrarily chosen "sane" max packet size -- 50M */
179 #define SANE_CHUNK_SIZE (50000000)
181 int ffio_limit(AVIOContext *s, int size)
183 if (s->maxsize>= 0) {
184 int64_t remaining= s->maxsize - avio_tell(s);
185 if (remaining < size) {
186 int64_t newsize = avio_size(s);
187 if (!s->maxsize || s->maxsize<newsize)
188 s->maxsize = newsize - !newsize;
189 remaining= s->maxsize - avio_tell(s);
190 remaining= FFMAX(remaining, 0);
193 if (s->maxsize>= 0 && remaining+1 < size) {
194 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
201 /* Read the data in sane-sized chunks and append to pkt.
202 * Return the number of bytes read or an error. */
203 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
205 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
206 int orig_size = pkt->size;
210 int prev_size = pkt->size;
213 /* When the caller requests a lot of data, limit it to the amount
214 * left in file or SANE_CHUNK_SIZE when it is not known. */
216 if (read_size > SANE_CHUNK_SIZE/10) {
217 read_size = ffio_limit(s, read_size);
218 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
220 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
223 ret = av_grow_packet(pkt, read_size);
227 ret = avio_read(s, pkt->data + prev_size, read_size);
228 if (ret != read_size) {
229 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
236 pkt->flags |= AV_PKT_FLAG_CORRUPT;
241 return pkt->size > orig_size ? pkt->size - orig_size : ret;
244 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
249 pkt->pos = avio_tell(s);
251 return append_packet_chunked(s, pkt, size);
254 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
257 return av_get_packet(s, pkt, size);
258 return append_packet_chunked(s, pkt, size);
261 int av_filename_number_test(const char *filename)
265 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
268 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
271 static const struct {
274 enum AVMediaType type;
276 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
277 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
278 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
279 { "dvbsub", AV_CODEC_ID_DVB_SUBTITLE,AVMEDIA_TYPE_SUBTITLE },
280 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
281 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
282 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
283 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
284 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
285 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
286 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
290 AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
292 if (fmt && st->request_probe <= score) {
294 av_log(s, AV_LOG_DEBUG,
295 "Probe with size=%d, packets=%d detected %s with score=%d\n",
296 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
298 for (i = 0; fmt_id_type[i].name; i++) {
299 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
300 st->codec->codec_id = fmt_id_type[i].id;
301 st->codec->codec_type = fmt_id_type[i].type;
309 /************************************************************/
310 /* input media file */
312 int av_demuxer_open(AVFormatContext *ic) {
315 if (ic->format_whitelist && av_match_list(ic->iformat->name, ic->format_whitelist, ',') <= 0) {
316 av_log(ic, AV_LOG_ERROR, "Format not on whitelist\n");
317 return AVERROR(EINVAL);
320 if (ic->iformat->read_header) {
321 err = ic->iformat->read_header(ic);
326 if (ic->pb && !ic->internal->data_offset)
327 ic->internal->data_offset = avio_tell(ic->pb);
332 /* Open input file and probe the format if necessary. */
333 static int init_input(AVFormatContext *s, const char *filename,
334 AVDictionary **options)
337 AVProbeData pd = { filename, NULL, 0 };
338 int score = AVPROBE_SCORE_RETRY;
341 s->flags |= AVFMT_FLAG_CUSTOM_IO;
343 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
344 s, 0, s->format_probesize);
345 else if (s->iformat->flags & AVFMT_NOFILE)
346 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
347 "will be ignored with AVFMT_NOFILE format.\n");
351 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
352 (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
355 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
356 &s->interrupt_callback, options)) < 0)
360 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
361 s, 0, s->format_probesize);
364 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
365 AVPacketList **plast_pktl)
367 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
372 (*plast_pktl)->next = pktl;
374 *packet_buffer = pktl;
376 /* Add the packet in the buffered packet list. */
382 int avformat_queue_attached_pictures(AVFormatContext *s)
385 for (i = 0; i < s->nb_streams; i++)
386 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
387 s->streams[i]->discard < AVDISCARD_ALL) {
388 AVPacket copy = s->streams[i]->attached_pic;
389 if (copy.size <= 0) {
390 av_log(s, AV_LOG_WARNING,
391 "Attached picture on stream %d has invalid size, "
395 copy.buf = av_buffer_ref(copy.buf);
397 return AVERROR(ENOMEM);
399 add_to_pktbuf(&s->internal->raw_packet_buffer, ©,
400 &s->internal->raw_packet_buffer_end);
405 int avformat_open_input(AVFormatContext **ps, const char *filename,
406 AVInputFormat *fmt, AVDictionary **options)
408 AVFormatContext *s = *ps;
410 AVDictionary *tmp = NULL;
411 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
413 if (!s && !(s = avformat_alloc_context()))
414 return AVERROR(ENOMEM);
416 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
417 return AVERROR(EINVAL);
423 av_dict_copy(&tmp, *options, 0);
425 if (s->pb) // must be before any goto fail
426 s->flags |= AVFMT_FLAG_CUSTOM_IO;
428 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
431 if ((ret = init_input(s, filename, &tmp)) < 0)
433 s->probe_score = ret;
435 if (s->format_whitelist && av_match_list(s->iformat->name, s->format_whitelist, ',') <= 0) {
436 av_log(s, AV_LOG_ERROR, "Format not on whitelist\n");
437 ret = AVERROR(EINVAL);
441 avio_skip(s->pb, s->skip_initial_bytes);
443 /* Check filename in case an image number is expected. */
444 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
445 if (!av_filename_number_test(filename)) {
446 ret = AVERROR(EINVAL);
451 s->duration = s->start_time = AV_NOPTS_VALUE;
452 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
454 /* Allocate private data. */
455 if (s->iformat->priv_data_size > 0) {
456 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
457 ret = AVERROR(ENOMEM);
460 if (s->iformat->priv_class) {
461 *(const AVClass **) s->priv_data = s->iformat->priv_class;
462 av_opt_set_defaults(s->priv_data);
463 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
468 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
470 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, 0);
472 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
473 if ((ret = s->iformat->read_header(s)) < 0)
476 if (id3v2_extra_meta) {
477 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
478 !strcmp(s->iformat->name, "tta")) {
479 if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
482 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
484 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
486 if ((ret = avformat_queue_attached_pictures(s)) < 0)
489 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->internal->data_offset)
490 s->internal->data_offset = avio_tell(s->pb);
492 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
495 av_dict_free(options);
502 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
504 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
506 avformat_free_context(s);
511 /*******************************************************/
513 static void force_codec_ids(AVFormatContext *s, AVStream *st)
515 switch (st->codec->codec_type) {
516 case AVMEDIA_TYPE_VIDEO:
517 if (s->video_codec_id)
518 st->codec->codec_id = s->video_codec_id;
520 case AVMEDIA_TYPE_AUDIO:
521 if (s->audio_codec_id)
522 st->codec->codec_id = s->audio_codec_id;
524 case AVMEDIA_TYPE_SUBTITLE:
525 if (s->subtitle_codec_id)
526 st->codec->codec_id = s->subtitle_codec_id;
531 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
533 if (st->request_probe>0) {
534 AVProbeData *pd = &st->probe_data;
536 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
540 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
542 av_log(s, AV_LOG_WARNING,
543 "Failed to reallocate probe buffer for stream %d\n",
548 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
549 pd->buf_size += pkt->size;
550 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
553 st->probe_packets = 0;
555 av_log(s, AV_LOG_WARNING,
556 "nothing to probe for stream %d\n", st->index);
560 end= s->internal->raw_packet_buffer_remaining_size <= 0
561 || st->probe_packets<= 0;
563 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
564 int score = set_codec_from_probe_data(s, st, pd);
565 if ( (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
569 st->request_probe = -1;
570 if (st->codec->codec_id != AV_CODEC_ID_NONE) {
571 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
573 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
575 force_codec_ids(s, st);
581 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
583 int64_t ref = pkt->dts;
584 int i, pts_wrap_behavior;
585 int64_t pts_wrap_reference;
586 AVProgram *first_program;
588 if (ref == AV_NOPTS_VALUE)
590 if (st->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
592 ref &= (1LL << st->pts_wrap_bits)-1;
594 // reference time stamp should be 60 s before first time stamp
595 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
596 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
597 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
598 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
599 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
601 first_program = av_find_program_from_stream(s, NULL, stream_index);
603 if (!first_program) {
604 int default_stream_index = av_find_default_stream_index(s);
605 if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {
606 for (i = 0; i < s->nb_streams; i++) {
607 if (av_find_program_from_stream(s, NULL, i))
609 s->streams[i]->pts_wrap_reference = pts_wrap_reference;
610 s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;
614 st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;
615 st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;
619 AVProgram *program = first_program;
621 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
622 pts_wrap_reference = program->pts_wrap_reference;
623 pts_wrap_behavior = program->pts_wrap_behavior;
626 program = av_find_program_from_stream(s, program, stream_index);
629 // update every program with differing pts_wrap_reference
630 program = first_program;
632 if (program->pts_wrap_reference != pts_wrap_reference) {
633 for (i = 0; i<program->nb_stream_indexes; i++) {
634 s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;
635 s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;
638 program->pts_wrap_reference = pts_wrap_reference;
639 program->pts_wrap_behavior = pts_wrap_behavior;
641 program = av_find_program_from_stream(s, program, stream_index);
647 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
653 AVPacketList *pktl = s->internal->raw_packet_buffer;
657 st = s->streams[pkt->stream_index];
658 if (s->internal->raw_packet_buffer_remaining_size <= 0)
659 if ((err = probe_codec(s, st, NULL)) < 0)
661 if (st->request_probe <= 0) {
662 s->internal->raw_packet_buffer = pktl->next;
663 s->internal->raw_packet_buffer_remaining_size += pkt->size;
672 ret = s->iformat->read_packet(s, pkt);
674 if (!pktl || ret == AVERROR(EAGAIN))
676 for (i = 0; i < s->nb_streams; i++) {
678 if (st->probe_packets)
679 if ((err = probe_codec(s, st, NULL)) < 0)
681 av_assert0(st->request_probe <= 0);
687 AVPacket tmp = { 0 };
688 ret = av_packet_ref(&tmp, pkt);
694 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
695 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
696 av_log(s, AV_LOG_WARNING,
697 "Dropped corrupted packet (stream = %d)\n",
703 if (pkt->stream_index >= (unsigned)s->nb_streams) {
704 av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
708 st = s->streams[pkt->stream_index];
710 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
711 // correct first time stamps to negative values
712 if (!is_relative(st->first_dts))
713 st->first_dts = wrap_timestamp(st, st->first_dts);
714 if (!is_relative(st->start_time))
715 st->start_time = wrap_timestamp(st, st->start_time);
716 if (!is_relative(st->cur_dts))
717 st->cur_dts = wrap_timestamp(st, st->cur_dts);
720 pkt->dts = wrap_timestamp(st, pkt->dts);
721 pkt->pts = wrap_timestamp(st, pkt->pts);
723 force_codec_ids(s, st);
725 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
726 if (s->use_wallclock_as_timestamps)
727 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
729 if (!pktl && st->request_probe <= 0)
732 add_to_pktbuf(&s->internal->raw_packet_buffer, pkt,
733 &s->internal->raw_packet_buffer_end);
734 s->internal->raw_packet_buffer_remaining_size -= pkt->size;
736 if ((err = probe_codec(s, st, pkt)) < 0)
742 /**********************************************************/
744 static int determinable_frame_size(AVCodecContext *avctx)
746 if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
747 avctx->codec_id == AV_CODEC_ID_MP1 ||
748 avctx->codec_id == AV_CODEC_ID_MP2 ||
749 avctx->codec_id == AV_CODEC_ID_MP3/* ||
750 avctx->codec_id == AV_CODEC_ID_CELT*/)
756 * Return the frame duration in seconds. Return 0 if not available.
758 void ff_compute_frame_duration(AVFormatContext *s, int *pnum, int *pden, AVStream *st,
759 AVCodecParserContext *pc, AVPacket *pkt)
761 AVRational codec_framerate = s->iformat ? st->codec->framerate :
762 av_mul_q(av_inv_q(st->codec->time_base), (AVRational){1, st->codec->ticks_per_frame});
767 switch (st->codec->codec_type) {
768 case AVMEDIA_TYPE_VIDEO:
769 if (st->r_frame_rate.num && !pc && s->iformat) {
770 *pnum = st->r_frame_rate.den;
771 *pden = st->r_frame_rate.num;
772 } else if (st->time_base.num * 1000LL > st->time_base.den) {
773 *pnum = st->time_base.num;
774 *pden = st->time_base.den;
775 } else if (codec_framerate.den * 1000LL > codec_framerate.num) {
776 av_assert0(st->codec->ticks_per_frame);
777 av_reduce(pnum, pden,
779 codec_framerate.num * (int64_t)st->codec->ticks_per_frame,
782 if (pc && pc->repeat_pict) {
783 av_assert0(s->iformat); // this may be wrong for interlaced encoding but its not used for that case
784 av_reduce(pnum, pden,
785 (*pnum) * (1LL + pc->repeat_pict),
789 /* If this codec can be interlaced or progressive then we need
790 * a parser to compute duration of a packet. Thus if we have
791 * no parser in such case leave duration undefined. */
792 if (st->codec->ticks_per_frame > 1 && !pc)
796 case AVMEDIA_TYPE_AUDIO:
797 frame_size = av_get_audio_frame_duration(st->codec, pkt->size);
798 if (frame_size <= 0 || st->codec->sample_rate <= 0)
801 *pden = st->codec->sample_rate;
808 static int is_intra_only(AVCodecContext *enc) {
809 const AVCodecDescriptor *desc;
811 if (enc->codec_type != AVMEDIA_TYPE_VIDEO)
814 desc = av_codec_get_codec_descriptor(enc);
816 desc = avcodec_descriptor_get(enc->codec_id);
817 av_codec_set_codec_descriptor(enc, desc);
820 return !!(desc->props & AV_CODEC_PROP_INTRA_ONLY);
824 static int has_decode_delay_been_guessed(AVStream *st)
826 if (st->codec->codec_id != AV_CODEC_ID_H264) return 1;
827 if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
829 #if CONFIG_H264_DECODER
830 if (st->codec->has_b_frames &&
831 avpriv_h264_has_num_reorder_frames(st->codec) == st->codec->has_b_frames)
834 if (st->codec->has_b_frames<3)
835 return st->nb_decoded_frames >= 7;
836 else if (st->codec->has_b_frames<4)
837 return st->nb_decoded_frames >= 18;
839 return st->nb_decoded_frames >= 20;
842 static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
846 if (pktl == s->internal->packet_buffer_end)
847 return s->internal->parse_queue;
851 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
852 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
853 st->codec->codec_id != AV_CODEC_ID_HEVC;
856 int delay = st->codec->has_b_frames;
859 if (dts == AV_NOPTS_VALUE) {
860 int64_t best_score = INT64_MAX;
861 for (i = 0; i<delay; i++) {
862 if (st->pts_reorder_error_count[i]) {
863 int64_t score = st->pts_reorder_error[i] / st->pts_reorder_error_count[i];
864 if (score < best_score) {
871 for (i = 0; i<delay; i++) {
872 if (pts_buffer[i] != AV_NOPTS_VALUE) {
873 int64_t diff = FFABS(pts_buffer[i] - dts)
874 + (uint64_t)st->pts_reorder_error[i];
875 diff = FFMAX(diff, st->pts_reorder_error[i]);
876 st->pts_reorder_error[i] = diff;
877 st->pts_reorder_error_count[i]++;
878 if (st->pts_reorder_error_count[i] > 250) {
879 st->pts_reorder_error[i] >>= 1;
880 st->pts_reorder_error_count[i] >>= 1;
887 if (dts == AV_NOPTS_VALUE)
893 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
894 int64_t dts, int64_t pts, AVPacket *pkt)
896 AVStream *st = s->streams[stream_index];
897 AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
898 int64_t pts_buffer[MAX_REORDER_DELAY+1];
902 if (st->first_dts != AV_NOPTS_VALUE ||
903 dts == AV_NOPTS_VALUE ||
904 st->cur_dts == AV_NOPTS_VALUE ||
908 delay = st->codec->has_b_frames;
909 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
911 shift = st->first_dts - RELATIVE_TS_BASE;
913 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
914 pts_buffer[i] = AV_NOPTS_VALUE;
916 if (is_relative(pts))
919 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
920 if (pktl->pkt.stream_index != stream_index)
922 if (is_relative(pktl->pkt.pts))
923 pktl->pkt.pts += shift;
925 if (is_relative(pktl->pkt.dts))
926 pktl->pkt.dts += shift;
928 if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
929 st->start_time = pktl->pkt.pts;
931 if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
932 pts_buffer[0] = pktl->pkt.pts;
933 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
934 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
936 pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);
940 if (st->start_time == AV_NOPTS_VALUE)
941 st->start_time = pts;
944 static void update_initial_durations(AVFormatContext *s, AVStream *st,
945 int stream_index, int duration)
947 AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
948 int64_t cur_dts = RELATIVE_TS_BASE;
950 if (st->first_dts != AV_NOPTS_VALUE) {
951 if (st->update_initial_durations_done)
953 st->update_initial_durations_done = 1;
954 cur_dts = st->first_dts;
955 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
956 if (pktl->pkt.stream_index == stream_index) {
957 if (pktl->pkt.pts != pktl->pkt.dts ||
958 pktl->pkt.dts != AV_NOPTS_VALUE ||
964 if (pktl && pktl->pkt.dts != st->first_dts) {
965 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
966 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
970 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
973 pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
974 st->first_dts = cur_dts;
975 } else if (st->cur_dts != RELATIVE_TS_BASE)
978 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
979 if (pktl->pkt.stream_index != stream_index)
981 if (pktl->pkt.pts == pktl->pkt.dts &&
982 (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&
983 !pktl->pkt.duration) {
984 pktl->pkt.dts = cur_dts;
985 if (!st->codec->has_b_frames)
986 pktl->pkt.pts = cur_dts;
987 // if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
988 pktl->pkt.duration = duration;
991 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
994 st->cur_dts = cur_dts;
997 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
998 AVCodecParserContext *pc, AVPacket *pkt,
999 int64_t next_dts, int64_t next_pts)
1001 int num, den, presentation_delayed, delay, i;
1003 AVRational duration;
1004 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
1005 st->codec->codec_id != AV_CODEC_ID_HEVC;
1007 if (s->flags & AVFMT_FLAG_NOFILLIN)
1010 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1011 if (pkt->dts == pkt->pts && st->last_dts_for_order_check != AV_NOPTS_VALUE) {
1012 if (st->last_dts_for_order_check <= pkt->dts) {
1015 av_log(s, st->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1016 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1018 st->last_dts_for_order_check);
1019 st->dts_misordered++;
1021 if (st->dts_ordered + st->dts_misordered > 250) {
1022 st->dts_ordered >>= 1;
1023 st->dts_misordered >>= 1;
1027 st->last_dts_for_order_check = pkt->dts;
1028 if (st->dts_ordered < 8*st->dts_misordered && pkt->dts == pkt->pts)
1029 pkt->dts = AV_NOPTS_VALUE;
1032 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1033 pkt->dts = AV_NOPTS_VALUE;
1035 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1036 && !st->codec->has_b_frames)
1037 //FIXME Set low_delay = 0 when has_b_frames = 1
1038 st->codec->has_b_frames = 1;
1040 /* do we have a video B-frame ? */
1041 delay = st->codec->has_b_frames;
1042 presentation_delayed = 0;
1044 /* XXX: need has_b_frame, but cannot get it if the codec is
1045 * not initialized */
1047 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1048 presentation_delayed = 1;
1050 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1051 st->pts_wrap_bits < 63 &&
1052 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1053 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1054 pkt->dts -= 1LL << st->pts_wrap_bits;
1056 pkt->pts += 1LL << st->pts_wrap_bits;
1059 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1060 * We take the conservative approach and discard both.
1061 * Note: If this is misbehaving for an H.264 file, then possibly
1062 * presentation_delayed is not set correctly. */
1063 if (delay == 1 && pkt->dts == pkt->pts &&
1064 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1065 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1066 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1067 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1068 pkt->dts = AV_NOPTS_VALUE;
1071 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1072 if (pkt->duration == 0) {
1073 ff_compute_frame_duration(s, &num, &den, st, pc, pkt);
1075 duration = (AVRational) {num, den};
1076 pkt->duration = av_rescale_rnd(1,
1077 num * (int64_t) st->time_base.den,
1078 den * (int64_t) st->time_base.num,
1083 if (pkt->duration != 0 && (s->internal->packet_buffer || s->internal->parse_queue))
1084 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1086 /* Correct timestamps with byte offset if demuxers only have timestamps
1087 * on packet boundaries */
1088 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1089 /* this will estimate bitrate based on this frame's duration and size */
1090 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1091 if (pkt->pts != AV_NOPTS_VALUE)
1093 if (pkt->dts != AV_NOPTS_VALUE)
1097 /* This may be redundant, but it should not hurt. */
1098 if (pkt->dts != AV_NOPTS_VALUE &&
1099 pkt->pts != AV_NOPTS_VALUE &&
1100 pkt->pts > pkt->dts)
1101 presentation_delayed = 1;
1103 if (s->debug & FF_FDEBUG_TS)
1104 av_log(s, AV_LOG_TRACE,
1105 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%"PRId64" delay:%d onein_oneout:%d\n",
1106 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1107 pkt->stream_index, pc, pkt->duration, delay, onein_oneout);
1109 /* Interpolate PTS and DTS if they are not present. We skip H264
1110 * currently because delay and has_b_frames are not reliably set. */
1111 if ((delay == 0 || (delay == 1 && pc)) &&
1113 if (presentation_delayed) {
1114 /* DTS = decompression timestamp */
1115 /* PTS = presentation timestamp */
1116 if (pkt->dts == AV_NOPTS_VALUE)
1117 pkt->dts = st->last_IP_pts;
1118 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1119 if (pkt->dts == AV_NOPTS_VALUE)
1120 pkt->dts = st->cur_dts;
1122 /* This is tricky: the dts must be incremented by the duration
1123 * of the frame we are displaying, i.e. the last I- or P-frame. */
1124 if (st->last_IP_duration == 0)
1125 st->last_IP_duration = pkt->duration;
1126 if (pkt->dts != AV_NOPTS_VALUE)
1127 st->cur_dts = pkt->dts + st->last_IP_duration;
1128 if (pkt->dts != AV_NOPTS_VALUE &&
1129 pkt->pts == AV_NOPTS_VALUE &&
1130 st->last_IP_duration > 0 &&
1131 ((uint64_t)st->cur_dts - (uint64_t)next_dts + 1) <= 2 &&
1132 next_dts != next_pts &&
1133 next_pts != AV_NOPTS_VALUE)
1134 pkt->pts = next_dts;
1136 st->last_IP_duration = pkt->duration;
1137 st->last_IP_pts = pkt->pts;
1138 /* Cannot compute PTS if not present (we can compute it only
1139 * by knowing the future. */
1140 } else if (pkt->pts != AV_NOPTS_VALUE ||
1141 pkt->dts != AV_NOPTS_VALUE ||
1144 /* presentation is not delayed : PTS and DTS are the same */
1145 if (pkt->pts == AV_NOPTS_VALUE)
1146 pkt->pts = pkt->dts;
1147 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1149 if (pkt->pts == AV_NOPTS_VALUE)
1150 pkt->pts = st->cur_dts;
1151 pkt->dts = pkt->pts;
1152 if (pkt->pts != AV_NOPTS_VALUE)
1153 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1157 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
1158 st->pts_buffer[0] = pkt->pts;
1159 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
1160 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
1162 pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1164 // We skipped it above so we try here.
1166 // This should happen on the first packet
1167 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1168 if (pkt->dts > st->cur_dts)
1169 st->cur_dts = pkt->dts;
1171 if (s->debug & FF_FDEBUG_TS)
1172 av_log(s, AV_LOG_TRACE, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
1173 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1176 if (is_intra_only(st->codec))
1177 pkt->flags |= AV_PKT_FLAG_KEY;
1178 #if FF_API_CONVERGENCE_DURATION
1179 FF_DISABLE_DEPRECATION_WARNINGS
1181 pkt->convergence_duration = pc->convergence_duration;
1182 FF_ENABLE_DEPRECATION_WARNINGS
1186 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1189 AVPacketList *pktl = *pkt_buf;
1190 *pkt_buf = pktl->next;
1191 av_free_packet(&pktl->pkt);
1194 *pkt_buf_end = NULL;
1198 * Parse a packet, add all split parts to parse_queue.
1200 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1202 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1204 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1205 AVStream *st = s->streams[stream_index];
1206 uint8_t *data = pkt ? pkt->data : NULL;
1207 int size = pkt ? pkt->size : 0;
1208 int ret = 0, got_output = 0;
1211 av_init_packet(&flush_pkt);
1214 } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1215 // preserve 0-size sync packets
1216 compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1219 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1221 int64_t next_pts = pkt->pts;
1222 int64_t next_dts = pkt->dts;
1224 av_init_packet(&out_pkt);
1225 len = av_parser_parse2(st->parser, st->codec,
1226 &out_pkt.data, &out_pkt.size, data, size,
1227 pkt->pts, pkt->dts, pkt->pos);
1229 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1231 /* increment read pointer */
1235 got_output = !!out_pkt.size;
1240 if (pkt->side_data) {
1241 out_pkt.side_data = pkt->side_data;
1242 out_pkt.side_data_elems = pkt->side_data_elems;
1243 pkt->side_data = NULL;
1244 pkt->side_data_elems = 0;
1247 /* set the duration */
1248 out_pkt.duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;
1249 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1250 if (st->codec->sample_rate > 0) {
1252 av_rescale_q_rnd(st->parser->duration,
1253 (AVRational) { 1, st->codec->sample_rate },
1259 out_pkt.stream_index = st->index;
1260 out_pkt.pts = st->parser->pts;
1261 out_pkt.dts = st->parser->dts;
1262 out_pkt.pos = st->parser->pos;
1264 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1265 out_pkt.pos = st->parser->frame_offset;
1267 if (st->parser->key_frame == 1 ||
1268 (st->parser->key_frame == -1 &&
1269 st->parser->pict_type == AV_PICTURE_TYPE_I))
1270 out_pkt.flags |= AV_PKT_FLAG_KEY;
1272 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1273 out_pkt.flags |= AV_PKT_FLAG_KEY;
1275 compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);
1277 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1278 out_pkt.buf = pkt->buf;
1281 if ((ret = av_dup_packet(&out_pkt)) < 0)
1284 if (!add_to_pktbuf(&s->internal->parse_queue, &out_pkt, &s->internal->parse_queue_end)) {
1285 av_free_packet(&out_pkt);
1286 ret = AVERROR(ENOMEM);
1291 /* end of the stream => close and free the parser */
1292 if (pkt == &flush_pkt) {
1293 av_parser_close(st->parser);
1298 av_free_packet(pkt);
1302 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1303 AVPacketList **pkt_buffer_end,
1307 av_assert0(*pkt_buffer);
1310 *pkt_buffer = pktl->next;
1312 *pkt_buffer_end = NULL;
1317 static int64_t ts_to_samples(AVStream *st, int64_t ts)
1319 return av_rescale(ts, st->time_base.num * st->codec->sample_rate, st->time_base.den);
1322 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1324 int ret = 0, i, got_packet = 0;
1325 AVDictionary *metadata = NULL;
1327 av_init_packet(pkt);
1329 while (!got_packet && !s->internal->parse_queue) {
1333 /* read next packet */
1334 ret = ff_read_packet(s, &cur_pkt);
1336 if (ret == AVERROR(EAGAIN))
1338 /* flush the parsers */
1339 for (i = 0; i < s->nb_streams; i++) {
1341 if (st->parser && st->need_parsing)
1342 parse_packet(s, NULL, st->index);
1344 /* all remaining packets are now in parse_queue =>
1345 * really terminate parsing */
1349 st = s->streams[cur_pkt.stream_index];
1351 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1352 cur_pkt.dts != AV_NOPTS_VALUE &&
1353 cur_pkt.pts < cur_pkt.dts) {
1354 av_log(s, AV_LOG_WARNING,
1355 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1356 cur_pkt.stream_index,
1357 av_ts2str(cur_pkt.pts),
1358 av_ts2str(cur_pkt.dts),
1361 if (s->debug & FF_FDEBUG_TS)
1362 av_log(s, AV_LOG_DEBUG,
1363 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%"PRId64", flags=%d\n",
1364 cur_pkt.stream_index,
1365 av_ts2str(cur_pkt.pts),
1366 av_ts2str(cur_pkt.dts),
1367 cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1369 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1370 st->parser = av_parser_init(st->codec->codec_id);
1372 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1373 "%s, packets or times may be invalid.\n",
1374 avcodec_get_name(st->codec->codec_id));
1375 /* no parser available: just output the raw packets */
1376 st->need_parsing = AVSTREAM_PARSE_NONE;
1377 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1378 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1379 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1380 st->parser->flags |= PARSER_FLAG_ONCE;
1381 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1382 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1385 if (!st->need_parsing || !st->parser) {
1386 /* no parsing needed: we just output the packet as is */
1388 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
1389 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1390 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1391 ff_reduce_index(s, st->index);
1392 av_add_index_entry(st, pkt->pos, pkt->dts,
1393 0, 0, AVINDEX_KEYFRAME);
1396 } else if (st->discard < AVDISCARD_ALL) {
1397 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1401 av_free_packet(&cur_pkt);
1403 if (pkt->flags & AV_PKT_FLAG_KEY)
1404 st->skip_to_keyframe = 0;
1405 if (st->skip_to_keyframe) {
1406 av_free_packet(&cur_pkt);
1414 if (!got_packet && s->internal->parse_queue)
1415 ret = read_from_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end, pkt);
1418 AVStream *st = s->streams[pkt->stream_index];
1419 int discard_padding = 0;
1420 if (st->first_discard_sample && pkt->pts != AV_NOPTS_VALUE) {
1421 int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);
1422 int64_t sample = ts_to_samples(st, pts);
1423 int duration = ts_to_samples(st, pkt->duration);
1424 int64_t end_sample = sample + duration;
1425 if (duration > 0 && end_sample >= st->first_discard_sample &&
1426 sample < st->last_discard_sample)
1427 discard_padding = FFMIN(end_sample - st->first_discard_sample, duration);
1429 if (st->start_skip_samples && (pkt->pts == 0 || pkt->pts == RELATIVE_TS_BASE))
1430 st->skip_samples = st->start_skip_samples;
1431 if (st->skip_samples || discard_padding) {
1432 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1434 AV_WL32(p, st->skip_samples);
1435 AV_WL32(p + 4, discard_padding);
1436 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d / discard %d\n", st->skip_samples, discard_padding);
1438 st->skip_samples = 0;
1441 if (st->inject_global_side_data) {
1442 for (i = 0; i < st->nb_side_data; i++) {
1443 AVPacketSideData *src_sd = &st->side_data[i];
1446 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1449 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1451 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1455 memcpy(dst_data, src_sd->data, src_sd->size);
1457 st->inject_global_side_data = 0;
1460 if (!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
1461 av_packet_merge_side_data(pkt);
1464 av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);
1466 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
1467 av_dict_copy(&s->metadata, metadata, 0);
1468 av_dict_free(&metadata);
1469 av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);
1472 if (s->debug & FF_FDEBUG_TS)
1473 av_log(s, AV_LOG_DEBUG,
1474 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1475 "size=%d, duration=%"PRId64", flags=%d\n",
1477 av_ts2str(pkt->pts),
1478 av_ts2str(pkt->dts),
1479 pkt->size, pkt->duration, pkt->flags);
1484 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1486 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1492 ret = s->internal->packet_buffer
1493 ? read_from_packet_buffer(&s->internal->packet_buffer,
1494 &s->internal->packet_buffer_end, pkt)
1495 : read_frame_internal(s, pkt);
1502 AVPacketList *pktl = s->internal->packet_buffer;
1505 AVPacket *next_pkt = &pktl->pkt;
1507 if (next_pkt->dts != AV_NOPTS_VALUE) {
1508 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1509 // last dts seen for this stream. if any of packets following
1510 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1511 int64_t last_dts = next_pkt->dts;
1512 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1513 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1514 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {
1515 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
1517 next_pkt->pts = pktl->pkt.dts;
1519 if (last_dts != AV_NOPTS_VALUE) {
1520 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1521 last_dts = pktl->pkt.dts;
1526 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1527 // Fixing the last reference frame had none pts issue (For MXF etc).
1528 // We only do this when
1530 // 2. we are not able to resolve a pts value for current packet.
1531 // 3. the packets for this stream at the end of the files had valid dts.
1532 next_pkt->pts = last_dts + next_pkt->duration;
1534 pktl = s->internal->packet_buffer;
1537 /* read packet from packet buffer, if there is data */
1538 st = s->streams[next_pkt->stream_index];
1539 if (!(next_pkt->pts == AV_NOPTS_VALUE && st->discard < AVDISCARD_ALL &&
1540 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1541 ret = read_from_packet_buffer(&s->internal->packet_buffer,
1542 &s->internal->packet_buffer_end, pkt);
1547 ret = read_frame_internal(s, pkt);
1549 if (pktl && ret != AVERROR(EAGAIN)) {
1556 if (av_dup_packet(add_to_pktbuf(&s->internal->packet_buffer, pkt,
1557 &s->internal->packet_buffer_end)) < 0)
1558 return AVERROR(ENOMEM);
1563 st = s->streams[pkt->stream_index];
1564 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1565 ff_reduce_index(s, st->index);
1566 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1569 if (is_relative(pkt->dts))
1570 pkt->dts -= RELATIVE_TS_BASE;
1571 if (is_relative(pkt->pts))
1572 pkt->pts -= RELATIVE_TS_BASE;
1577 /* XXX: suppress the packet queue */
1578 static void flush_packet_queue(AVFormatContext *s)
1582 free_packet_buffer(&s->internal->parse_queue, &s->internal->parse_queue_end);
1583 free_packet_buffer(&s->internal->packet_buffer, &s->internal->packet_buffer_end);
1584 free_packet_buffer(&s->internal->raw_packet_buffer, &s->internal->raw_packet_buffer_end);
1586 s->internal->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1589 /*******************************************************/
1592 int av_find_default_stream_index(AVFormatContext *s)
1596 int best_stream = 0;
1597 int best_score = INT_MIN;
1599 if (s->nb_streams <= 0)
1601 for (i = 0; i < s->nb_streams; i++) {
1604 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1605 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
1607 if (st->codec->width && st->codec->height)
1611 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1612 if (st->codec->sample_rate)
1615 if (st->codec_info_nb_frames)
1618 if (st->discard != AVDISCARD_ALL)
1621 if (score > best_score) {
1629 /** Flush the frame reader. */
1630 void ff_read_frame_flush(AVFormatContext *s)
1635 flush_packet_queue(s);
1637 /* Reset read state for each stream. */
1638 for (i = 0; i < s->nb_streams; i++) {
1642 av_parser_close(st->parser);
1645 st->last_IP_pts = AV_NOPTS_VALUE;
1646 st->last_dts_for_order_check = AV_NOPTS_VALUE;
1647 if (st->first_dts == AV_NOPTS_VALUE)
1648 st->cur_dts = RELATIVE_TS_BASE;
1650 /* We set the current DTS to an unspecified origin. */
1651 st->cur_dts = AV_NOPTS_VALUE;
1653 st->probe_packets = MAX_PROBE_PACKETS;
1655 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1656 st->pts_buffer[j] = AV_NOPTS_VALUE;
1658 if (s->internal->inject_global_side_data)
1659 st->inject_global_side_data = 1;
1661 st->skip_samples = 0;
1665 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1669 for (i = 0; i < s->nb_streams; i++) {
1670 AVStream *st = s->streams[i];
1673 av_rescale(timestamp,
1674 st->time_base.den * (int64_t) ref_st->time_base.num,
1675 st->time_base.num * (int64_t) ref_st->time_base.den);
1679 void ff_reduce_index(AVFormatContext *s, int stream_index)
1681 AVStream *st = s->streams[stream_index];
1682 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1684 if ((unsigned) st->nb_index_entries >= max_entries) {
1686 for (i = 0; 2 * i < st->nb_index_entries; i++)
1687 st->index_entries[i] = st->index_entries[2 * i];
1688 st->nb_index_entries = i;
1692 int ff_add_index_entry(AVIndexEntry **index_entries,
1693 int *nb_index_entries,
1694 unsigned int *index_entries_allocated_size,
1695 int64_t pos, int64_t timestamp,
1696 int size, int distance, int flags)
1698 AVIndexEntry *entries, *ie;
1701 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1704 if (timestamp == AV_NOPTS_VALUE)
1705 return AVERROR(EINVAL);
1707 if (size < 0 || size > 0x3FFFFFFF)
1708 return AVERROR(EINVAL);
1710 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1711 timestamp -= RELATIVE_TS_BASE;
1713 entries = av_fast_realloc(*index_entries,
1714 index_entries_allocated_size,
1715 (*nb_index_entries + 1) *
1716 sizeof(AVIndexEntry));
1720 *index_entries = entries;
1722 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1723 timestamp, AVSEEK_FLAG_ANY);
1726 index = (*nb_index_entries)++;
1727 ie = &entries[index];
1728 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1730 ie = &entries[index];
1731 if (ie->timestamp != timestamp) {
1732 if (ie->timestamp <= timestamp)
1734 memmove(entries + index + 1, entries + index,
1735 sizeof(AVIndexEntry) * (*nb_index_entries - index));
1736 (*nb_index_entries)++;
1737 } else if (ie->pos == pos && distance < ie->min_distance)
1738 // do not reduce the distance
1739 distance = ie->min_distance;
1743 ie->timestamp = timestamp;
1744 ie->min_distance = distance;
1751 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1752 int size, int distance, int flags)
1754 timestamp = wrap_timestamp(st, timestamp);
1755 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1756 &st->index_entries_allocated_size, pos,
1757 timestamp, size, distance, flags);
1760 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1761 int64_t wanted_timestamp, int flags)
1769 // Optimize appending index entries at the end.
1770 if (b && entries[b - 1].timestamp < wanted_timestamp)
1775 timestamp = entries[m].timestamp;
1776 if (timestamp >= wanted_timestamp)
1778 if (timestamp <= wanted_timestamp)
1781 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1783 if (!(flags & AVSEEK_FLAG_ANY))
1784 while (m >= 0 && m < nb_entries &&
1785 !(entries[m].flags & AVINDEX_KEYFRAME))
1786 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1788 if (m == nb_entries)
1793 void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
1796 int64_t pos_delta = 0;
1798 //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable
1799 const char *proto = avio_find_protocol_name(s->filename);
1802 av_log(s, AV_LOG_INFO,
1803 "Protocol name not provided, cannot determine if input is local or "
1804 "a network protocol, buffers and access patterns cannot be configured "
1805 "optimally without knowing the protocol\n");
1808 if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))
1811 for (ist1 = 0; ist1 < s->nb_streams; ist1++) {
1812 AVStream *st1 = s->streams[ist1];
1813 for (ist2 = 0; ist2 < s->nb_streams; ist2++) {
1814 AVStream *st2 = s->streams[ist2];
1820 for (i1 = i2 = 0; i1 < st1->nb_index_entries; i1++) {
1821 AVIndexEntry *e1 = &st1->index_entries[i1];
1822 int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);
1824 skip = FFMAX(skip, e1->size);
1825 for (; i2 < st2->nb_index_entries; i2++) {
1826 AVIndexEntry *e2 = &st2->index_entries[i2];
1827 int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);
1828 if (e2_pts - e1_pts < time_tolerance)
1830 pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);
1838 /* XXX This could be adjusted depending on protocol*/
1839 if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {
1840 av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);
1841 ffio_set_buf_size(s->pb, pos_delta);
1842 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);
1845 if (skip < (1<<23)) {
1846 s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, skip);
1850 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1852 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1853 wanted_timestamp, flags);
1856 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
1857 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1859 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
1860 if (stream_index >= 0)
1861 ts = wrap_timestamp(s->streams[stream_index], ts);
1865 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1866 int64_t target_ts, int flags)
1868 AVInputFormat *avif = s->iformat;
1869 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1870 int64_t ts_min, ts_max, ts;
1875 if (stream_index < 0)
1878 av_log(s, AV_LOG_TRACE, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1881 ts_min = AV_NOPTS_VALUE;
1882 pos_limit = -1; // GCC falsely says it may be uninitialized.
1884 st = s->streams[stream_index];
1885 if (st->index_entries) {
1888 /* FIXME: Whole function must be checked for non-keyframe entries in
1889 * index case, especially read_timestamp(). */
1890 index = av_index_search_timestamp(st, target_ts,
1891 flags | AVSEEK_FLAG_BACKWARD);
1892 index = FFMAX(index, 0);
1893 e = &st->index_entries[index];
1895 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1897 ts_min = e->timestamp;
1898 av_log(s, AV_LOG_TRACE, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
1899 pos_min, av_ts2str(ts_min));
1901 av_assert1(index == 0);
1904 index = av_index_search_timestamp(st, target_ts,
1905 flags & ~AVSEEK_FLAG_BACKWARD);
1906 av_assert0(index < st->nb_index_entries);
1908 e = &st->index_entries[index];
1909 av_assert1(e->timestamp >= target_ts);
1911 ts_max = e->timestamp;
1912 pos_limit = pos_max - e->min_distance;
1913 av_log(s, AV_LOG_TRACE, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1914 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
1918 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1919 ts_min, ts_max, flags, &ts, avif->read_timestamp);
1924 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1927 ff_read_frame_flush(s);
1928 ff_update_cur_dts(s, st, ts);
1933 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
1934 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1936 int64_t step = 1024;
1937 int64_t limit, ts_max;
1938 int64_t filesize = avio_size(s->pb);
1939 int64_t pos_max = filesize - 1;
1942 pos_max = FFMAX(0, (pos_max) - step);
1943 ts_max = ff_read_timestamp(s, stream_index,
1944 &pos_max, limit, read_timestamp);
1946 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
1947 if (ts_max == AV_NOPTS_VALUE)
1951 int64_t tmp_pos = pos_max + 1;
1952 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
1953 &tmp_pos, INT64_MAX, read_timestamp);
1954 if (tmp_ts == AV_NOPTS_VALUE)
1956 av_assert0(tmp_pos > pos_max);
1959 if (tmp_pos >= filesize)
1971 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1972 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1973 int64_t ts_min, int64_t ts_max,
1974 int flags, int64_t *ts_ret,
1975 int64_t (*read_timestamp)(struct AVFormatContext *, int,
1976 int64_t *, int64_t))
1983 av_log(s, AV_LOG_TRACE, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1985 if (ts_min == AV_NOPTS_VALUE) {
1986 pos_min = s->internal->data_offset;
1987 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1988 if (ts_min == AV_NOPTS_VALUE)
1992 if (ts_min >= target_ts) {
1997 if (ts_max == AV_NOPTS_VALUE) {
1998 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2000 pos_limit = pos_max;
2003 if (ts_max <= target_ts) {
2008 av_assert0(ts_min < ts_max);
2011 while (pos_min < pos_limit) {
2012 av_log(s, AV_LOG_TRACE,
2013 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2014 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2015 av_assert0(pos_limit <= pos_max);
2017 if (no_change == 0) {
2018 int64_t approximate_keyframe_distance = pos_max - pos_limit;
2019 // interpolate position (better than dichotomy)
2020 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2022 pos_min - approximate_keyframe_distance;
2023 } else if (no_change == 1) {
2024 // bisection if interpolation did not change min / max pos last time
2025 pos = (pos_min + pos_limit) >> 1;
2027 /* linear search if bisection failed, can only happen if there
2028 * are very few or no keyframes between min/max */
2033 else if (pos > pos_limit)
2037 // May pass pos_limit instead of -1.
2038 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2043 av_log(s, AV_LOG_TRACE, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2044 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2045 pos_min, pos, pos_max,
2046 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2047 pos_limit, start_pos, no_change);
2048 if (ts == AV_NOPTS_VALUE) {
2049 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2052 if (target_ts <= ts) {
2053 pos_limit = start_pos - 1;
2057 if (target_ts >= ts) {
2063 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2064 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2067 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2069 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2070 av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2071 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2077 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2078 int64_t pos, int flags)
2080 int64_t pos_min, pos_max;
2082 pos_min = s->internal->data_offset;
2083 pos_max = avio_size(s->pb) - 1;
2087 else if (pos > pos_max)
2090 avio_seek(s->pb, pos, SEEK_SET);
2092 s->io_repositioned = 1;
2097 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2098 int64_t timestamp, int flags)
2105 st = s->streams[stream_index];
2107 index = av_index_search_timestamp(st, timestamp, flags);
2109 if (index < 0 && st->nb_index_entries &&
2110 timestamp < st->index_entries[0].timestamp)
2113 if (index < 0 || index == st->nb_index_entries - 1) {
2117 if (st->nb_index_entries) {
2118 av_assert0(st->index_entries);
2119 ie = &st->index_entries[st->nb_index_entries - 1];
2120 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2122 ff_update_cur_dts(s, st, ie->timestamp);
2124 if ((ret = avio_seek(s->pb, s->internal->data_offset, SEEK_SET)) < 0)
2130 read_status = av_read_frame(s, &pkt);
2131 } while (read_status == AVERROR(EAGAIN));
2132 if (read_status < 0)
2134 av_free_packet(&pkt);
2135 if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2136 if (pkt.flags & AV_PKT_FLAG_KEY)
2138 if (nonkey++ > 1000 && st->codec->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2139 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);
2144 index = av_index_search_timestamp(st, timestamp, flags);
2149 ff_read_frame_flush(s);
2150 if (s->iformat->read_seek)
2151 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2153 ie = &st->index_entries[index];
2154 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2156 ff_update_cur_dts(s, st, ie->timestamp);
2161 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2162 int64_t timestamp, int flags)
2167 if (flags & AVSEEK_FLAG_BYTE) {
2168 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2170 ff_read_frame_flush(s);
2171 return seek_frame_byte(s, stream_index, timestamp, flags);
2174 if (stream_index < 0) {
2175 stream_index = av_find_default_stream_index(s);
2176 if (stream_index < 0)
2179 st = s->streams[stream_index];
2180 /* timestamp for default must be expressed in AV_TIME_BASE units */
2181 timestamp = av_rescale(timestamp, st->time_base.den,
2182 AV_TIME_BASE * (int64_t) st->time_base.num);
2185 /* first, we try the format specific seek */
2186 if (s->iformat->read_seek) {
2187 ff_read_frame_flush(s);
2188 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2194 if (s->iformat->read_timestamp &&
2195 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2196 ff_read_frame_flush(s);
2197 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2198 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2199 ff_read_frame_flush(s);
2200 return seek_frame_generic(s, stream_index, timestamp, flags);
2205 int av_seek_frame(AVFormatContext *s, int stream_index,
2206 int64_t timestamp, int flags)
2210 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2211 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2212 if ((flags & AVSEEK_FLAG_BACKWARD))
2216 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2217 flags & ~AVSEEK_FLAG_BACKWARD);
2220 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2223 ret = avformat_queue_attached_pictures(s);
2228 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2229 int64_t ts, int64_t max_ts, int flags)
2231 if (min_ts > ts || max_ts < ts)
2233 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2234 return AVERROR(EINVAL);
2237 flags |= AVSEEK_FLAG_ANY;
2238 flags &= ~AVSEEK_FLAG_BACKWARD;
2240 if (s->iformat->read_seek2) {
2242 ff_read_frame_flush(s);
2244 if (stream_index == -1 && s->nb_streams == 1) {
2245 AVRational time_base = s->streams[0]->time_base;
2246 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2247 min_ts = av_rescale_rnd(min_ts, time_base.den,
2248 time_base.num * (int64_t)AV_TIME_BASE,
2249 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2250 max_ts = av_rescale_rnd(max_ts, time_base.den,
2251 time_base.num * (int64_t)AV_TIME_BASE,
2252 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2255 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2259 ret = avformat_queue_attached_pictures(s);
2263 if (s->iformat->read_timestamp) {
2264 // try to seek via read_timestamp()
2267 // Fall back on old API if new is not implemented but old is.
2268 // Note the old API has somewhat different semantics.
2269 if (s->iformat->read_seek || 1) {
2270 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2271 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2272 if (ret<0 && ts != min_ts && max_ts != ts) {
2273 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2275 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2280 // try some generic seek like seek_frame_generic() but with new ts semantics
2281 return -1; //unreachable
2284 int avformat_flush(AVFormatContext *s)
2286 ff_read_frame_flush(s);
2290 /*******************************************************/
2293 * Return TRUE if the stream has accurate duration in any stream.
2295 * @return TRUE if the stream has accurate duration for at least one component.
2297 static int has_duration(AVFormatContext *ic)
2302 for (i = 0; i < ic->nb_streams; i++) {
2303 st = ic->streams[i];
2304 if (st->duration != AV_NOPTS_VALUE)
2307 if (ic->duration != AV_NOPTS_VALUE)
2313 * Estimate the stream timings from the one of each components.
2315 * Also computes the global bitrate if possible.
2317 static void update_stream_timings(AVFormatContext *ic)
2319 int64_t start_time, start_time1, start_time_text, end_time, end_time1;
2320 int64_t duration, duration1, filesize;
2325 start_time = INT64_MAX;
2326 start_time_text = INT64_MAX;
2327 end_time = INT64_MIN;
2328 duration = INT64_MIN;
2329 for (i = 0; i < ic->nb_streams; i++) {
2330 st = ic->streams[i];
2331 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2332 start_time1 = av_rescale_q(st->start_time, st->time_base,
2334 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA) {
2335 if (start_time1 < start_time_text)
2336 start_time_text = start_time1;
2338 start_time = FFMIN(start_time, start_time1);
2339 end_time1 = AV_NOPTS_VALUE;
2340 if (st->duration != AV_NOPTS_VALUE) {
2341 end_time1 = start_time1 +
2342 av_rescale_q(st->duration, st->time_base,
2344 end_time = FFMAX(end_time, end_time1);
2346 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2347 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2348 p->start_time = start_time1;
2349 if (p->end_time < end_time1)
2350 p->end_time = end_time1;
2353 if (st->duration != AV_NOPTS_VALUE) {
2354 duration1 = av_rescale_q(st->duration, st->time_base,
2356 duration = FFMAX(duration, duration1);
2359 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
2360 start_time = start_time_text;
2361 else if (start_time > start_time_text)
2362 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2364 if (start_time != INT64_MAX) {
2365 ic->start_time = start_time;
2366 if (end_time != INT64_MIN) {
2367 if (ic->nb_programs) {
2368 for (i = 0; i < ic->nb_programs; i++) {
2369 p = ic->programs[i];
2370 if (p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time)
2371 duration = FFMAX(duration, p->end_time - p->start_time);
2374 duration = FFMAX(duration, end_time - start_time);
2377 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2378 ic->duration = duration;
2380 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
2381 /* compute the bitrate */
2382 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2383 (double) ic->duration;
2384 if (bitrate >= 0 && bitrate <= INT64_MAX)
2385 ic->bit_rate = bitrate;
2389 static void fill_all_stream_timings(AVFormatContext *ic)
2394 update_stream_timings(ic);
2395 for (i = 0; i < ic->nb_streams; i++) {
2396 st = ic->streams[i];
2397 if (st->start_time == AV_NOPTS_VALUE) {
2398 if (ic->start_time != AV_NOPTS_VALUE)
2399 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2401 if (ic->duration != AV_NOPTS_VALUE)
2402 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2408 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2410 int64_t filesize, duration;
2411 int i, show_warning = 0;
2414 /* if bit_rate is already set, we believe it */
2415 if (ic->bit_rate <= 0) {
2417 for (i = 0; i < ic->nb_streams; i++) {
2418 st = ic->streams[i];
2419 if (st->codec->bit_rate > 0) {
2420 if (INT_MAX - st->codec->bit_rate < bit_rate) {
2424 bit_rate += st->codec->bit_rate;
2425 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->codec_info_nb_frames > 1) {
2426 // If we have a videostream with packets but without a bitrate
2427 // then consider the sum not known
2432 ic->bit_rate = bit_rate;
2435 /* if duration is already set, we believe it */
2436 if (ic->duration == AV_NOPTS_VALUE &&
2437 ic->bit_rate != 0) {
2438 filesize = ic->pb ? avio_size(ic->pb) : 0;
2439 if (filesize > ic->internal->data_offset) {
2440 filesize -= ic->internal->data_offset;
2441 for (i = 0; i < ic->nb_streams; i++) {
2442 st = ic->streams[i];
2443 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2444 && st->duration == AV_NOPTS_VALUE) {
2445 duration = av_rescale(8 * filesize, st->time_base.den,
2447 (int64_t) st->time_base.num);
2448 st->duration = duration;
2455 av_log(ic, AV_LOG_WARNING,
2456 "Estimating duration from bitrate, this may be inaccurate\n");
2459 #define DURATION_MAX_READ_SIZE 250000LL
2460 #define DURATION_MAX_RETRY 4
2462 /* only usable for MPEG-PS streams */
2463 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2465 AVPacket pkt1, *pkt = &pkt1;
2467 int num, den, read_size, i, ret;
2468 int found_duration = 0;
2470 int64_t filesize, offset, duration;
2473 /* flush packet queue */
2474 flush_packet_queue(ic);
2476 for (i = 0; i < ic->nb_streams; i++) {
2477 st = ic->streams[i];
2478 if (st->start_time == AV_NOPTS_VALUE &&
2479 st->first_dts == AV_NOPTS_VALUE &&
2480 st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN)
2481 av_log(st->codec, AV_LOG_WARNING,
2482 "start time for stream %d is not set in estimate_timings_from_pts\n", i);
2485 av_parser_close(st->parser);
2490 av_opt_set(ic, "skip_changes", "1", AV_OPT_SEARCH_CHILDREN);
2491 /* estimate the end time (duration) */
2492 /* XXX: may need to support wrapping */
2493 filesize = ic->pb ? avio_size(ic->pb) : 0;
2495 is_end = found_duration;
2496 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2500 avio_seek(ic->pb, offset, SEEK_SET);
2503 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2507 ret = ff_read_packet(ic, pkt);
2508 } while (ret == AVERROR(EAGAIN));
2511 read_size += pkt->size;
2512 st = ic->streams[pkt->stream_index];
2513 if (pkt->pts != AV_NOPTS_VALUE &&
2514 (st->start_time != AV_NOPTS_VALUE ||
2515 st->first_dts != AV_NOPTS_VALUE)) {
2516 if (pkt->duration == 0) {
2517 ff_compute_frame_duration(ic, &num, &den, st, st->parser, pkt);
2519 pkt->duration = av_rescale_rnd(1,
2520 num * (int64_t) st->time_base.den,
2521 den * (int64_t) st->time_base.num,
2525 duration = pkt->pts + pkt->duration;
2527 if (st->start_time != AV_NOPTS_VALUE)
2528 duration -= st->start_time;
2530 duration -= st->first_dts;
2532 if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2533 (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2534 st->duration = duration;
2535 st->info->last_duration = duration;
2538 av_free_packet(pkt);
2541 /* check if all audio/video streams have valid duration */
2544 for (i = 0; i < ic->nb_streams; i++) {
2545 st = ic->streams[i];
2546 switch (st->codec->codec_type) {
2547 case AVMEDIA_TYPE_VIDEO:
2548 case AVMEDIA_TYPE_AUDIO:
2549 if (st->duration == AV_NOPTS_VALUE)
2556 ++retry <= DURATION_MAX_RETRY);
2558 av_opt_set(ic, "skip_changes", "0", AV_OPT_SEARCH_CHILDREN);
2560 /* warn about audio/video streams which duration could not be estimated */
2561 for (i = 0; i < ic->nb_streams; i++) {
2562 st = ic->streams[i];
2563 if (st->duration == AV_NOPTS_VALUE) {
2564 switch (st->codec->codec_type) {
2565 case AVMEDIA_TYPE_VIDEO:
2566 case AVMEDIA_TYPE_AUDIO:
2567 if (st->start_time != AV_NOPTS_VALUE || st->first_dts != AV_NOPTS_VALUE) {
2568 av_log(ic, AV_LOG_DEBUG, "stream %d : no PTS found at end of file, duration not set\n", i);
2570 av_log(ic, AV_LOG_DEBUG, "stream %d : no TS found at start of file, duration not set\n", i);
2574 fill_all_stream_timings(ic);
2576 avio_seek(ic->pb, old_offset, SEEK_SET);
2577 for (i = 0; i < ic->nb_streams; i++) {
2580 st = ic->streams[i];
2581 st->cur_dts = st->first_dts;
2582 st->last_IP_pts = AV_NOPTS_VALUE;
2583 st->last_dts_for_order_check = AV_NOPTS_VALUE;
2584 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2585 st->pts_buffer[j] = AV_NOPTS_VALUE;
2589 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2593 /* get the file size, if possible */
2594 if (ic->iformat->flags & AVFMT_NOFILE) {
2597 file_size = avio_size(ic->pb);
2598 file_size = FFMAX(0, file_size);
2601 if ((!strcmp(ic->iformat->name, "mpeg") ||
2602 !strcmp(ic->iformat->name, "mpegts")) &&
2603 file_size && ic->pb->seekable) {
2604 /* get accurate estimate from the PTSes */
2605 estimate_timings_from_pts(ic, old_offset);
2606 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2607 } else if (has_duration(ic)) {
2608 /* at least one component has timings - we use them for all
2610 fill_all_stream_timings(ic);
2611 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2613 /* less precise: use bitrate info */
2614 estimate_timings_from_bit_rate(ic);
2615 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2617 update_stream_timings(ic);
2621 AVStream av_unused *st;
2622 for (i = 0; i < ic->nb_streams; i++) {
2623 st = ic->streams[i];
2624 av_log(ic, AV_LOG_TRACE, "%d: start_time: %0.3f duration: %0.3f\n", i,
2625 (double) st->start_time / AV_TIME_BASE,
2626 (double) st->duration / AV_TIME_BASE);
2628 av_log(ic, AV_LOG_TRACE,
2629 "stream: start_time: %0.3f duration: %0.3f bitrate=%"PRId64" kb/s\n",
2630 (double) ic->start_time / AV_TIME_BASE,
2631 (double) ic->duration / AV_TIME_BASE,
2632 (int64_t)ic->bit_rate / 1000);
2636 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2638 AVCodecContext *avctx = st->codec;
2640 #define FAIL(errmsg) do { \
2642 *errmsg_ptr = errmsg; \
2646 if ( avctx->codec_id == AV_CODEC_ID_NONE
2647 && avctx->codec_type != AVMEDIA_TYPE_DATA)
2648 FAIL("unknown codec");
2649 switch (avctx->codec_type) {
2650 case AVMEDIA_TYPE_AUDIO:
2651 if (!avctx->frame_size && determinable_frame_size(avctx))
2652 FAIL("unspecified frame size");
2653 if (st->info->found_decoder >= 0 &&
2654 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2655 FAIL("unspecified sample format");
2656 if (!avctx->sample_rate)
2657 FAIL("unspecified sample rate");
2658 if (!avctx->channels)
2659 FAIL("unspecified number of channels");
2660 if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2661 FAIL("no decodable DTS frames");
2663 case AVMEDIA_TYPE_VIDEO:
2665 FAIL("unspecified size");
2666 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2667 FAIL("unspecified pixel format");
2668 if (st->codec->codec_id == AV_CODEC_ID_RV30 || st->codec->codec_id == AV_CODEC_ID_RV40)
2669 if (!st->sample_aspect_ratio.num && !st->codec->sample_aspect_ratio.num && !st->codec_info_nb_frames)
2670 FAIL("no frame in rv30/40 and no sar");
2672 case AVMEDIA_TYPE_SUBTITLE:
2673 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2674 FAIL("unspecified size");
2676 case AVMEDIA_TYPE_DATA:
2677 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2683 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2684 static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
2685 AVDictionary **options)
2687 const AVCodec *codec;
2688 int got_picture = 1, ret = 0;
2689 AVFrame *frame = av_frame_alloc();
2690 AVSubtitle subtitle;
2691 AVPacket pkt = *avpkt;
2694 return AVERROR(ENOMEM);
2696 if (!avcodec_is_open(st->codec) &&
2697 st->info->found_decoder <= 0 &&
2698 (st->codec->codec_id != -st->info->found_decoder || !st->codec->codec_id)) {
2699 AVDictionary *thread_opt = NULL;
2701 codec = find_decoder(s, st, st->codec->codec_id);
2704 st->info->found_decoder = -st->codec->codec_id;
2709 /* Force thread count to 1 since the H.264 decoder will not extract
2710 * SPS and PPS to extradata during multi-threaded decoding. */
2711 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2712 if (s->codec_whitelist)
2713 av_dict_set(options ? options : &thread_opt, "codec_whitelist", s->codec_whitelist, 0);
2714 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2716 av_dict_free(&thread_opt);
2718 st->info->found_decoder = -st->codec->codec_id;
2721 st->info->found_decoder = 1;
2722 } else if (!st->info->found_decoder)
2723 st->info->found_decoder = 1;
2725 if (st->info->found_decoder < 0) {
2730 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2732 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
2733 (!st->codec_info_nb_frames &&
2734 (st->codec->codec->capabilities & AV_CODEC_CAP_CHANNEL_CONF)))) {
2736 switch (st->codec->codec_type) {
2737 case AVMEDIA_TYPE_VIDEO:
2738 ret = avcodec_decode_video2(st->codec, frame,
2739 &got_picture, &pkt);
2741 case AVMEDIA_TYPE_AUDIO:
2742 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2744 case AVMEDIA_TYPE_SUBTITLE:
2745 ret = avcodec_decode_subtitle2(st->codec, &subtitle,
2746 &got_picture, &pkt);
2754 st->nb_decoded_frames++;
2761 if (!pkt.data && !got_picture)
2765 av_frame_free(&frame);
2769 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2771 while (tags->id != AV_CODEC_ID_NONE) {
2779 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2782 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2783 if (tag == tags[i].tag)
2785 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2786 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2788 return AV_CODEC_ID_NONE;
2791 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2796 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2798 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2800 return AV_CODEC_ID_NONE;
2805 if (sflags & (1 << (bps - 1))) {
2808 return AV_CODEC_ID_PCM_S8;
2810 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2812 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2814 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2816 return AV_CODEC_ID_NONE;
2821 return AV_CODEC_ID_PCM_U8;
2823 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2825 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2827 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2829 return AV_CODEC_ID_NONE;
2835 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2838 if (!av_codec_get_tag2(tags, id, &tag))
2843 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
2847 for (i = 0; tags && tags[i]; i++) {
2848 const AVCodecTag *codec_tags = tags[i];
2849 while (codec_tags->id != AV_CODEC_ID_NONE) {
2850 if (codec_tags->id == id) {
2851 *tag = codec_tags->tag;
2860 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2863 for (i = 0; tags && tags[i]; i++) {
2864 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2865 if (id != AV_CODEC_ID_NONE)
2868 return AV_CODEC_ID_NONE;
2871 static void compute_chapters_end(AVFormatContext *s)
2874 int64_t max_time = s->duration +
2875 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2877 for (i = 0; i < s->nb_chapters; i++)
2878 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2879 AVChapter *ch = s->chapters[i];
2880 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2884 for (j = 0; j < s->nb_chapters; j++) {
2885 AVChapter *ch1 = s->chapters[j];
2886 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2888 if (j != i && next_start > ch->start && next_start < end)
2891 ch->end = (end == INT64_MAX) ? ch->start : end;
2895 static int get_std_framerate(int i)
2898 return (i + 1) * 1001;
2902 return ((const int[]) { 40, 48, 50, 60, 80, 120, 240})[i] * 1001 * 12;
2906 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i] * 1000 * 12;
2909 /* Is the time base unreliable?
2910 * This is a heuristic to balance between quick acceptance of the values in
2911 * the headers vs. some extra checks.
2912 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2913 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2914 * And there are "variable" fps files this needs to detect as well. */
2915 static int tb_unreliable(AVCodecContext *c)
2917 if (c->time_base.den >= 101LL * c->time_base.num ||
2918 c->time_base.den < 5LL * c->time_base.num ||
2919 // c->codec_tag == AV_RL32("DIVX") ||
2920 // c->codec_tag == AV_RL32("XVID") ||
2921 c->codec_tag == AV_RL32("mp4v") ||
2922 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
2923 c->codec_id == AV_CODEC_ID_GIF ||
2924 c->codec_id == AV_CODEC_ID_HEVC ||
2925 c->codec_id == AV_CODEC_ID_H264)
2930 int ff_alloc_extradata(AVCodecContext *avctx, int size)
2934 if (size < 0 || size >= INT32_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
2935 avctx->extradata = NULL;
2936 avctx->extradata_size = 0;
2937 return AVERROR(EINVAL);
2939 avctx->extradata = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
2940 if (avctx->extradata) {
2941 memset(avctx->extradata + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2942 avctx->extradata_size = size;
2945 avctx->extradata_size = 0;
2946 ret = AVERROR(ENOMEM);
2951 int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
2953 int ret = ff_alloc_extradata(avctx, size);
2956 ret = avio_read(pb, avctx->extradata, size);
2958 av_freep(&avctx->extradata);
2959 avctx->extradata_size = 0;
2960 av_log(avctx, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
2961 return ret < 0 ? ret : AVERROR_INVALIDDATA;
2967 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
2970 int64_t last = st->info->last_dts;
2972 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
2973 && ts - (uint64_t)last < INT64_MAX) {
2974 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
2975 int64_t duration = ts - last;
2977 if (!st->info->duration_error)
2978 st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);
2979 if (!st->info->duration_error)
2980 return AVERROR(ENOMEM);
2982 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2983 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2984 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2985 if (st->info->duration_error[0][1][i] < 1e10) {
2986 int framerate = get_std_framerate(i);
2987 double sdts = dts*framerate/(1001*12);
2988 for (j= 0; j<2; j++) {
2989 int64_t ticks = llrint(sdts+j*0.5);
2990 double error= sdts - ticks + j*0.5;
2991 st->info->duration_error[j][0][i] += error;
2992 st->info->duration_error[j][1][i] += error*error;
2996 st->info->duration_count++;
2997 st->info->rfps_duration_sum += duration;
2999 if (st->info->duration_count % 10 == 0) {
3000 int n = st->info->duration_count;
3001 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
3002 if (st->info->duration_error[0][1][i] < 1e10) {
3003 double a0 = st->info->duration_error[0][0][i] / n;
3004 double error0 = st->info->duration_error[0][1][i] / n - a0*a0;
3005 double a1 = st->info->duration_error[1][0][i] / n;
3006 double error1 = st->info->duration_error[1][1][i] / n - a1*a1;
3007 if (error0 > 0.04 && error1 > 0.04) {
3008 st->info->duration_error[0][1][i] = 2e10;
3009 st->info->duration_error[1][1][i] = 2e10;
3015 // ignore the first 4 values, they might have some random jitter
3016 if (st->info->duration_count > 3 && is_relative(ts) == is_relative(last))
3017 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
3019 if (ts != AV_NOPTS_VALUE)
3020 st->info->last_dts = ts;
3025 void ff_rfps_calculate(AVFormatContext *ic)
3029 for (i = 0; i < ic->nb_streams; i++) {
3030 AVStream *st = ic->streams[i];
3032 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
3034 // the check for tb_unreliable() is not completely correct, since this is not about handling
3035 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
3036 // ipmovie.c produces.
3037 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)
3038 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);
3039 if (st->info->duration_count>1 && !st->r_frame_rate.num
3040 && tb_unreliable(st->codec)) {
3042 double best_error= 0.01;
3043 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3045 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3048 if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
3050 if (!st->info->codec_info_duration && get_std_framerate(j) < 1001*12)
3053 if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3056 for (k= 0; k<2; k++) {
3057 int n = st->info->duration_count;
3058 double a= st->info->duration_error[k][0][j] / n;
3059 double error= st->info->duration_error[k][1][j]/n - a*a;
3061 if (error < best_error && best_error> 0.000000001) {
3063 num = get_std_framerate(j);
3066 av_log(ic, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3069 // do not increase frame rate by more than 1 % in order to match a standard rate.
3070 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3071 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3073 if ( !st->avg_frame_rate.num
3074 && st->r_frame_rate.num && st->info->rfps_duration_sum
3075 && st->info->codec_info_duration <= 0
3076 && st->info->duration_count > 2
3077 && 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
3079 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3080 st->avg_frame_rate = st->r_frame_rate;
3083 av_freep(&st->info->duration_error);
3084 st->info->last_dts = AV_NOPTS_VALUE;
3085 st->info->duration_count = 0;
3086 st->info->rfps_duration_sum = 0;
3090 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3092 int i, count, ret = 0, j;
3095 AVPacket pkt1, *pkt;
3096 int64_t old_offset = avio_tell(ic->pb);
3097 // new streams might appear, no options for those
3098 int orig_nb_streams = ic->nb_streams;
3100 int64_t max_analyze_duration = ic->max_analyze_duration;
3101 int64_t max_stream_analyze_duration;
3102 int64_t max_subtitle_analyze_duration;
3103 int64_t probesize = ic->probesize;
3105 flush_codecs = probesize > 0;
3107 av_opt_set(ic, "skip_clear", "1", AV_OPT_SEARCH_CHILDREN);
3109 max_stream_analyze_duration = max_analyze_duration;
3110 max_subtitle_analyze_duration = max_analyze_duration;
3111 if (!max_analyze_duration) {
3112 max_stream_analyze_duration =
3113 max_analyze_duration = 5*AV_TIME_BASE;
3114 max_subtitle_analyze_duration = 30*AV_TIME_BASE;
3115 if (!strcmp(ic->iformat->name, "flv"))
3116 max_stream_analyze_duration = 90*AV_TIME_BASE;
3120 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d\n",
3121 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count);
3123 for (i = 0; i < ic->nb_streams; i++) {
3124 const AVCodec *codec;
3125 AVDictionary *thread_opt = NULL;
3126 st = ic->streams[i];
3128 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3129 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3130 /* if (!st->time_base.num)
3132 if (!st->codec->time_base.num)
3133 st->codec->time_base = st->time_base;
3135 // only for the split stuff
3136 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
3137 st->parser = av_parser_init(st->codec->codec_id);
3139 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3140 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3141 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3142 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3144 } else if (st->need_parsing) {
3145 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3146 "%s, packets or times may be invalid.\n",
3147 avcodec_get_name(st->codec->codec_id));
3150 codec = find_decoder(ic, st, st->codec->codec_id);
3152 /* Force thread count to 1 since the H.264 decoder will not extract
3153 * SPS and PPS to extradata during multi-threaded decoding. */
3154 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3156 if (ic->codec_whitelist)
3157 av_dict_set(options ? &options[i] : &thread_opt, "codec_whitelist", ic->codec_whitelist, 0);
3159 /* Ensure that subtitle_header is properly set. */
3160 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
3161 && codec && !st->codec->codec) {
3162 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3163 av_log(ic, AV_LOG_WARNING,
3164 "Failed to open codec in av_find_stream_info\n");
3167 // Try to just open decoders, in case this is enough to get parameters.
3168 if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3169 if (codec && !st->codec->codec)
3170 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3171 av_log(ic, AV_LOG_WARNING,
3172 "Failed to open codec in av_find_stream_info\n");
3175 av_dict_free(&thread_opt);
3178 for (i = 0; i < ic->nb_streams; i++) {
3179 #if FF_API_R_FRAME_RATE
3180 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3182 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
3183 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
3189 int analyzed_all_streams;
3190 if (ff_check_interrupt(&ic->interrupt_callback)) {
3192 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3196 /* check if one codec still needs to be handled */
3197 for (i = 0; i < ic->nb_streams; i++) {
3198 int fps_analyze_framecount = 20;
3200 st = ic->streams[i];
3201 if (!has_codec_parameters(st, NULL))
3203 /* If the timebase is coarse (like the usual millisecond precision
3204 * of mkv), we need to analyze more frames to reliably arrive at
3205 * the correct fps. */
3206 if (av_q2d(st->time_base) > 0.0005)
3207 fps_analyze_framecount *= 2;
3208 if (!tb_unreliable(st->codec))
3209 fps_analyze_framecount = 0;
3210 if (ic->fps_probe_size >= 0)
3211 fps_analyze_framecount = ic->fps_probe_size;
3212 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3213 fps_analyze_framecount = 0;
3214 /* variable fps and no guess at the real fps */
3215 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3216 st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3217 int count = (ic->iformat->flags & AVFMT_NOTIMESTAMPS) ?
3218 st->info->codec_info_duration_fields/2 :
3219 st->info->duration_count;
3220 if (count < fps_analyze_framecount)
3223 if (st->parser && st->parser->parser->split &&
3224 !st->codec->extradata)
3226 if (st->first_dts == AV_NOPTS_VALUE &&
3227 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
3228 st->codec_info_nb_frames < ic->max_ts_probe &&
3229 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3230 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
3233 analyzed_all_streams = 0;
3234 if (i == ic->nb_streams) {
3235 analyzed_all_streams = 1;
3236 /* NOTE: If the format has no header, then we need to read some
3237 * packets to get most of the streams, so we cannot stop here. */
3238 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3239 /* If we found the info for all the codecs, we can stop. */
3241 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3246 /* We did not get all the codec info, but we read too much data. */
3247 if (read_size >= probesize) {
3249 av_log(ic, AV_LOG_DEBUG,
3250 "Probe buffer size limit of %"PRId64" bytes reached\n", probesize);
3251 for (i = 0; i < ic->nb_streams; i++)
3252 if (!ic->streams[i]->r_frame_rate.num &&
3253 ic->streams[i]->info->duration_count <= 1 &&
3254 ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3255 strcmp(ic->iformat->name, "image2"))
3256 av_log(ic, AV_LOG_WARNING,
3257 "Stream #%d: not enough frames to estimate rate; "
3258 "consider increasing probesize\n", i);
3262 /* NOTE: A new stream can be added there if no header in file
3263 * (AVFMTCTX_NOHEADER). */
3264 ret = read_frame_internal(ic, &pkt1);
3265 if (ret == AVERROR(EAGAIN))
3273 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3274 free_packet_buffer(&ic->internal->packet_buffer,
3275 &ic->internal->packet_buffer_end);
3277 pkt = add_to_pktbuf(&ic->internal->packet_buffer, &pkt1,
3278 &ic->internal->packet_buffer_end);
3280 ret = AVERROR(ENOMEM);
3281 goto find_stream_info_err;
3283 if ((ret = av_dup_packet(pkt)) < 0)
3284 goto find_stream_info_err;
3287 st = ic->streams[pkt->stream_index];
3288 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3289 read_size += pkt->size;
3291 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3292 /* check for non-increasing dts */
3293 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3294 st->info->fps_last_dts >= pkt->dts) {
3295 av_log(ic, AV_LOG_DEBUG,
3296 "Non-increasing DTS in stream %d: packet %d with DTS "
3297 "%"PRId64", packet %d with DTS %"PRId64"\n",
3298 st->index, st->info->fps_last_dts_idx,
3299 st->info->fps_last_dts, st->codec_info_nb_frames,
3301 st->info->fps_first_dts =
3302 st->info->fps_last_dts = AV_NOPTS_VALUE;
3304 /* Check for a discontinuity in dts. If the difference in dts
3305 * is more than 1000 times the average packet duration in the
3306 * sequence, we treat it as a discontinuity. */
3307 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3308 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
3309 (pkt->dts - st->info->fps_last_dts) / 1000 >
3310 (st->info->fps_last_dts - st->info->fps_first_dts) /
3311 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
3312 av_log(ic, AV_LOG_WARNING,
3313 "DTS discontinuity in stream %d: packet %d with DTS "
3314 "%"PRId64", packet %d with DTS %"PRId64"\n",
3315 st->index, st->info->fps_last_dts_idx,
3316 st->info->fps_last_dts, st->codec_info_nb_frames,
3318 st->info->fps_first_dts =
3319 st->info->fps_last_dts = AV_NOPTS_VALUE;
3322 /* update stored dts values */
3323 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
3324 st->info->fps_first_dts = pkt->dts;
3325 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
3327 st->info->fps_last_dts = pkt->dts;
3328 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
3330 if (st->codec_info_nb_frames>1) {
3334 if (st->time_base.den > 0)
3335 t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3336 if (st->avg_frame_rate.num > 0)
3337 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3340 && st->codec_info_nb_frames>30
3341 && st->info->fps_first_dts != AV_NOPTS_VALUE
3342 && st->info->fps_last_dts != AV_NOPTS_VALUE)
3343 t = FFMAX(t, av_rescale_q(st->info->fps_last_dts - st->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));
3345 if (analyzed_all_streams) limit = max_analyze_duration;
3346 else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) limit = max_subtitle_analyze_duration;
3347 else limit = max_stream_analyze_duration;
3350 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %"PRId64" reached at %"PRId64" microseconds st:%d\n",
3352 t, pkt->stream_index);
3353 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3354 av_packet_unref(pkt);
3357 if (pkt->duration) {
3358 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE && pkt->pts != AV_NOPTS_VALUE && pkt->pts >= st->start_time) {
3359 st->info->codec_info_duration = FFMIN(pkt->pts - st->start_time, st->info->codec_info_duration + pkt->duration);
3361 st->info->codec_info_duration += pkt->duration;
3362 st->info->codec_info_duration_fields += st->parser && st->need_parsing && st->codec->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3365 #if FF_API_R_FRAME_RATE
3366 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3367 ff_rfps_add_frame(ic, st, pkt->dts);
3369 if (st->parser && st->parser->parser->split && !st->codec->extradata) {
3370 int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
3371 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
3372 if (ff_alloc_extradata(st->codec, i))
3373 return AVERROR(ENOMEM);
3374 memcpy(st->codec->extradata, pkt->data,
3375 st->codec->extradata_size);
3379 /* If still no information, we try to open the codec and to
3380 * decompress the frame. We try to avoid that in most cases as
3381 * it takes longer and uses more memory. For MPEG-4, we need to
3382 * decompress for QuickTime.
3384 * If AV_CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3385 * least one frame of codec data, this makes sure the codec initializes
3386 * the channel configuration and does not only trust the values from
3388 try_decode_frame(ic, st, pkt,
3389 (options && i < orig_nb_streams) ? &options[i] : NULL);
3391 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3392 av_packet_unref(pkt);
3394 st->codec_info_nb_frames++;
3399 AVPacket empty_pkt = { 0 };
3401 av_init_packet(&empty_pkt);
3403 for (i = 0; i < ic->nb_streams; i++) {
3405 st = ic->streams[i];
3407 /* flush the decoders */
3408 if (st->info->found_decoder == 1) {
3410 err = try_decode_frame(ic, st, &empty_pkt,
3411 (options && i < orig_nb_streams)
3412 ? &options[i] : NULL);
3413 } while (err > 0 && !has_codec_parameters(st, NULL));
3416 av_log(ic, AV_LOG_INFO,
3417 "decoding for stream %d failed\n", st->index);
3423 // close codecs which were opened in try_decode_frame()
3424 for (i = 0; i < ic->nb_streams; i++) {
3425 st = ic->streams[i];
3426 avcodec_close(st->codec);
3429 ff_rfps_calculate(ic);
3431 for (i = 0; i < ic->nb_streams; i++) {
3432 st = ic->streams[i];
3433 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3434 if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample) {
3435 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
3436 if (avpriv_find_pix_fmt(avpriv_get_raw_pix_fmt_tags(), tag) == st->codec->pix_fmt)
3437 st->codec->codec_tag= tag;
3440 /* estimate average framerate if not set by demuxer */
3441 if (st->info->codec_info_duration_fields &&
3442 !st->avg_frame_rate.num &&
3443 st->info->codec_info_duration) {
3445 double best_error = 0.01;
3447 if (st->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3448 st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3449 st->info->codec_info_duration < 0)
3451 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3452 st->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3453 st->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3455 /* Round guessed framerate to a "standard" framerate if it's
3456 * within 1% of the original estimate. */
3457 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3458 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3459 double error = fabs(av_q2d(st->avg_frame_rate) /
3460 av_q2d(std_fps) - 1);
3462 if (error < best_error) {
3464 best_fps = std_fps.num;
3468 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3469 best_fps, 12 * 1001, INT_MAX);
3472 if (!st->r_frame_rate.num) {
3473 if ( st->codec->time_base.den * (int64_t) st->time_base.num
3474 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t) st->time_base.den) {
3475 st->r_frame_rate.num = st->codec->time_base.den;
3476 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
3478 st->r_frame_rate.num = st->time_base.den;
3479 st->r_frame_rate.den = st->time_base.num;
3482 if (st->display_aspect_ratio.num && st->display_aspect_ratio.den) {
3483 AVRational hw_ratio = { st->codec->height, st->codec->width };
3484 st->sample_aspect_ratio = av_mul_q(st->display_aspect_ratio,
3487 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3488 if (!st->codec->bits_per_coded_sample)
3489 st->codec->bits_per_coded_sample =
3490 av_get_bits_per_sample(st->codec->codec_id);
3491 // set stream disposition based on audio service type
3492 switch (st->codec->audio_service_type) {
3493 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
3494 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
3496 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
3497 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
3499 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
3500 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
3502 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
3503 st->disposition = AV_DISPOSITION_COMMENT;
3505 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
3506 st->disposition = AV_DISPOSITION_KARAOKE;
3513 estimate_timings(ic, old_offset);
3515 av_opt_set(ic, "skip_clear", "0", AV_OPT_SEARCH_CHILDREN);
3517 if (ret >= 0 && ic->nb_streams)
3518 /* We could not have all the codec parameters before EOF. */
3520 for (i = 0; i < ic->nb_streams; i++) {
3522 st = ic->streams[i];
3523 if (!has_codec_parameters(st, &errmsg)) {
3525 avcodec_string(buf, sizeof(buf), st->codec, 0);
3526 av_log(ic, AV_LOG_WARNING,
3527 "Could not find codec parameters for stream %d (%s): %s\n"
3528 "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",
3535 compute_chapters_end(ic);
3537 find_stream_info_err:
3538 for (i = 0; i < ic->nb_streams; i++) {
3539 st = ic->streams[i];
3540 if (ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3541 ic->streams[i]->codec->thread_count = 0;
3543 av_freep(&st->info->duration_error);
3544 av_freep(&ic->streams[i]->info);
3547 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
3548 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
3552 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
3556 for (i = 0; i < ic->nb_programs; i++) {
3557 if (ic->programs[i] == last) {
3561 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
3562 if (ic->programs[i]->stream_index[j] == s)
3563 return ic->programs[i];
3569 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
3570 int wanted_stream_nb, int related_stream,
3571 AVCodec **decoder_ret, int flags)
3573 int i, nb_streams = ic->nb_streams;
3574 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
3575 unsigned *program = NULL;
3576 const AVCodec *decoder = NULL, *best_decoder = NULL;
3578 if (related_stream >= 0 && wanted_stream_nb < 0) {
3579 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
3581 program = p->stream_index;
3582 nb_streams = p->nb_stream_indexes;
3585 for (i = 0; i < nb_streams; i++) {
3586 int real_stream_index = program ? program[i] : i;
3587 AVStream *st = ic->streams[real_stream_index];
3588 AVCodecContext *avctx = st->codec;
3589 if (avctx->codec_type != type)
3591 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
3593 if (wanted_stream_nb != real_stream_index &&
3594 st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
3595 AV_DISPOSITION_VISUAL_IMPAIRED))
3597 if (type == AVMEDIA_TYPE_AUDIO && !(avctx->channels && avctx->sample_rate))
3600 decoder = find_decoder(ic, st, st->codec->codec_id);
3603 ret = AVERROR_DECODER_NOT_FOUND;
3607 count = st->codec_info_nb_frames;
3608 bitrate = avctx->bit_rate;
3610 bitrate = avctx->rc_max_rate;
3611 multiframe = FFMIN(5, count);
3612 if ((best_multiframe > multiframe) ||
3613 (best_multiframe == multiframe && best_bitrate > bitrate) ||
3614 (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
3617 best_bitrate = bitrate;
3618 best_multiframe = multiframe;
3619 ret = real_stream_index;
3620 best_decoder = decoder;
3621 if (program && i == nb_streams - 1 && ret < 0) {
3623 nb_streams = ic->nb_streams;
3624 /* no related stream found, try again with everything */
3629 *decoder_ret = (AVCodec*)best_decoder;
3633 /*******************************************************/
3635 int av_read_play(AVFormatContext *s)
3637 if (s->iformat->read_play)
3638 return s->iformat->read_play(s);
3640 return avio_pause(s->pb, 0);
3641 return AVERROR(ENOSYS);
3644 int av_read_pause(AVFormatContext *s)
3646 if (s->iformat->read_pause)
3647 return s->iformat->read_pause(s);
3649 return avio_pause(s->pb, 1);
3650 return AVERROR(ENOSYS);
3653 void ff_free_stream(AVFormatContext *s, AVStream *st) {
3655 av_assert0(s->nb_streams>0);
3656 av_assert0(s->streams[ s->nb_streams - 1 ] == st);
3658 for (j = 0; j < st->nb_side_data; j++)
3659 av_freep(&st->side_data[j].data);
3660 av_freep(&st->side_data);
3661 st->nb_side_data = 0;
3664 av_parser_close(st->parser);
3666 if (st->attached_pic.data)
3667 av_free_packet(&st->attached_pic);
3668 av_dict_free(&st->metadata);
3669 av_freep(&st->probe_data.buf);
3670 av_freep(&st->index_entries);
3671 av_freep(&st->codec->extradata);
3672 av_freep(&st->codec->subtitle_header);
3673 av_freep(&st->codec);
3674 av_freep(&st->priv_data);
3676 av_freep(&st->info->duration_error);
3677 av_freep(&st->info);
3678 av_freep(&st->recommended_encoder_configuration);
3679 av_freep(&st->priv_pts);
3680 av_freep(&s->streams[ --s->nb_streams ]);
3683 void avformat_free_context(AVFormatContext *s)
3691 if (s->iformat && s->iformat->priv_class && s->priv_data)
3692 av_opt_free(s->priv_data);
3693 if (s->oformat && s->oformat->priv_class && s->priv_data)
3694 av_opt_free(s->priv_data);
3696 for (i = s->nb_streams - 1; i >= 0; i--) {
3697 ff_free_stream(s, s->streams[i]);
3699 for (i = s->nb_programs - 1; i >= 0; i--) {
3700 av_dict_free(&s->programs[i]->metadata);
3701 av_freep(&s->programs[i]->stream_index);
3702 av_freep(&s->programs[i]);
3704 av_freep(&s->programs);
3705 av_freep(&s->priv_data);
3706 while (s->nb_chapters--) {
3707 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
3708 av_freep(&s->chapters[s->nb_chapters]);
3710 av_freep(&s->chapters);
3711 av_dict_free(&s->metadata);
3712 av_freep(&s->streams);
3713 av_freep(&s->internal);
3714 flush_packet_queue(s);
3718 void avformat_close_input(AVFormatContext **ps)
3729 if ((s->iformat && strcmp(s->iformat->name, "image2") && s->iformat->flags & AVFMT_NOFILE) ||
3730 (s->flags & AVFMT_FLAG_CUSTOM_IO))
3733 flush_packet_queue(s);
3736 if (s->iformat->read_close)
3737 s->iformat->read_close(s);
3739 avformat_free_context(s);
3746 AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)
3752 if (s->nb_streams >= INT_MAX/sizeof(*streams))
3754 streams = av_realloc_array(s->streams, s->nb_streams + 1, sizeof(*streams));
3757 s->streams = streams;
3759 st = av_mallocz(sizeof(AVStream));
3762 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
3766 st->info->last_dts = AV_NOPTS_VALUE;
3768 st->codec = avcodec_alloc_context3(c);
3775 /* no default bitrate if decoding */
3776 st->codec->bit_rate = 0;
3778 /* default pts setting is MPEG-like */
3779 avpriv_set_pts_info(st, 33, 1, 90000);
3782 st->index = s->nb_streams;
3783 st->start_time = AV_NOPTS_VALUE;
3784 st->duration = AV_NOPTS_VALUE;
3785 /* we set the current DTS to 0 so that formats without any timestamps
3786 * but durations get some timestamps, formats with some unknown
3787 * timestamps have their first few packets buffered and the
3788 * timestamps corrected before they are returned to the user */
3789 st->cur_dts = s->iformat ? RELATIVE_TS_BASE : 0;
3790 st->first_dts = AV_NOPTS_VALUE;
3791 st->probe_packets = MAX_PROBE_PACKETS;
3792 st->pts_wrap_reference = AV_NOPTS_VALUE;
3793 st->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3795 st->last_IP_pts = AV_NOPTS_VALUE;
3796 st->last_dts_for_order_check = AV_NOPTS_VALUE;
3797 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
3798 st->pts_buffer[i] = AV_NOPTS_VALUE;
3800 st->sample_aspect_ratio = (AVRational) { 0, 1 };
3802 #if FF_API_R_FRAME_RATE
3803 st->info->last_dts = AV_NOPTS_VALUE;
3805 st->info->fps_first_dts = AV_NOPTS_VALUE;
3806 st->info->fps_last_dts = AV_NOPTS_VALUE;
3808 st->inject_global_side_data = s->internal->inject_global_side_data;
3810 s->streams[s->nb_streams++] = st;
3814 AVProgram *av_new_program(AVFormatContext *ac, int id)
3816 AVProgram *program = NULL;
3819 av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
3821 for (i = 0; i < ac->nb_programs; i++)
3822 if (ac->programs[i]->id == id)
3823 program = ac->programs[i];
3826 program = av_mallocz(sizeof(AVProgram));
3829 dynarray_add(&ac->programs, &ac->nb_programs, program);
3830 program->discard = AVDISCARD_NONE;
3833 program->pts_wrap_reference = AV_NOPTS_VALUE;
3834 program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
3836 program->start_time =
3837 program->end_time = AV_NOPTS_VALUE;
3842 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
3843 int64_t start, int64_t end, const char *title)
3845 AVChapter *chapter = NULL;
3848 if (end != AV_NOPTS_VALUE && start > end) {
3849 av_log(s, AV_LOG_ERROR, "Chapter end time %"PRId64" before start %"PRId64"\n", end, start);
3853 for (i = 0; i < s->nb_chapters; i++)
3854 if (s->chapters[i]->id == id)
3855 chapter = s->chapters[i];
3858 chapter = av_mallocz(sizeof(AVChapter));
3861 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
3863 av_dict_set(&chapter->metadata, "title", title, 0);
3865 chapter->time_base = time_base;
3866 chapter->start = start;
3872 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
3875 AVProgram *program = NULL;
3878 if (idx >= ac->nb_streams) {
3879 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3883 for (i = 0; i < ac->nb_programs; i++) {
3884 if (ac->programs[i]->id != progid)
3886 program = ac->programs[i];
3887 for (j = 0; j < program->nb_stream_indexes; j++)
3888 if (program->stream_index[j] == idx)
3891 tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
3894 program->stream_index = tmp;
3895 program->stream_index[program->nb_stream_indexes++] = idx;
3900 uint64_t ff_ntp_time(void)
3902 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3905 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
3908 char *q, buf1[20], c;
3909 int nd, len, percentd_found;
3921 while (av_isdigit(*p))
3922 nd = nd * 10 + *p++ - '0';
3924 } while (av_isdigit(c));
3935 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3937 if ((q - buf + len) > buf_size - 1)
3939 memcpy(q, buf1, len);
3947 if ((q - buf) < buf_size - 1)
3951 if (!percentd_found)
3960 void av_url_split(char *proto, int proto_size,
3961 char *authorization, int authorization_size,
3962 char *hostname, int hostname_size,
3963 int *port_ptr, char *path, int path_size, const char *url)
3965 const char *p, *ls, *ls2, *at, *at2, *col, *brk;
3971 if (authorization_size > 0)
3972 authorization[0] = 0;
3973 if (hostname_size > 0)
3978 /* parse protocol */
3979 if ((p = strchr(url, ':'))) {
3980 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3987 /* no protocol means plain filename */
3988 av_strlcpy(path, url, path_size);
3992 /* separate path from hostname */
3993 ls = strchr(p, '/');
3994 ls2 = strchr(p, '?');
3998 ls = FFMIN(ls, ls2);
4000 av_strlcpy(path, ls, path_size);
4002 ls = &p[strlen(p)]; // XXX
4004 /* the rest is hostname, use that to parse auth/port */
4006 /* authorization (user[:pass]@hostname) */
4008 while ((at = strchr(p, '@')) && at < ls) {
4009 av_strlcpy(authorization, at2,
4010 FFMIN(authorization_size, at + 1 - at2));
4011 p = at + 1; /* skip '@' */
4014 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
4016 av_strlcpy(hostname, p + 1,
4017 FFMIN(hostname_size, brk - p));
4018 if (brk[1] == ':' && port_ptr)
4019 *port_ptr = atoi(brk + 2);
4020 } else if ((col = strchr(p, ':')) && col < ls) {
4021 av_strlcpy(hostname, p,
4022 FFMIN(col + 1 - p, hostname_size));
4024 *port_ptr = atoi(col + 1);
4026 av_strlcpy(hostname, p,
4027 FFMIN(ls + 1 - p, hostname_size));
4031 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
4034 static const char hex_table_uc[16] = { '0', '1', '2', '3',
4037 'C', 'D', 'E', 'F' };
4038 static const char hex_table_lc[16] = { '0', '1', '2', '3',
4041 'c', 'd', 'e', 'f' };
4042 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
4044 for (i = 0; i < s; i++) {
4045 buff[i * 2] = hex_table[src[i] >> 4];
4046 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4052 int ff_hex_to_data(uint8_t *data, const char *p)
4059 p += strspn(p, SPACE_CHARS);
4062 c = av_toupper((unsigned char) *p++);
4063 if (c >= '0' && c <= '9')
4065 else if (c >= 'A' && c <= 'F')
4080 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4081 unsigned int pts_num, unsigned int pts_den)
4084 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
4085 if (new_tb.num != pts_num)
4086 av_log(NULL, AV_LOG_DEBUG,
4087 "st:%d removing common factor %d from timebase\n",
4088 s->index, pts_num / new_tb.num);
4090 av_log(NULL, AV_LOG_WARNING,
4091 "st:%d has too large timebase, reducing\n", s->index);
4093 if (new_tb.num <= 0 || new_tb.den <= 0) {
4094 av_log(NULL, AV_LOG_ERROR,
4095 "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
4096 new_tb.num, new_tb.den,
4100 s->time_base = new_tb;
4101 av_codec_set_pkt_timebase(s->codec, new_tb);
4102 s->pts_wrap_bits = pts_wrap_bits;
4105 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4108 const char *ptr = str;
4110 /* Parse key=value pairs. */
4113 char *dest = NULL, *dest_end;
4114 int key_len, dest_len = 0;
4116 /* Skip whitespace and potential commas. */
4117 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
4124 if (!(ptr = strchr(key, '=')))
4127 key_len = ptr - key;
4129 callback_get_buf(context, key, key_len, &dest, &dest_len);
4130 dest_end = dest + dest_len - 1;
4134 while (*ptr && *ptr != '\"') {
4138 if (dest && dest < dest_end)
4142 if (dest && dest < dest_end)
4150 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
4151 if (dest && dest < dest_end)
4159 int ff_find_stream_index(AVFormatContext *s, int id)
4162 for (i = 0; i < s->nb_streams; i++)
4163 if (s->streams[i]->id == id)
4168 int64_t ff_iso8601_to_unix_time(const char *datestr)
4170 struct tm time1 = { 0 }, time2 = { 0 };
4171 const char *ret1, *ret2;
4172 ret1 = av_small_strptime(datestr, "%Y - %m - %d %T", &time1);
4173 ret2 = av_small_strptime(datestr, "%Y - %m - %dT%T", &time2);
4175 return av_timegm(&time2);
4177 return av_timegm(&time1);
4180 int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id,
4184 unsigned int codec_tag;
4185 if (ofmt->query_codec)
4186 return ofmt->query_codec(codec_id, std_compliance);
4187 else if (ofmt->codec_tag)
4188 return !!av_codec_get_tag2(ofmt->codec_tag, codec_id, &codec_tag);
4189 else if (codec_id == ofmt->video_codec ||
4190 codec_id == ofmt->audio_codec ||
4191 codec_id == ofmt->subtitle_codec)
4194 return AVERROR_PATCHWELCOME;
4197 int avformat_network_init(void)
4201 ff_network_inited_globally = 1;
4202 if ((ret = ff_network_init()) < 0)
4204 if ((ret = ff_tls_init()) < 0)
4210 int avformat_network_deinit(void)
4215 ff_network_inited_globally = 0;
4220 int ff_add_param_change(AVPacket *pkt, int32_t channels,
4221 uint64_t channel_layout, int32_t sample_rate,
4222 int32_t width, int32_t height)
4228 return AVERROR(EINVAL);
4231 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
4233 if (channel_layout) {
4235 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
4239 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
4241 if (width || height) {
4243 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
4245 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
4247 return AVERROR(ENOMEM);
4248 bytestream_put_le32(&data, flags);
4250 bytestream_put_le32(&data, channels);
4252 bytestream_put_le64(&data, channel_layout);
4254 bytestream_put_le32(&data, sample_rate);
4255 if (width || height) {
4256 bytestream_put_le32(&data, width);
4257 bytestream_put_le32(&data, height);
4262 AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
4264 AVRational undef = {0, 1};
4265 AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
4266 AVRational codec_sample_aspect_ratio = stream && stream->codec ? stream->codec->sample_aspect_ratio : undef;
4267 AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
4269 av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
4270 stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
4271 if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
4272 stream_sample_aspect_ratio = undef;
4274 av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
4275 frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
4276 if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
4277 frame_sample_aspect_ratio = undef;
4279 if (stream_sample_aspect_ratio.num)
4280 return stream_sample_aspect_ratio;
4282 return frame_sample_aspect_ratio;
4285 AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
4287 AVRational fr = st->r_frame_rate;
4288 AVRational codec_fr = st->codec->framerate;
4289 AVRational avg_fr = st->avg_frame_rate;
4291 if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
4292 av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
4297 if (st->codec->ticks_per_frame > 1) {
4298 if ( codec_fr.num > 0 && codec_fr.den > 0 &&
4299 (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
4306 int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
4309 if (*spec <= '9' && *spec >= '0') /* opt:index */
4310 return strtol(spec, NULL, 0) == st->index;
4311 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
4312 *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
4313 enum AVMediaType type;
4317 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
4318 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
4319 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
4320 case 'd': type = AVMEDIA_TYPE_DATA; break;
4321 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
4322 case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
4323 default: av_assert0(0);
4325 if (type != st->codec->codec_type)
4327 if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
4329 if (*spec++ == ':') { /* possibly followed by :index */
4330 int i, index = strtol(spec, NULL, 0);
4331 for (i = 0; i < s->nb_streams; i++)
4332 if (s->streams[i]->codec->codec_type == type &&
4333 !(nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC)) &&
4335 return i == st->index;
4339 } else if (*spec == 'p' && *(spec + 1) == ':') {
4343 prog_id = strtol(spec, &endptr, 0);
4344 for (i = 0; i < s->nb_programs; i++) {
4345 if (s->programs[i]->id != prog_id)
4348 if (*endptr++ == ':') {
4349 int stream_idx = strtol(endptr, NULL, 0);
4350 return stream_idx >= 0 &&
4351 stream_idx < s->programs[i]->nb_stream_indexes &&
4352 st->index == s->programs[i]->stream_index[stream_idx];
4355 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
4356 if (st->index == s->programs[i]->stream_index[j])
4360 } else if (*spec == '#' ||
4361 (*spec == 'i' && *(spec + 1) == ':')) {
4364 spec += 1 + (*spec == 'i');
4365 stream_id = strtol(spec, &endptr, 0);
4367 return stream_id == st->id;
4368 } else if (*spec == 'm' && *(spec + 1) == ':') {
4369 AVDictionaryEntry *tag;
4374 val = strchr(spec, ':');
4376 key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
4378 return AVERROR(ENOMEM);
4380 tag = av_dict_get(st->metadata, key, NULL, 0);
4382 if (!val || !strcmp(tag->value, val + 1))
4391 } else if (*spec == 'u') {
4392 AVCodecContext *avctx = st->codec;
4394 switch (avctx->codec_type) {
4395 case AVMEDIA_TYPE_AUDIO:
4396 val = avctx->sample_rate && avctx->channels;
4397 if (avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
4400 case AVMEDIA_TYPE_VIDEO:
4401 val = avctx->width && avctx->height;
4402 if (avctx->pix_fmt == AV_PIX_FMT_NONE)
4405 case AVMEDIA_TYPE_UNKNOWN:
4412 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
4413 } else if (!*spec) /* empty specifier, matches everything */
4416 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
4417 return AVERROR(EINVAL);
4420 int ff_generate_avci_extradata(AVStream *st)
4422 static const uint8_t avci100_1080p_extradata[] = {
4424 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4425 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4426 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4427 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
4428 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
4429 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
4430 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
4431 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
4432 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
4434 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4437 static const uint8_t avci100_1080i_extradata[] = {
4439 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4440 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
4441 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
4442 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
4443 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
4444 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
4445 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
4446 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
4447 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
4448 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
4449 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x20,
4451 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
4454 static const uint8_t avci50_1080p_extradata[] = {
4456 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4457 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4458 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4459 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4460 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4461 0x6e, 0x6c, 0xd3, 0x3c, 0x05, 0xa0, 0x22, 0x7e,
4462 0x5f, 0xfc, 0x00, 0x0c, 0x00, 0x13, 0x8c, 0x04,
4463 0x04, 0x05, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00,
4464 0x00, 0x03, 0x00, 0x32, 0x84, 0x00, 0x00, 0x00,
4466 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4469 static const uint8_t avci50_1080i_extradata[] = {
4471 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
4472 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4473 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4474 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
4475 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
4476 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
4477 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
4478 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
4479 0x81, 0x13, 0xf7, 0xff, 0x80, 0x02, 0x00, 0x01,
4480 0xf1, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
4481 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
4483 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4486 static const uint8_t avci100_720p_extradata[] = {
4488 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
4489 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
4490 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
4491 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
4492 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
4493 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
4494 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
4495 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
4496 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
4497 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
4499 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
4502 static const uint8_t avci50_720p_extradata[] = {
4504 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x20,
4505 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
4506 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
4507 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6f, 0x37,
4508 0xcd, 0xf9, 0xbf, 0x81, 0x6b, 0xf3, 0x7c, 0xde,
4509 0x6e, 0x6c, 0xd3, 0x3c, 0x0f, 0x01, 0x6e, 0xff,
4510 0xc0, 0x00, 0xc0, 0x01, 0x38, 0xc0, 0x40, 0x40,
4511 0x50, 0x00, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00,
4512 0x06, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
4514 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
4518 const uint8_t *data = NULL;
4521 if (st->codec->width == 1920) {
4522 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4523 data = avci100_1080p_extradata;
4524 size = sizeof(avci100_1080p_extradata);
4526 data = avci100_1080i_extradata;
4527 size = sizeof(avci100_1080i_extradata);
4529 } else if (st->codec->width == 1440) {
4530 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
4531 data = avci50_1080p_extradata;
4532 size = sizeof(avci50_1080p_extradata);
4534 data = avci50_1080i_extradata;
4535 size = sizeof(avci50_1080i_extradata);
4537 } else if (st->codec->width == 1280) {
4538 data = avci100_720p_extradata;
4539 size = sizeof(avci100_720p_extradata);
4540 } else if (st->codec->width == 960) {
4541 data = avci50_720p_extradata;
4542 size = sizeof(avci50_720p_extradata);
4548 av_freep(&st->codec->extradata);
4549 if (ff_alloc_extradata(st->codec, size))
4550 return AVERROR(ENOMEM);
4551 memcpy(st->codec->extradata, data, size);
4556 uint8_t *av_stream_get_side_data(AVStream *st, enum AVPacketSideDataType type,
4561 for (i = 0; i < st->nb_side_data; i++) {
4562 if (st->side_data[i].type == type) {
4564 *size = st->side_data[i].size;
4565 return st->side_data[i].data;
4571 uint8_t *ff_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
4574 AVPacketSideData *sd, *tmp;
4576 uint8_t *data = av_malloc(size);
4581 for (i = 0; i < st->nb_side_data; i++) {
4582 sd = &st->side_data[i];
4584 if (sd->type == type) {
4585 av_freep(&sd->data);
4592 tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));
4598 st->side_data = tmp;
4601 sd = &st->side_data[st->nb_side_data - 1];