2 * various utility functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/dict.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/time.h"
39 #include "libavcodec/bytestream.h"
40 #include "libavcodec/internal.h"
42 #include "audiointerleave.h"
44 #include "avio_internal.h"
56 * various utility functions for use within Libav
59 unsigned avformat_version(void)
61 return LIBAVFORMAT_VERSION_INT;
64 const char *avformat_configuration(void)
66 return LIBAV_CONFIGURATION;
69 const char *avformat_license(void)
71 #define LICENSE_PREFIX "libavformat license: "
72 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
75 /* an arbitrarily chosen "sane" max packet size -- 50M */
76 #define SANE_CHUNK_SIZE (50000000)
78 /* Read the data in sane-sized chunks and append to pkt.
79 * Return the number of bytes read or an error. */
80 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
82 int64_t chunk_size = size;
83 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
84 int orig_size = pkt->size;
88 int prev_size = pkt->size;
91 /* When the caller requests a lot of data, limit it to the amount
92 * left in file or SANE_CHUNK_SIZE when it is not known. */
93 if (size > SANE_CHUNK_SIZE) {
94 int64_t filesize = avio_size(s) - avio_tell(s);
95 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
97 read_size = FFMIN(size, chunk_size);
99 ret = av_grow_packet(pkt, read_size);
103 ret = avio_read(s, pkt->data + prev_size, read_size);
104 if (ret != read_size) {
105 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
115 return pkt->size > orig_size ? pkt->size - orig_size : ret;
118 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
123 pkt->pos = avio_tell(s);
125 return append_packet_chunked(s, pkt, size);
128 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
131 return av_get_packet(s, pkt, size);
132 return append_packet_chunked(s, pkt, size);
135 int av_filename_number_test(const char *filename)
139 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
142 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened,
145 AVProbeData lpd = *pd;
146 AVInputFormat *fmt1 = NULL, *fmt;
149 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
150 int id3len = ff_id3v2_tag_len(lpd.buf);
151 if (lpd.buf_size > id3len + 16) {
153 lpd.buf_size -= id3len;
159 while ((fmt1 = av_iformat_next(fmt1))) {
160 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
163 if (fmt1->read_probe) {
164 score = fmt1->read_probe(&lpd);
165 } else if (fmt1->extensions) {
166 if (av_match_ext(lpd.filename, fmt1->extensions))
167 score = AVPROBE_SCORE_EXTENSION;
169 if (score > *score_max) {
172 } else if (score == *score_max)
176 // A hack for files with huge id3v2 tags -- try to guess by file extension.
177 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_EXTENSION / 2) {
178 while ((fmt = av_iformat_next(fmt)))
179 if (fmt->extensions &&
180 av_match_ext(lpd.filename, fmt->extensions)) {
181 *score_max = AVPROBE_SCORE_EXTENSION / 2;
186 if (!fmt && id3 && *score_max < AVPROBE_SCORE_EXTENSION / 2 - 1) {
187 while ((fmt = av_iformat_next(fmt)))
188 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
189 *score_max = AVPROBE_SCORE_EXTENSION / 2 - 1;
197 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
200 return av_probe_input_format2(pd, is_opened, &score);
203 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
204 AVProbeData *pd, int score)
206 static const struct {
209 enum AVMediaType type;
211 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
212 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
213 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
214 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
215 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
216 { "latm", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
217 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
218 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
219 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
222 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
226 av_log(s, AV_LOG_DEBUG,
227 "Probe with size=%d, packets=%d detected %s with score=%d\n",
228 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
230 for (i = 0; fmt_id_type[i].name; i++) {
231 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
232 st->codec->codec_id = fmt_id_type[i].id;
233 st->codec->codec_type = fmt_id_type[i].type;
241 /************************************************************/
242 /* input media file */
244 /** size of probe buffer, for guessing file type from file contents */
245 #define PROBE_BUF_MIN 2048
246 #define PROBE_BUF_MAX (1 << 20)
248 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
249 const char *filename, void *logctx,
250 unsigned int offset, unsigned int max_probe_size)
252 AVProbeData pd = { filename ? filename : "" };
254 int ret = 0, probe_size;
257 max_probe_size = PROBE_BUF_MAX;
258 else if (max_probe_size > PROBE_BUF_MAX)
259 max_probe_size = PROBE_BUF_MAX;
260 else if (max_probe_size < PROBE_BUF_MIN)
261 return AVERROR(EINVAL);
263 if (offset >= max_probe_size)
264 return AVERROR(EINVAL);
265 avio_skip(pb, offset);
266 max_probe_size -= offset;
268 for (probe_size = PROBE_BUF_MIN; probe_size <= max_probe_size && !*fmt;
269 probe_size = FFMIN(probe_size << 1,
270 FFMAX(max_probe_size, probe_size + 1))) {
271 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX / 4 : 0;
273 /* Read probe data. */
274 if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)
276 if ((ret = avio_read(pb, buf + pd.buf_size,
277 probe_size - pd.buf_size)) < 0) {
278 /* Fail if error was not end of file, otherwise, lower score. */
279 if (ret != AVERROR_EOF) {
284 ret = 0; /* error was end of file, nothing read */
289 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
291 /* Guess file format. */
292 *fmt = av_probe_input_format2(&pd, 1, &score);
294 /* This can only be true in the last iteration. */
295 if (score <= AVPROBE_SCORE_MAX / 4) {
296 av_log(logctx, AV_LOG_WARNING,
297 "Format detected only with low score of %d, "
298 "misdetection possible!\n", score);
300 av_log(logctx, AV_LOG_DEBUG,
301 "Probed with size=%d and score=%d\n", probe_size, score);
307 return AVERROR_INVALIDDATA;
310 /* Rewind. Reuse probe buffer to avoid seeking. */
311 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
317 /* Open input file and probe the format if necessary. */
318 static int init_input(AVFormatContext *s, const char *filename,
319 AVDictionary **options)
322 AVProbeData pd = { filename, NULL, 0 };
325 s->flags |= AVFMT_FLAG_CUSTOM_IO;
327 return av_probe_input_buffer(s->pb, &s->iformat, filename,
329 else if (s->iformat->flags & AVFMT_NOFILE)
330 return AVERROR(EINVAL);
334 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
335 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
338 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
339 &s->interrupt_callback, options)) < 0)
343 return av_probe_input_buffer(s->pb, &s->iformat, filename,
347 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
348 AVPacketList **plast_pktl)
350 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
355 (*plast_pktl)->next = pktl;
357 *packet_buffer = pktl;
359 /* Add the packet in the buffered packet list. */
365 static int queue_attached_pictures(AVFormatContext *s)
368 for (i = 0; i < s->nb_streams; i++)
369 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
370 s->streams[i]->discard < AVDISCARD_ALL) {
371 AVPacket copy = s->streams[i]->attached_pic;
372 copy.buf = av_buffer_ref(copy.buf);
374 return AVERROR(ENOMEM);
376 add_to_pktbuf(&s->raw_packet_buffer, ©,
377 &s->raw_packet_buffer_end);
382 int avformat_open_input(AVFormatContext **ps, const char *filename,
383 AVInputFormat *fmt, AVDictionary **options)
385 AVFormatContext *s = *ps;
387 AVDictionary *tmp = NULL;
388 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
390 if (!s && !(s = avformat_alloc_context()))
391 return AVERROR(ENOMEM);
396 av_dict_copy(&tmp, *options, 0);
398 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
401 if ((ret = init_input(s, filename, &tmp)) < 0)
404 /* Check filename in case an image number is expected. */
405 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
406 if (!av_filename_number_test(filename)) {
407 ret = AVERROR(EINVAL);
412 s->duration = s->start_time = AV_NOPTS_VALUE;
413 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
415 /* Allocate private data. */
416 if (s->iformat->priv_data_size > 0) {
417 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
418 ret = AVERROR(ENOMEM);
421 if (s->iformat->priv_class) {
422 *(const AVClass **) s->priv_data = s->iformat->priv_class;
423 av_opt_set_defaults(s->priv_data);
424 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
429 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
431 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
433 if (s->iformat->read_header)
434 if ((ret = s->iformat->read_header(s)) < 0)
437 if (id3v2_extra_meta &&
438 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
440 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
442 if ((ret = queue_attached_pictures(s)) < 0)
445 if (s->pb && !s->data_offset)
446 s->data_offset = avio_tell(s->pb);
448 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
451 av_dict_free(options);
458 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
460 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
462 avformat_free_context(s);
467 /*******************************************************/
469 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
471 if (st->codec->codec_id == AV_CODEC_ID_PROBE) {
472 AVProbeData *pd = &st->probe_data;
473 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
478 if ((err = av_reallocp(&pd->buf, pd->buf_size + pkt->size +
479 AVPROBE_PADDING_SIZE)) < 0)
481 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
482 pd->buf_size += pkt->size;
483 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
485 st->probe_packets = 0;
487 av_log(s, AV_LOG_ERROR,
488 "nothing to probe for stream %d\n", st->index);
493 if (!st->probe_packets ||
494 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
495 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0
496 ? AVPROBE_SCORE_MAX / 4 : 0);
497 if (st->codec->codec_id != AV_CODEC_ID_PROBE) {
500 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
507 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
513 AVPacketList *pktl = s->raw_packet_buffer;
517 st = s->streams[pkt->stream_index];
518 if (st->codec->codec_id != AV_CODEC_ID_PROBE ||
519 !st->probe_packets ||
520 s->raw_packet_buffer_remaining_size < pkt->size) {
522 if (st->probe_packets)
523 if ((err = probe_codec(s, st, NULL)) < 0)
525 pd = &st->probe_data;
528 s->raw_packet_buffer = pktl->next;
529 s->raw_packet_buffer_remaining_size += pkt->size;
538 ret = s->iformat->read_packet(s, pkt);
540 if (!pktl || ret == AVERROR(EAGAIN))
542 for (i = 0; i < s->nb_streams; i++) {
544 if (st->probe_packets)
545 if ((err = probe_codec(s, st, NULL)) < 0)
551 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
552 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
553 av_log(s, AV_LOG_WARNING,
554 "Dropped corrupted packet (stream = %d)\n",
560 st = s->streams[pkt->stream_index];
562 switch (st->codec->codec_type) {
563 case AVMEDIA_TYPE_VIDEO:
564 if (s->video_codec_id)
565 st->codec->codec_id = s->video_codec_id;
567 case AVMEDIA_TYPE_AUDIO:
568 if (s->audio_codec_id)
569 st->codec->codec_id = s->audio_codec_id;
571 case AVMEDIA_TYPE_SUBTITLE:
572 if (s->subtitle_codec_id)
573 st->codec->codec_id = s->subtitle_codec_id;
577 if (!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
581 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
582 s->raw_packet_buffer_remaining_size -= pkt->size;
584 if ((err = probe_codec(s, st, pkt)) < 0)
589 /**********************************************************/
592 * Get the number of samples of an audio frame. Return -1 on error.
594 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
598 /* give frame_size priority if demuxing */
599 if (!mux && enc->frame_size > 1)
600 return enc->frame_size;
602 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
605 /* Fall back on using frame_size if muxing. */
606 if (enc->frame_size > 1)
607 return enc->frame_size;
613 * Return the frame duration in seconds. Return 0 if not available.
615 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
616 AVCodecParserContext *pc, AVPacket *pkt)
622 switch (st->codec->codec_type) {
623 case AVMEDIA_TYPE_VIDEO:
624 if (st->avg_frame_rate.num) {
625 *pnum = st->avg_frame_rate.den;
626 *pden = st->avg_frame_rate.num;
627 } else if (st->time_base.num * 1000LL > st->time_base.den) {
628 *pnum = st->time_base.num;
629 *pden = st->time_base.den;
630 } else if (st->codec->time_base.num * 1000LL > st->codec->time_base.den) {
631 *pnum = st->codec->time_base.num;
632 *pden = st->codec->time_base.den;
633 if (pc && pc->repeat_pict) {
634 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
635 *pden /= 1 + pc->repeat_pict;
637 *pnum *= 1 + pc->repeat_pict;
639 /* If this codec can be interlaced or progressive then we need
640 * a parser to compute duration of a packet. Thus if we have
641 * no parser in such case leave duration undefined. */
642 if (st->codec->ticks_per_frame > 1 && !pc)
646 case AVMEDIA_TYPE_AUDIO:
647 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
648 if (frame_size <= 0 || st->codec->sample_rate <= 0)
651 *pden = st->codec->sample_rate;
658 static int is_intra_only(enum AVCodecID id)
660 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
663 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
668 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
669 int64_t dts, int64_t pts)
671 AVStream *st = s->streams[stream_index];
672 AVPacketList *pktl = s->packet_buffer;
674 if (st->first_dts != AV_NOPTS_VALUE ||
675 dts == AV_NOPTS_VALUE ||
676 st->cur_dts == AV_NOPTS_VALUE)
679 st->first_dts = dts - st->cur_dts;
682 for (; pktl; pktl = pktl->next) {
683 if (pktl->pkt.stream_index != stream_index)
685 // FIXME: think more about this check
686 if (pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
687 pktl->pkt.pts += st->first_dts;
689 if (pktl->pkt.dts != AV_NOPTS_VALUE)
690 pktl->pkt.dts += st->first_dts;
692 if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
693 st->start_time = pktl->pkt.pts;
695 if (st->start_time == AV_NOPTS_VALUE)
696 st->start_time = pts;
699 static void update_initial_durations(AVFormatContext *s, AVStream *st,
700 int stream_index, int duration)
702 AVPacketList *pktl = s->packet_buffer;
705 if (st->first_dts != AV_NOPTS_VALUE) {
706 cur_dts = st->first_dts;
707 for (; pktl; pktl = pktl->next) {
708 if (pktl->pkt.stream_index == stream_index) {
709 if (pktl->pkt.pts != pktl->pkt.dts ||
710 pktl->pkt.dts != AV_NOPTS_VALUE ||
716 pktl = s->packet_buffer;
717 st->first_dts = cur_dts;
718 } else if (st->cur_dts)
721 for (; pktl; pktl = pktl->next) {
722 if (pktl->pkt.stream_index != stream_index)
724 if (pktl->pkt.pts == pktl->pkt.dts &&
725 pktl->pkt.dts == AV_NOPTS_VALUE &&
726 !pktl->pkt.duration) {
727 pktl->pkt.dts = cur_dts;
728 if (!st->codec->has_b_frames)
729 pktl->pkt.pts = cur_dts;
731 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
732 pktl->pkt.duration = duration;
736 if (st->first_dts == AV_NOPTS_VALUE)
737 st->cur_dts = cur_dts;
740 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
741 AVCodecParserContext *pc, AVPacket *pkt)
743 int num, den, presentation_delayed, delay, i;
746 if (s->flags & AVFMT_FLAG_NOFILLIN)
749 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
750 pkt->dts = AV_NOPTS_VALUE;
752 /* do we have a video B-frame ? */
753 delay = st->codec->has_b_frames;
754 presentation_delayed = 0;
756 /* XXX: need has_b_frame, but cannot get it if the codec is
759 pc && pc->pict_type != AV_PICTURE_TYPE_B)
760 presentation_delayed = 1;
762 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
763 st->pts_wrap_bits < 63 &&
764 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
765 pkt->dts -= 1LL << st->pts_wrap_bits;
768 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
769 * We take the conservative approach and discard both.
770 * Note: If this is misbehaving for an H.264 file, then possibly
771 * presentation_delayed is not set correctly. */
772 if (delay == 1 && pkt->dts == pkt->pts &&
773 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
774 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
775 pkt->dts = pkt->pts = AV_NOPTS_VALUE;
778 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
779 ff_compute_frame_duration(&num, &den, st, pc, pkt);
781 pkt->duration = av_rescale_rnd(1, num * (int64_t) st->time_base.den,
782 den * (int64_t) st->time_base.num,
785 if (pkt->duration != 0 && s->packet_buffer)
786 update_initial_durations(s, st, pkt->stream_index,
791 /* Correct timestamps with byte offset if demuxers only have timestamps
792 * on packet boundaries */
793 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
794 /* this will estimate bitrate based on this frame's duration and size */
795 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
796 if (pkt->pts != AV_NOPTS_VALUE)
798 if (pkt->dts != AV_NOPTS_VALUE)
802 /* This may be redundant, but it should not hurt. */
803 if (pkt->dts != AV_NOPTS_VALUE &&
804 pkt->pts != AV_NOPTS_VALUE &&
806 presentation_delayed = 1;
809 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" "
810 "cur_dts:%"PRId64" st:%d pc:%p\n",
811 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
812 pkt->stream_index, pc);
813 /* Interpolate PTS and DTS if they are not present. We skip H.264
814 * currently because delay and has_b_frames are not reliably set. */
815 if ((delay == 0 || (delay == 1 && pc)) &&
816 st->codec->codec_id != AV_CODEC_ID_H264) {
817 if (presentation_delayed) {
818 /* DTS = decompression timestamp */
819 /* PTS = presentation timestamp */
820 if (pkt->dts == AV_NOPTS_VALUE)
821 pkt->dts = st->last_IP_pts;
822 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
823 if (pkt->dts == AV_NOPTS_VALUE)
824 pkt->dts = st->cur_dts;
826 /* This is tricky: the dts must be incremented by the duration
827 * of the frame we are displaying, i.e. the last I- or P-frame. */
828 if (st->last_IP_duration == 0)
829 st->last_IP_duration = pkt->duration;
830 if (pkt->dts != AV_NOPTS_VALUE)
831 st->cur_dts = pkt->dts + st->last_IP_duration;
832 st->last_IP_duration = pkt->duration;
833 st->last_IP_pts = pkt->pts;
834 /* Cannot compute PTS if not present (we can compute it only
835 * by knowing the future. */
836 } else if (pkt->pts != AV_NOPTS_VALUE ||
837 pkt->dts != AV_NOPTS_VALUE ||
839 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
840 int duration = pkt->duration;
841 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
842 ff_compute_frame_duration(&num, &den, st, pc, pkt);
844 duration = av_rescale_rnd(1,
845 num * (int64_t) st->time_base.den,
846 den * (int64_t) st->time_base.num,
848 if (duration != 0 && s->packet_buffer)
849 update_initial_durations(s, st, pkt->stream_index,
854 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
856 /* presentation is not delayed : PTS and DTS are the same */
857 if (pkt->pts == AV_NOPTS_VALUE)
859 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
861 if (pkt->pts == AV_NOPTS_VALUE)
862 pkt->pts = st->cur_dts;
864 if (pkt->pts != AV_NOPTS_VALUE)
865 st->cur_dts = pkt->pts + duration;
870 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
871 st->pts_buffer[0] = pkt->pts;
872 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
873 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
874 if (pkt->dts == AV_NOPTS_VALUE)
875 pkt->dts = st->pts_buffer[0];
876 // We skipped it above so we try here.
877 if (st->codec->codec_id == AV_CODEC_ID_H264)
878 // This should happen on the first packet
879 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
880 if (pkt->dts > st->cur_dts)
881 st->cur_dts = pkt->dts;
885 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
886 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
889 if (is_intra_only(st->codec->codec_id))
890 pkt->flags |= AV_PKT_FLAG_KEY;
892 pkt->convergence_duration = pc->convergence_duration;
895 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
898 AVPacketList *pktl = *pkt_buf;
899 *pkt_buf = pktl->next;
900 av_free_packet(&pktl->pkt);
907 * Parse a packet, add all split parts to parse_queue.
909 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
911 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
913 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
914 AVStream *st = s->streams[stream_index];
915 uint8_t *data = pkt ? pkt->data : NULL;
916 int size = pkt ? pkt->size : 0;
917 int ret = 0, got_output = 0;
920 av_init_packet(&flush_pkt);
925 while (size > 0 || (pkt == &flush_pkt && got_output)) {
928 av_init_packet(&out_pkt);
929 len = av_parser_parse2(st->parser, st->codec,
930 &out_pkt.data, &out_pkt.size, data, size,
931 pkt->pts, pkt->dts, pkt->pos);
933 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
934 /* increment read pointer */
938 got_output = !!out_pkt.size;
943 if (pkt->side_data) {
944 out_pkt.side_data = pkt->side_data;
945 out_pkt.side_data_elems = pkt->side_data_elems;
946 pkt->side_data = NULL;
947 pkt->side_data_elems = 0;
950 /* set the duration */
951 out_pkt.duration = 0;
952 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
953 if (st->codec->sample_rate > 0) {
955 av_rescale_q_rnd(st->parser->duration,
956 (AVRational) { 1, st->codec->sample_rate },
962 out_pkt.stream_index = st->index;
963 out_pkt.pts = st->parser->pts;
964 out_pkt.dts = st->parser->dts;
965 out_pkt.pos = st->parser->pos;
967 if (st->parser->key_frame == 1 ||
968 (st->parser->key_frame == -1 &&
969 st->parser->pict_type == AV_PICTURE_TYPE_I))
970 out_pkt.flags |= AV_PKT_FLAG_KEY;
972 compute_pkt_fields(s, st, st->parser, &out_pkt);
974 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
975 out_pkt.flags & AV_PKT_FLAG_KEY) {
976 ff_reduce_index(s, st->index);
977 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
978 0, 0, AVINDEX_KEYFRAME);
981 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
982 out_pkt.buf = pkt->buf;
984 #if FF_API_DESTRUCT_PACKET
985 FF_DISABLE_DEPRECATION_WARNINGS
986 out_pkt.destruct = pkt->destruct;
987 pkt->destruct = NULL;
988 FF_ENABLE_DEPRECATION_WARNINGS
991 if ((ret = av_dup_packet(&out_pkt)) < 0)
994 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
995 av_free_packet(&out_pkt);
996 ret = AVERROR(ENOMEM);
1001 /* end of the stream => close and free the parser */
1002 if (pkt == &flush_pkt) {
1003 av_parser_close(st->parser);
1008 av_free_packet(pkt);
1012 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1013 AVPacketList **pkt_buffer_end,
1017 av_assert0(*pkt_buffer);
1020 *pkt_buffer = pktl->next;
1022 *pkt_buffer_end = NULL;
1027 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1029 int ret = 0, i, got_packet = 0;
1031 av_init_packet(pkt);
1033 while (!got_packet && !s->parse_queue) {
1037 /* read next packet */
1038 ret = ff_read_packet(s, &cur_pkt);
1040 if (ret == AVERROR(EAGAIN))
1042 /* flush the parsers */
1043 for (i = 0; i < s->nb_streams; i++) {
1045 if (st->parser && st->need_parsing)
1046 parse_packet(s, NULL, st->index);
1048 /* all remaining packets are now in parse_queue =>
1049 * really terminate parsing */
1053 st = s->streams[cur_pkt.stream_index];
1055 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1056 cur_pkt.dts != AV_NOPTS_VALUE &&
1057 cur_pkt.pts < cur_pkt.dts) {
1058 av_log(s, AV_LOG_WARNING,
1059 "Invalid timestamps stream=%d, pts=%"PRId64", "
1060 "dts=%"PRId64", size=%d\n",
1061 cur_pkt.stream_index, cur_pkt.pts,
1062 cur_pkt.dts, cur_pkt.size);
1064 if (s->debug & FF_FDEBUG_TS)
1065 av_log(s, AV_LOG_DEBUG,
1066 "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", "
1067 "size=%d, duration=%d, flags=%d\n",
1068 cur_pkt.stream_index, cur_pkt.pts, cur_pkt.dts,
1069 cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1071 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1072 st->parser = av_parser_init(st->codec->codec_id);
1074 /* no parser available: just output the raw packets */
1075 st->need_parsing = AVSTREAM_PARSE_NONE;
1076 else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1077 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1078 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1079 st->parser->flags |= PARSER_FLAG_ONCE;
1082 if (!st->need_parsing || !st->parser) {
1083 /* no parsing needed: we just output the packet as is */
1085 compute_pkt_fields(s, st, NULL, pkt);
1086 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1087 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1088 ff_reduce_index(s, st->index);
1089 av_add_index_entry(st, pkt->pos, pkt->dts,
1090 0, 0, AVINDEX_KEYFRAME);
1093 } else if (st->discard < AVDISCARD_ALL) {
1094 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1098 av_free_packet(&cur_pkt);
1102 if (!got_packet && s->parse_queue)
1103 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1105 if (s->debug & FF_FDEBUG_TS)
1106 av_log(s, AV_LOG_DEBUG,
1107 "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", "
1108 "size=%d, duration=%d, flags=%d\n",
1109 pkt->stream_index, pkt->pts, pkt->dts,
1110 pkt->size, pkt->duration, pkt->flags);
1115 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1117 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1121 return s->packet_buffer
1122 ? read_from_packet_buffer(&s->packet_buffer,
1123 &s->packet_buffer_end, pkt)
1124 : read_frame_internal(s, pkt);
1128 AVPacketList *pktl = s->packet_buffer;
1131 AVPacket *next_pkt = &pktl->pkt;
1133 if (next_pkt->dts != AV_NOPTS_VALUE) {
1134 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1135 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1136 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1137 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1138 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
1140 next_pkt->pts = pktl->pkt.dts;
1144 pktl = s->packet_buffer;
1147 /* read packet from packet buffer, if there is data */
1148 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1149 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1150 return read_from_packet_buffer(&s->packet_buffer,
1151 &s->packet_buffer_end, pkt);
1154 ret = read_frame_internal(s, pkt);
1156 if (pktl && ret != AVERROR(EAGAIN)) {
1163 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1164 &s->packet_buffer_end)) < 0)
1165 return AVERROR(ENOMEM);
1169 /* XXX: suppress the packet queue */
1170 static void flush_packet_queue(AVFormatContext *s)
1172 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1173 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1174 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1176 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1179 /*******************************************************/
1182 int av_find_default_stream_index(AVFormatContext *s)
1184 int first_audio_index = -1;
1188 if (s->nb_streams <= 0)
1190 for (i = 0; i < s->nb_streams; i++) {
1192 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1193 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1196 if (first_audio_index < 0 &&
1197 st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1198 first_audio_index = i;
1200 return first_audio_index >= 0 ? first_audio_index : 0;
1203 /** Flush the frame reader. */
1204 void ff_read_frame_flush(AVFormatContext *s)
1209 flush_packet_queue(s);
1211 /* Reset read state for each stream. */
1212 for (i = 0; i < s->nb_streams; i++) {
1216 av_parser_close(st->parser);
1219 st->last_IP_pts = AV_NOPTS_VALUE;
1220 /* We set the current DTS to an unspecified origin. */
1221 st->cur_dts = AV_NOPTS_VALUE;
1223 st->probe_packets = MAX_PROBE_PACKETS;
1225 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1226 st->pts_buffer[j] = AV_NOPTS_VALUE;
1230 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1234 for (i = 0; i < s->nb_streams; i++) {
1235 AVStream *st = s->streams[i];
1238 av_rescale(timestamp,
1239 st->time_base.den * (int64_t) ref_st->time_base.num,
1240 st->time_base.num * (int64_t) ref_st->time_base.den);
1244 void ff_reduce_index(AVFormatContext *s, int stream_index)
1246 AVStream *st = s->streams[stream_index];
1247 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1249 if ((unsigned) st->nb_index_entries >= max_entries) {
1251 for (i = 0; 2 * i < st->nb_index_entries; i++)
1252 st->index_entries[i] = st->index_entries[2 * i];
1253 st->nb_index_entries = i;
1257 int ff_add_index_entry(AVIndexEntry **index_entries,
1258 int *nb_index_entries,
1259 unsigned int *index_entries_allocated_size,
1260 int64_t pos, int64_t timestamp,
1261 int size, int distance, int flags)
1263 AVIndexEntry *entries, *ie;
1266 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1269 entries = av_fast_realloc(*index_entries,
1270 index_entries_allocated_size,
1271 (*nb_index_entries + 1) *
1272 sizeof(AVIndexEntry));
1276 *index_entries = entries;
1278 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1279 timestamp, AVSEEK_FLAG_ANY);
1282 index = (*nb_index_entries)++;
1283 ie = &entries[index];
1284 assert(index == 0 || ie[-1].timestamp < timestamp);
1286 ie = &entries[index];
1287 if (ie->timestamp != timestamp) {
1288 if (ie->timestamp <= timestamp)
1290 memmove(entries + index + 1, entries + index,
1291 sizeof(AVIndexEntry) * (*nb_index_entries - index));
1292 (*nb_index_entries)++;
1293 } else if (ie->pos == pos && distance < ie->min_distance)
1294 // do not reduce the distance
1295 distance = ie->min_distance;
1299 ie->timestamp = timestamp;
1300 ie->min_distance = distance;
1307 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1308 int size, int distance, int flags)
1310 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1311 &st->index_entries_allocated_size, pos,
1312 timestamp, size, distance, flags);
1315 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1316 int64_t wanted_timestamp, int flags)
1324 // Optimize appending index entries at the end.
1325 if (b && entries[b - 1].timestamp < wanted_timestamp)
1330 timestamp = entries[m].timestamp;
1331 if (timestamp >= wanted_timestamp)
1333 if (timestamp <= wanted_timestamp)
1336 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1338 if (!(flags & AVSEEK_FLAG_ANY))
1339 while (m >= 0 && m < nb_entries &&
1340 !(entries[m].flags & AVINDEX_KEYFRAME))
1341 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1343 if (m == nb_entries)
1348 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1350 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1351 wanted_timestamp, flags);
1354 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1355 int64_t target_ts, int flags)
1357 AVInputFormat *avif = s->iformat;
1358 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1359 int64_t ts_min, ts_max, ts;
1364 if (stream_index < 0)
1367 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1370 ts_min = AV_NOPTS_VALUE;
1371 pos_limit = -1; // GCC falsely says it may be uninitialized.
1373 st = s->streams[stream_index];
1374 if (st->index_entries) {
1377 /* FIXME: Whole function must be checked for non-keyframe entries in
1378 * index case, especially read_timestamp(). */
1379 index = av_index_search_timestamp(st, target_ts,
1380 flags | AVSEEK_FLAG_BACKWARD);
1381 index = FFMAX(index, 0);
1382 e = &st->index_entries[index];
1384 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1386 ts_min = e->timestamp;
1387 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1393 index = av_index_search_timestamp(st, target_ts,
1394 flags & ~AVSEEK_FLAG_BACKWARD);
1395 assert(index < st->nb_index_entries);
1397 e = &st->index_entries[index];
1398 assert(e->timestamp >= target_ts);
1400 ts_max = e->timestamp;
1401 pos_limit = pos_max - e->min_distance;
1402 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1403 " dts_max=%"PRId64"\n", pos_max, pos_limit, ts_max);
1407 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1408 ts_min, ts_max, flags, &ts, avif->read_timestamp);
1413 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1416 ff_update_cur_dts(s, st, ts);
1421 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1422 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1423 int64_t ts_min, int64_t ts_max,
1424 int flags, int64_t *ts_ret,
1425 int64_t (*read_timestamp)(struct AVFormatContext *, int,
1426 int64_t *, int64_t))
1429 int64_t start_pos, filesize;
1432 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1434 if (ts_min == AV_NOPTS_VALUE) {
1435 pos_min = s->data_offset;
1436 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1437 if (ts_min == AV_NOPTS_VALUE)
1441 if (ts_max == AV_NOPTS_VALUE) {
1443 filesize = avio_size(s->pb);
1444 pos_max = filesize - 1;
1447 ts_max = read_timestamp(s, stream_index, &pos_max,
1450 } while (ts_max == AV_NOPTS_VALUE && pos_max >= step);
1451 if (ts_max == AV_NOPTS_VALUE)
1455 int64_t tmp_pos = pos_max + 1;
1456 int64_t tmp_ts = read_timestamp(s, stream_index,
1457 &tmp_pos, INT64_MAX);
1458 if (tmp_ts == AV_NOPTS_VALUE)
1462 if (tmp_pos >= filesize)
1465 pos_limit = pos_max;
1468 if (ts_min > ts_max)
1470 else if (ts_min == ts_max)
1471 pos_limit = pos_min;
1474 while (pos_min < pos_limit) {
1475 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64
1476 " dts_max=%"PRId64"\n", pos_min, pos_max, ts_min, ts_max);
1477 assert(pos_limit <= pos_max);
1479 if (no_change == 0) {
1480 int64_t approximate_keyframe_distance = pos_max - pos_limit;
1481 // interpolate position (better than dichotomy)
1482 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
1484 pos_min - approximate_keyframe_distance;
1485 } else if (no_change == 1) {
1486 // bisection if interpolation did not change min / max pos last time
1487 pos = (pos_min + pos_limit) >> 1;
1489 /* linear search if bisection failed, can only happen if there
1490 * are very few or no keyframes between min/max */
1495 else if (pos > pos_limit)
1499 // May pass pos_limit instead of -1.
1500 ts = read_timestamp(s, stream_index, &pos, INT64_MAX);
1505 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64
1506 " target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1507 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1508 pos_limit, start_pos, no_change);
1509 if (ts == AV_NOPTS_VALUE) {
1510 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1513 assert(ts != AV_NOPTS_VALUE);
1514 if (target_ts <= ts) {
1515 pos_limit = start_pos - 1;
1519 if (target_ts >= ts) {
1525 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1526 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1528 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1530 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1531 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1532 pos, ts_min, target_ts, ts_max);
1537 static int seek_frame_byte(AVFormatContext *s, int stream_index,
1538 int64_t pos, int flags)
1540 int64_t pos_min, pos_max;
1542 pos_min = s->data_offset;
1543 pos_max = avio_size(s->pb) - 1;
1547 else if (pos > pos_max)
1550 avio_seek(s->pb, pos, SEEK_SET);
1555 static int seek_frame_generic(AVFormatContext *s, int stream_index,
1556 int64_t timestamp, int flags)
1563 st = s->streams[stream_index];
1565 index = av_index_search_timestamp(st, timestamp, flags);
1567 if (index < 0 && st->nb_index_entries &&
1568 timestamp < st->index_entries[0].timestamp)
1571 if (index < 0 || index == st->nb_index_entries - 1) {
1574 if (st->nb_index_entries) {
1575 assert(st->index_entries);
1576 ie = &st->index_entries[st->nb_index_entries - 1];
1577 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1579 ff_update_cur_dts(s, st, ie->timestamp);
1581 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1587 read_status = av_read_frame(s, &pkt);
1588 } while (read_status == AVERROR(EAGAIN));
1589 if (read_status < 0)
1591 av_free_packet(&pkt);
1592 if (stream_index == pkt.stream_index)
1593 if ((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1596 index = av_index_search_timestamp(st, timestamp, flags);
1601 ff_read_frame_flush(s);
1602 if (s->iformat->read_seek)
1603 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1605 ie = &st->index_entries[index];
1606 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1608 ff_update_cur_dts(s, st, ie->timestamp);
1613 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1614 int64_t timestamp, int flags)
1619 if (flags & AVSEEK_FLAG_BYTE) {
1620 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1622 ff_read_frame_flush(s);
1623 return seek_frame_byte(s, stream_index, timestamp, flags);
1626 if (stream_index < 0) {
1627 stream_index = av_find_default_stream_index(s);
1628 if (stream_index < 0)
1631 st = s->streams[stream_index];
1632 /* timestamp for default must be expressed in AV_TIME_BASE units */
1633 timestamp = av_rescale(timestamp, st->time_base.den,
1634 AV_TIME_BASE * (int64_t) st->time_base.num);
1637 /* first, we try the format specific seek */
1638 if (s->iformat->read_seek) {
1639 ff_read_frame_flush(s);
1640 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1646 if (s->iformat->read_timestamp &&
1647 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1648 ff_read_frame_flush(s);
1649 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1650 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1651 ff_read_frame_flush(s);
1652 return seek_frame_generic(s, stream_index, timestamp, flags);
1657 int av_seek_frame(AVFormatContext *s, int stream_index,
1658 int64_t timestamp, int flags)
1660 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1663 ret = queue_attached_pictures(s);
1668 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
1669 int64_t ts, int64_t max_ts, int flags)
1671 if (min_ts > ts || max_ts < ts)
1674 if (s->iformat->read_seek2) {
1676 ff_read_frame_flush(s);
1677 ret = s->iformat->read_seek2(s, stream_index, min_ts,
1681 ret = queue_attached_pictures(s);
1685 if (s->iformat->read_timestamp) {
1686 // try to seek via read_timestamp()
1689 // Fall back on old API if new is not implemented but old is.
1690 // Note the old API has somewhat different semantics.
1691 if (s->iformat->read_seek || 1)
1692 return av_seek_frame(s, stream_index, ts,
1693 flags | ((uint64_t) ts - min_ts >
1694 (uint64_t) max_ts - ts
1695 ? AVSEEK_FLAG_BACKWARD : 0));
1697 // try some generic seek like seek_frame_generic() but with new ts semantics
1700 /*******************************************************/
1703 * Return TRUE if the stream has accurate duration in any stream.
1705 * @return TRUE if the stream has accurate duration for at least one component.
1707 static int has_duration(AVFormatContext *ic)
1712 for (i = 0; i < ic->nb_streams; i++) {
1713 st = ic->streams[i];
1714 if (st->duration != AV_NOPTS_VALUE)
1717 if (ic->duration != AV_NOPTS_VALUE)
1723 * Estimate the stream timings from the one of each components.
1725 * Also computes the global bitrate if possible.
1727 static void update_stream_timings(AVFormatContext *ic)
1729 int64_t start_time, start_time1, end_time, end_time1;
1730 int64_t duration, duration1, filesize;
1734 start_time = INT64_MAX;
1735 end_time = INT64_MIN;
1736 duration = INT64_MIN;
1737 for (i = 0; i < ic->nb_streams; i++) {
1738 st = ic->streams[i];
1739 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1740 start_time1 = av_rescale_q(st->start_time, st->time_base,
1742 start_time = FFMIN(start_time, start_time1);
1743 if (st->duration != AV_NOPTS_VALUE) {
1744 end_time1 = start_time1 +
1745 av_rescale_q(st->duration, st->time_base,
1747 end_time = FFMAX(end_time, end_time1);
1750 if (st->duration != AV_NOPTS_VALUE) {
1751 duration1 = av_rescale_q(st->duration, st->time_base,
1753 duration = FFMAX(duration, duration1);
1756 if (start_time != INT64_MAX) {
1757 ic->start_time = start_time;
1758 if (end_time != INT64_MIN)
1759 duration = FFMAX(duration, end_time - start_time);
1761 if (duration != INT64_MIN) {
1762 ic->duration = duration;
1763 if (ic->pb && (filesize = avio_size(ic->pb)) > 0)
1764 /* compute the bitrate */
1765 ic->bit_rate = (double) filesize * 8.0 * AV_TIME_BASE /
1766 (double) ic->duration;
1770 static void fill_all_stream_timings(AVFormatContext *ic)
1775 update_stream_timings(ic);
1776 for (i = 0; i < ic->nb_streams; i++) {
1777 st = ic->streams[i];
1778 if (st->start_time == AV_NOPTS_VALUE) {
1779 if (ic->start_time != AV_NOPTS_VALUE)
1780 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
1782 if (ic->duration != AV_NOPTS_VALUE)
1783 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
1789 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1791 int64_t filesize, duration;
1795 /* if bit_rate is already set, we believe it */
1796 if (ic->bit_rate <= 0) {
1798 for (i = 0; i < ic->nb_streams; i++) {
1799 st = ic->streams[i];
1800 if (st->codec->bit_rate > 0) {
1801 if (INT_MAX - st->codec->bit_rate < bit_rate) {
1805 bit_rate += st->codec->bit_rate;
1808 ic->bit_rate = bit_rate;
1811 /* if duration is already set, we believe it */
1812 if (ic->duration == AV_NOPTS_VALUE &&
1813 ic->bit_rate != 0) {
1814 filesize = ic->pb ? avio_size(ic->pb) : 0;
1816 for (i = 0; i < ic->nb_streams; i++) {
1817 st = ic->streams[i];
1818 duration = av_rescale(8 * filesize, st->time_base.den,
1820 (int64_t) st->time_base.num);
1821 if (st->duration == AV_NOPTS_VALUE)
1822 st->duration = duration;
1828 #define DURATION_MAX_READ_SIZE 250000
1829 #define DURATION_MAX_RETRY 3
1831 /* only usable for MPEG-PS streams */
1832 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1834 AVPacket pkt1, *pkt = &pkt1;
1836 int read_size, i, ret;
1838 int64_t filesize, offset, duration;
1841 /* flush packet queue */
1842 flush_packet_queue(ic);
1844 for (i = 0; i < ic->nb_streams; i++) {
1845 st = ic->streams[i];
1846 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1847 av_log(st->codec, AV_LOG_WARNING,
1848 "start time is not set in estimate_timings_from_pts\n");
1851 av_parser_close(st->parser);
1856 /* estimate the end time (duration) */
1857 /* XXX: may need to support wrapping */
1858 filesize = ic->pb ? avio_size(ic->pb) : 0;
1859 end_time = AV_NOPTS_VALUE;
1861 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
1865 avio_seek(ic->pb, offset, SEEK_SET);
1868 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
1872 ret = ff_read_packet(ic, pkt);
1873 } while (ret == AVERROR(EAGAIN));
1876 read_size += pkt->size;
1877 st = ic->streams[pkt->stream_index];
1878 if (pkt->pts != AV_NOPTS_VALUE &&
1879 (st->start_time != AV_NOPTS_VALUE ||
1880 st->first_dts != AV_NOPTS_VALUE)) {
1881 duration = end_time = pkt->pts;
1882 if (st->start_time != AV_NOPTS_VALUE)
1883 duration -= st->start_time;
1885 duration -= st->first_dts;
1887 duration += 1LL << st->pts_wrap_bits;
1889 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1890 st->duration = duration;
1893 av_free_packet(pkt);
1895 } while (end_time == AV_NOPTS_VALUE &&
1896 filesize > (DURATION_MAX_READ_SIZE << retry) &&
1897 ++retry <= DURATION_MAX_RETRY);
1899 fill_all_stream_timings(ic);
1901 avio_seek(ic->pb, old_offset, SEEK_SET);
1902 for (i = 0; i < ic->nb_streams; i++) {
1903 st = ic->streams[i];
1904 st->cur_dts = st->first_dts;
1905 st->last_IP_pts = AV_NOPTS_VALUE;
1909 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1913 /* get the file size, if possible */
1914 if (ic->iformat->flags & AVFMT_NOFILE) {
1917 file_size = avio_size(ic->pb);
1918 file_size = FFMAX(0, file_size);
1921 if ((!strcmp(ic->iformat->name, "mpeg") ||
1922 !strcmp(ic->iformat->name, "mpegts")) &&
1923 file_size && ic->pb->seekable) {
1924 /* get accurate estimate from the PTSes */
1925 estimate_timings_from_pts(ic, old_offset);
1926 } else if (has_duration(ic)) {
1927 /* at least one component has timings - we use them for all
1929 fill_all_stream_timings(ic);
1931 av_log(ic, AV_LOG_WARNING,
1932 "Estimating duration from bitrate, this may be inaccurate\n");
1933 /* less precise: use bitrate info */
1934 estimate_timings_from_bit_rate(ic);
1936 update_stream_timings(ic);
1940 AVStream av_unused *st;
1941 for (i = 0; i < ic->nb_streams; i++) {
1942 st = ic->streams[i];
1943 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
1944 (double) st->start_time / AV_TIME_BASE,
1945 (double) st->duration / AV_TIME_BASE);
1948 "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1949 (double) ic->start_time / AV_TIME_BASE,
1950 (double) ic->duration / AV_TIME_BASE,
1951 ic->bit_rate / 1000);
1955 static int has_codec_parameters(AVStream *st)
1957 AVCodecContext *avctx = st->codec;
1960 switch (avctx->codec_type) {
1961 case AVMEDIA_TYPE_AUDIO:
1962 val = avctx->sample_rate && avctx->channels;
1963 if (st->info->found_decoder >= 0 &&
1964 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
1967 case AVMEDIA_TYPE_VIDEO:
1969 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
1976 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
1979 static int has_decode_delay_been_guessed(AVStream *st)
1981 return st->codec->codec_id != AV_CODEC_ID_H264 ||
1982 st->info->nb_decoded_frames >= 6;
1985 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
1986 static int try_decode_frame(AVStream *st, AVPacket *avpkt,
1987 AVDictionary **options)
1989 const AVCodec *codec;
1990 int got_picture = 1, ret = 0;
1991 AVFrame *frame = av_frame_alloc();
1992 AVPacket pkt = *avpkt;
1995 return AVERROR(ENOMEM);
1997 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
1998 AVDictionary *thread_opt = NULL;
2000 codec = st->codec->codec ? st->codec->codec
2001 : avcodec_find_decoder(st->codec->codec_id);
2004 st->info->found_decoder = -1;
2009 /* Force thread count to 1 since the H.264 decoder will not extract
2010 * SPS and PPS to extradata during multi-threaded decoding. */
2011 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2012 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2014 av_dict_free(&thread_opt);
2016 st->info->found_decoder = -1;
2019 st->info->found_decoder = 1;
2020 } else if (!st->info->found_decoder)
2021 st->info->found_decoder = 1;
2023 if (st->info->found_decoder < 0) {
2028 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2030 (!has_codec_parameters(st) || !has_decode_delay_been_guessed(st) ||
2031 (!st->codec_info_nb_frames &&
2032 st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2034 switch (st->codec->codec_type) {
2035 case AVMEDIA_TYPE_VIDEO:
2036 ret = avcodec_decode_video2(st->codec, frame,
2037 &got_picture, &pkt);
2039 case AVMEDIA_TYPE_AUDIO:
2040 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2047 st->info->nb_decoded_frames++;
2055 av_frame_free(&frame);
2059 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2061 while (tags->id != AV_CODEC_ID_NONE) {
2069 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2072 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2073 if (tag == tags[i].tag)
2075 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2076 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2078 return AV_CODEC_ID_NONE;
2081 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2086 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2088 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2090 return AV_CODEC_ID_NONE;
2094 if (sflags & (1 << (bps - 1))) {
2097 return AV_CODEC_ID_PCM_S8;
2099 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2101 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2103 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2105 return AV_CODEC_ID_NONE;
2110 return AV_CODEC_ID_PCM_U8;
2112 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2114 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2116 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2118 return AV_CODEC_ID_NONE;
2124 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2127 for (i = 0; tags && tags[i]; i++) {
2128 int tag = ff_codec_get_tag(tags[i], id);
2135 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2138 for (i = 0; tags && tags[i]; i++) {
2139 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2140 if (id != AV_CODEC_ID_NONE)
2143 return AV_CODEC_ID_NONE;
2146 static void compute_chapters_end(AVFormatContext *s)
2149 int64_t max_time = s->duration +
2150 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2152 for (i = 0; i < s->nb_chapters; i++)
2153 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2154 AVChapter *ch = s->chapters[i];
2155 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2159 for (j = 0; j < s->nb_chapters; j++) {
2160 AVChapter *ch1 = s->chapters[j];
2161 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2163 if (j != i && next_start > ch->start && next_start < end)
2166 ch->end = (end == INT64_MAX) ? ch->start : end;
2170 static int get_std_framerate(int i)
2173 return (i + 1) * 1001;
2175 return ((const int[]) { 24, 30, 60, 12, 15 })[i - 60 * 12] * 1000 * 12;
2178 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2180 int i, count, ret, read_size, j;
2182 AVPacket pkt1, *pkt;
2183 int64_t old_offset = avio_tell(ic->pb);
2184 // new streams might appear, no options for those
2185 int orig_nb_streams = ic->nb_streams;
2187 for (i = 0; i < ic->nb_streams; i++) {
2188 const AVCodec *codec;
2189 AVDictionary *thread_opt = NULL;
2190 st = ic->streams[i];
2192 // only for the split stuff
2193 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2194 st->parser = av_parser_init(st->codec->codec_id);
2195 if (st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser)
2196 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2198 codec = st->codec->codec ? st->codec->codec
2199 : avcodec_find_decoder(st->codec->codec_id);
2201 /* Force thread count to 1 since the H.264 decoder will not extract
2202 * SPS and PPS to extradata during multi-threaded decoding. */
2203 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2205 /* Ensure that subtitle_header is properly set. */
2206 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2207 && codec && !st->codec->codec)
2208 avcodec_open2(st->codec, codec,
2209 options ? &options[i] : &thread_opt);
2211 // Try to just open decoders, in case this is enough to get parameters.
2212 if (!has_codec_parameters(st)) {
2213 if (codec && !st->codec->codec)
2214 avcodec_open2(st->codec, codec,
2215 options ? &options[i] : &thread_opt);
2218 av_dict_free(&thread_opt);
2221 for (i = 0; i < ic->nb_streams; i++) {
2222 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2223 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2229 if (ff_check_interrupt(&ic->interrupt_callback)) {
2231 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2235 /* check if one codec still needs to be handled */
2236 for (i = 0; i < ic->nb_streams; i++) {
2237 int fps_analyze_framecount = 20;
2239 st = ic->streams[i];
2240 if (!has_codec_parameters(st))
2242 /* If the timebase is coarse (like the usual millisecond precision
2243 * of mkv), we need to analyze more frames to reliably arrive at
2244 * the correct fps. */
2245 if (av_q2d(st->time_base) > 0.0005)
2246 fps_analyze_framecount *= 2;
2247 if (ic->fps_probe_size >= 0)
2248 fps_analyze_framecount = ic->fps_probe_size;
2249 /* variable fps and no guess at the real fps */
2250 if (!st->avg_frame_rate.num &&
2251 st->codec_info_nb_frames < fps_analyze_framecount &&
2252 st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2254 if (st->parser && st->parser->parser->split &&
2255 !st->codec->extradata)
2257 if (st->first_dts == AV_NOPTS_VALUE &&
2258 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2259 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2262 if (i == ic->nb_streams) {
2263 /* NOTE: If the format has no header, then we need to read some
2264 * packets to get most of the streams, so we cannot stop here. */
2265 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2266 /* If we found the info for all the codecs, we can stop. */
2268 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2272 /* We did not get all the codec info, but we read too much data. */
2273 if (read_size >= ic->probesize) {
2275 av_log(ic, AV_LOG_DEBUG,
2276 "Probe buffer size limit %d reached\n", ic->probesize);
2280 /* NOTE: A new stream can be added there if no header in file
2281 * (AVFMTCTX_NOHEADER). */
2282 ret = read_frame_internal(ic, &pkt1);
2283 if (ret == AVERROR(EAGAIN))
2288 AVPacket empty_pkt = { 0 };
2290 av_init_packet(&empty_pkt);
2292 /* We could not have all the codec parameters before EOF. */
2294 for (i = 0; i < ic->nb_streams; i++) {
2295 st = ic->streams[i];
2297 /* flush the decoders */
2298 if (st->info->found_decoder == 1) {
2300 err = try_decode_frame(st, &empty_pkt,
2301 (options && i < orig_nb_streams)
2302 ? &options[i] : NULL);
2303 } while (err > 0 && !has_codec_parameters(st));
2307 av_log(ic, AV_LOG_WARNING,
2308 "decoding for stream %d failed\n", st->index);
2309 } else if (!has_codec_parameters(st)) {
2311 avcodec_string(buf, sizeof(buf), st->codec, 0);
2312 av_log(ic, AV_LOG_WARNING,
2313 "Could not find codec parameters (%s)\n", buf);
2321 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2324 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2325 &ic->packet_buffer_end);
2326 if ((ret = av_dup_packet(pkt)) < 0)
2327 goto find_stream_info_err;
2330 read_size += pkt->size;
2332 st = ic->streams[pkt->stream_index];
2333 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2334 /* check for non-increasing dts */
2335 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2336 st->info->fps_last_dts >= pkt->dts) {
2337 av_log(ic, AV_LOG_WARNING,
2338 "Non-increasing DTS in stream %d: packet %d with DTS "
2339 "%"PRId64", packet %d with DTS %"PRId64"\n",
2340 st->index, st->info->fps_last_dts_idx,
2341 st->info->fps_last_dts, st->codec_info_nb_frames,
2343 st->info->fps_first_dts =
2344 st->info->fps_last_dts = AV_NOPTS_VALUE;
2346 /* Check for a discontinuity in dts. If the difference in dts
2347 * is more than 1000 times the average packet duration in the
2348 * sequence, we treat it as a discontinuity. */
2349 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2350 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2351 (pkt->dts - st->info->fps_last_dts) / 1000 >
2352 (st->info->fps_last_dts - st->info->fps_first_dts) /
2353 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2354 av_log(ic, AV_LOG_WARNING,
2355 "DTS discontinuity in stream %d: packet %d with DTS "
2356 "%"PRId64", packet %d with DTS %"PRId64"\n",
2357 st->index, st->info->fps_last_dts_idx,
2358 st->info->fps_last_dts, st->codec_info_nb_frames,
2360 st->info->fps_first_dts =
2361 st->info->fps_last_dts = AV_NOPTS_VALUE;
2364 /* update stored dts values */
2365 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2366 st->info->fps_first_dts = pkt->dts;
2367 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2369 st->info->fps_last_dts = pkt->dts;
2370 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2372 /* check max_analyze_duration */
2373 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2374 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2375 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached\n",
2376 ic->max_analyze_duration);
2380 if (st->parser && st->parser->parser->split && !st->codec->extradata) {
2381 int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
2382 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2383 st->codec->extradata_size = i;
2384 st->codec->extradata = av_malloc(st->codec->extradata_size +
2385 FF_INPUT_BUFFER_PADDING_SIZE);
2386 if (!st->codec->extradata)
2387 return AVERROR(ENOMEM);
2388 memcpy(st->codec->extradata, pkt->data,
2389 st->codec->extradata_size);
2390 memset(st->codec->extradata + i, 0,
2391 FF_INPUT_BUFFER_PADDING_SIZE);
2395 /* If still no information, we try to open the codec and to
2396 * decompress the frame. We try to avoid that in most cases as
2397 * it takes longer and uses more memory. For MPEG-4, we need to
2398 * decompress for QuickTime.
2400 * If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2401 * least one frame of codec data, this makes sure the codec initializes
2402 * the channel configuration and does not only trust the values from
2404 try_decode_frame(st, pkt,
2405 (options && i < orig_nb_streams) ? &options[i] : NULL);
2407 st->codec_info_nb_frames++;
2411 // close codecs which were opened in try_decode_frame()
2412 for (i = 0; i < ic->nb_streams; i++) {
2413 st = ic->streams[i];
2414 avcodec_close(st->codec);
2416 for (i = 0; i < ic->nb_streams; i++) {
2417 st = ic->streams[i];
2418 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2419 /* estimate average framerate if not set by demuxer */
2420 if (!st->avg_frame_rate.num &&
2421 st->info->fps_last_dts != st->info->fps_first_dts) {
2422 int64_t delta_dts = st->info->fps_last_dts -
2423 st->info->fps_first_dts;
2424 int delta_packets = st->info->fps_last_dts_idx -
2425 st->info->fps_first_dts_idx;
2427 double best_error = 0.01;
2429 if (delta_dts >= INT64_MAX / st->time_base.num ||
2430 delta_packets >= INT64_MAX / st->time_base.den ||
2433 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2434 delta_packets * (int64_t) st->time_base.den,
2435 delta_dts * (int64_t) st->time_base.num, 60000);
2437 /* Round guessed framerate to a "standard" framerate if it's
2438 * within 1% of the original estimate. */
2439 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
2440 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
2441 double error = fabs(av_q2d(st->avg_frame_rate) /
2442 av_q2d(std_fps) - 1);
2444 if (error < best_error) {
2446 best_fps = std_fps.num;
2450 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2451 best_fps, 12 * 1001, INT_MAX);
2453 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2454 if (!st->codec->bits_per_coded_sample)
2455 st->codec->bits_per_coded_sample =
2456 av_get_bits_per_sample(st->codec->codec_id);
2457 // set stream disposition based on audio service type
2458 switch (st->codec->audio_service_type) {
2459 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2460 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
2462 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2463 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
2465 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2466 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
2468 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2469 st->disposition = AV_DISPOSITION_COMMENT;
2471 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2472 st->disposition = AV_DISPOSITION_KARAOKE;
2478 estimate_timings(ic, old_offset);
2480 compute_chapters_end(ic);
2482 find_stream_info_err:
2483 for (i = 0; i < ic->nb_streams; i++) {
2484 ic->streams[i]->codec->thread_count = 0;
2485 av_freep(&ic->streams[i]->info);
2490 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2494 for (i = 0; i < ic->nb_programs; i++)
2495 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2496 if (ic->programs[i]->stream_index[j] == s)
2497 return ic->programs[i];
2501 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
2502 int wanted_stream_nb, int related_stream,
2503 AVCodec **decoder_ret, int flags)
2505 int i, nb_streams = ic->nb_streams;
2506 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2507 unsigned *program = NULL;
2508 AVCodec *decoder = NULL, *best_decoder = NULL;
2510 if (related_stream >= 0 && wanted_stream_nb < 0) {
2511 AVProgram *p = find_program_from_stream(ic, related_stream);
2513 program = p->stream_index;
2514 nb_streams = p->nb_stream_indexes;
2517 for (i = 0; i < nb_streams; i++) {
2518 int real_stream_index = program ? program[i] : i;
2519 AVStream *st = ic->streams[real_stream_index];
2520 AVCodecContext *avctx = st->codec;
2521 if (avctx->codec_type != type)
2523 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2525 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
2526 AV_DISPOSITION_VISUAL_IMPAIRED))
2529 decoder = avcodec_find_decoder(st->codec->codec_id);
2532 ret = AVERROR_DECODER_NOT_FOUND;
2536 if (best_count >= st->codec_info_nb_frames)
2538 best_count = st->codec_info_nb_frames;
2539 ret = real_stream_index;
2540 best_decoder = decoder;
2541 if (program && i == nb_streams - 1 && ret < 0) {
2543 nb_streams = ic->nb_streams;
2544 /* no related stream found, try again with everything */
2549 *decoder_ret = best_decoder;
2553 /*******************************************************/
2555 int av_read_play(AVFormatContext *s)
2557 if (s->iformat->read_play)
2558 return s->iformat->read_play(s);
2560 return avio_pause(s->pb, 0);
2561 return AVERROR(ENOSYS);
2564 int av_read_pause(AVFormatContext *s)
2566 if (s->iformat->read_pause)
2567 return s->iformat->read_pause(s);
2569 return avio_pause(s->pb, 1);
2570 return AVERROR(ENOSYS);
2573 void avformat_free_context(AVFormatContext *s)
2579 if (s->iformat && s->iformat->priv_class && s->priv_data)
2580 av_opt_free(s->priv_data);
2582 for (i = 0; i < s->nb_streams; i++) {
2583 /* free all data in a stream component */
2586 for (j = 0; j < st->nb_side_data; j++)
2587 av_freep(&st->side_data[j].data);
2588 av_freep(&st->side_data);
2589 st->nb_side_data = 0;
2592 av_parser_close(st->parser);
2594 if (st->attached_pic.data)
2595 av_free_packet(&st->attached_pic);
2596 av_dict_free(&st->metadata);
2597 av_freep(&st->probe_data.buf);
2598 av_free(st->index_entries);
2599 av_free(st->codec->extradata);
2600 av_free(st->codec->subtitle_header);
2602 av_free(st->priv_data);
2606 for (i = s->nb_programs - 1; i >= 0; i--) {
2607 av_dict_free(&s->programs[i]->metadata);
2608 av_freep(&s->programs[i]->stream_index);
2609 av_freep(&s->programs[i]);
2611 av_freep(&s->programs);
2612 av_freep(&s->priv_data);
2613 while (s->nb_chapters--) {
2614 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2615 av_free(s->chapters[s->nb_chapters]);
2617 av_freep(&s->chapters);
2618 av_dict_free(&s->metadata);
2619 av_freep(&s->streams);
2620 av_freep(&s->internal);
2624 void avformat_close_input(AVFormatContext **ps)
2626 AVFormatContext *s = *ps;
2627 AVIOContext *pb = s->pb;
2629 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2630 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2633 flush_packet_queue(s);
2636 if (s->iformat->read_close)
2637 s->iformat->read_close(s);
2639 avformat_free_context(s);
2646 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2651 if (av_reallocp_array(&s->streams, s->nb_streams + 1,
2652 sizeof(*s->streams)) < 0) {
2657 st = av_mallocz(sizeof(AVStream));
2660 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2665 st->codec = avcodec_alloc_context3(c);
2667 /* no default bitrate if decoding */
2668 st->codec->bit_rate = 0;
2669 st->index = s->nb_streams;
2670 st->start_time = AV_NOPTS_VALUE;
2671 st->duration = AV_NOPTS_VALUE;
2672 /* we set the current DTS to 0 so that formats without any timestamps
2673 * but durations get some timestamps, formats with some unknown
2674 * timestamps have their first few packets buffered and the
2675 * timestamps corrected before they are returned to the user */
2677 st->first_dts = AV_NOPTS_VALUE;
2678 st->probe_packets = MAX_PROBE_PACKETS;
2680 /* default pts setting is MPEG-like */
2681 avpriv_set_pts_info(st, 33, 1, 90000);
2682 st->last_IP_pts = AV_NOPTS_VALUE;
2683 for (i = 0; i < MAX_REORDER_DELAY + 1; i++)
2684 st->pts_buffer[i] = AV_NOPTS_VALUE;
2686 st->sample_aspect_ratio = (AVRational) { 0, 1 };
2688 st->info->fps_first_dts = AV_NOPTS_VALUE;
2689 st->info->fps_last_dts = AV_NOPTS_VALUE;
2691 s->streams[s->nb_streams++] = st;
2695 AVProgram *av_new_program(AVFormatContext *ac, int id)
2697 AVProgram *program = NULL;
2700 av_dlog(ac, "new_program: id=0x%04x\n", id);
2702 for (i = 0; i < ac->nb_programs; i++)
2703 if (ac->programs[i]->id == id)
2704 program = ac->programs[i];
2707 program = av_mallocz(sizeof(AVProgram));
2710 dynarray_add(&ac->programs, &ac->nb_programs, program);
2711 program->discard = AVDISCARD_NONE;
2718 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base,
2719 int64_t start, int64_t end, const char *title)
2721 AVChapter *chapter = NULL;
2724 for (i = 0; i < s->nb_chapters; i++)
2725 if (s->chapters[i]->id == id)
2726 chapter = s->chapters[i];
2729 chapter = av_mallocz(sizeof(AVChapter));
2732 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2734 av_dict_set(&chapter->metadata, "title", title, 0);
2736 chapter->time_base = time_base;
2737 chapter->start = start;
2743 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
2746 AVProgram *program = NULL;
2748 if (idx >= ac->nb_streams) {
2749 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2753 for (i = 0; i < ac->nb_programs; i++) {
2754 if (ac->programs[i]->id != progid)
2756 program = ac->programs[i];
2757 for (j = 0; j < program->nb_stream_indexes; j++)
2758 if (program->stream_index[j] == idx)
2761 if (av_reallocp_array(&program->stream_index,
2762 program->nb_stream_indexes + 1,
2763 sizeof(*program->stream_index)) < 0) {
2764 program->nb_stream_indexes = 0;
2767 program->stream_index[program->nb_stream_indexes++] = idx;
2772 static void print_fps(double d, const char *postfix)
2774 uint64_t v = lrintf(d * 100);
2776 av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2777 else if (v % (100 * 1000))
2778 av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2780 av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d / 1000, postfix);
2783 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2785 if (m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))) {
2786 AVDictionaryEntry *tag = NULL;
2788 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2789 while ((tag = av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX)))
2790 if (strcmp("language", tag->key))
2791 av_log(ctx, AV_LOG_INFO,
2792 "%s %-16s: %s\n", indent, tag->key, tag->value);
2796 /* "user interface" functions */
2797 static void dump_stream_format(AVFormatContext *ic, int i,
2798 int index, int is_output)
2801 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2802 AVStream *st = ic->streams[i];
2803 int g = av_gcd(st->time_base.num, st->time_base.den);
2804 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2805 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2806 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2807 /* the pid is an important information, so we display it */
2808 /* XXX: add a generic system */
2809 if (flags & AVFMT_SHOW_IDS)
2810 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2812 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2813 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames,
2814 st->time_base.num / g, st->time_base.den / g);
2815 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2816 if (st->sample_aspect_ratio.num && // default
2817 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2818 AVRational display_aspect_ratio;
2819 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2820 st->codec->width * st->sample_aspect_ratio.num,
2821 st->codec->height * st->sample_aspect_ratio.den,
2823 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2824 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2825 display_aspect_ratio.num, display_aspect_ratio.den);
2827 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2828 if (st->avg_frame_rate.den && st->avg_frame_rate.num)
2829 print_fps(av_q2d(st->avg_frame_rate), "fps");
2830 if (st->time_base.den && st->time_base.num)
2831 print_fps(1 / av_q2d(st->time_base), "tbn");
2832 if (st->codec->time_base.den && st->codec->time_base.num)
2833 print_fps(1 / av_q2d(st->codec->time_base), "tbc");
2835 if (st->disposition & AV_DISPOSITION_DEFAULT)
2836 av_log(NULL, AV_LOG_INFO, " (default)");
2837 if (st->disposition & AV_DISPOSITION_DUB)
2838 av_log(NULL, AV_LOG_INFO, " (dub)");
2839 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2840 av_log(NULL, AV_LOG_INFO, " (original)");
2841 if (st->disposition & AV_DISPOSITION_COMMENT)
2842 av_log(NULL, AV_LOG_INFO, " (comment)");
2843 if (st->disposition & AV_DISPOSITION_LYRICS)
2844 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2845 if (st->disposition & AV_DISPOSITION_KARAOKE)
2846 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2847 if (st->disposition & AV_DISPOSITION_FORCED)
2848 av_log(NULL, AV_LOG_INFO, " (forced)");
2849 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2850 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2851 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2852 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2853 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2854 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2855 av_log(NULL, AV_LOG_INFO, "\n");
2856 dump_metadata(NULL, st->metadata, " ");
2859 void av_dump_format(AVFormatContext *ic, int index,
2860 const char *url, int is_output)
2863 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2864 if (ic->nb_streams && !printed)
2867 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2868 is_output ? "Output" : "Input",
2870 is_output ? ic->oformat->name : ic->iformat->name,
2871 is_output ? "to" : "from", url);
2872 dump_metadata(NULL, ic->metadata, " ");
2874 av_log(NULL, AV_LOG_INFO, " Duration: ");
2875 if (ic->duration != AV_NOPTS_VALUE) {
2876 int hours, mins, secs, us;
2877 secs = ic->duration / AV_TIME_BASE;
2878 us = ic->duration % AV_TIME_BASE;
2883 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2884 (100 * us) / AV_TIME_BASE);
2886 av_log(NULL, AV_LOG_INFO, "N/A");
2888 if (ic->start_time != AV_NOPTS_VALUE) {
2890 av_log(NULL, AV_LOG_INFO, ", start: ");
2891 secs = ic->start_time / AV_TIME_BASE;
2892 us = abs(ic->start_time % AV_TIME_BASE);
2893 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2894 secs, (int) av_rescale(us, 1000000, AV_TIME_BASE));
2896 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2898 av_log(NULL, AV_LOG_INFO, "%d kb/s", ic->bit_rate / 1000);
2900 av_log(NULL, AV_LOG_INFO, "N/A");
2901 av_log(NULL, AV_LOG_INFO, "\n");
2903 for (i = 0; i < ic->nb_chapters; i++) {
2904 AVChapter *ch = ic->chapters[i];
2905 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2906 av_log(NULL, AV_LOG_INFO,
2907 "start %f, ", ch->start * av_q2d(ch->time_base));
2908 av_log(NULL, AV_LOG_INFO,
2909 "end %f\n", ch->end * av_q2d(ch->time_base));
2911 dump_metadata(NULL, ch->metadata, " ");
2913 if (ic->nb_programs) {
2914 int j, k, total = 0;
2915 for (j = 0; j < ic->nb_programs; j++) {
2916 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2918 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2919 name ? name->value : "");
2920 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2921 for (k = 0; k < ic->programs[j]->nb_stream_indexes; k++) {
2922 dump_stream_format(ic, ic->programs[j]->stream_index[k],
2924 printed[ic->programs[j]->stream_index[k]] = 1;
2926 total += ic->programs[j]->nb_stream_indexes;
2928 if (total < ic->nb_streams)
2929 av_log(NULL, AV_LOG_INFO, " No Program\n");
2931 for (i = 0; i < ic->nb_streams; i++)
2933 dump_stream_format(ic, i, index, is_output);
2938 uint64_t ff_ntp_time(void)
2940 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
2943 int av_get_frame_filename(char *buf, int buf_size, const char *path, int number)
2946 char *q, buf1[20], c;
2947 int nd, len, percentd_found;
2959 while (av_isdigit(*p))
2960 nd = nd * 10 + *p++ - '0';
2962 } while (av_isdigit(c));
2971 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2973 if ((q - buf + len) > buf_size - 1)
2975 memcpy(q, buf1, len);
2983 if ((q - buf) < buf_size - 1)
2987 if (!percentd_found)
2996 #define HEXDUMP_PRINT(...) \
2999 av_log(avcl, level, __VA_ARGS__); \
3001 fprintf(f, __VA_ARGS__); \
3004 static void hex_dump_internal(void *avcl, FILE *f, int level,
3005 const uint8_t *buf, int size)
3009 for (i = 0; i < size; i += 16) {
3013 HEXDUMP_PRINT("%08x ", i);
3014 for (j = 0; j < 16; j++) {
3016 HEXDUMP_PRINT(" %02x", buf[i + j]);
3021 for (j = 0; j < len; j++) {
3023 if (c < ' ' || c > '~')
3025 HEXDUMP_PRINT("%c", c);
3027 HEXDUMP_PRINT("\n");
3031 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3033 hex_dump_internal(NULL, f, 0, buf, size);
3036 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3038 hex_dump_internal(avcl, NULL, level, buf, size);
3041 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt,
3042 int dump_payload, AVRational time_base)
3044 HEXDUMP_PRINT("stream #%d:\n", pkt->stream_index);
3045 HEXDUMP_PRINT(" keyframe=%d\n", (pkt->flags & AV_PKT_FLAG_KEY) != 0);
3046 HEXDUMP_PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3047 /* DTS is _always_ valid after av_read_frame() */
3048 HEXDUMP_PRINT(" dts=");
3049 if (pkt->dts == AV_NOPTS_VALUE)
3050 HEXDUMP_PRINT("N/A");
3052 HEXDUMP_PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3053 /* PTS may not be known if B-frames are present. */
3054 HEXDUMP_PRINT(" pts=");
3055 if (pkt->pts == AV_NOPTS_VALUE)
3056 HEXDUMP_PRINT("N/A");
3058 HEXDUMP_PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3059 HEXDUMP_PRINT("\n");
3060 HEXDUMP_PRINT(" size=%d\n", pkt->size);
3062 av_hex_dump(f, pkt->data, pkt->size);
3065 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3067 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3070 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3073 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3076 void av_url_split(char *proto, int proto_size,
3077 char *authorization, int authorization_size,
3078 char *hostname, int hostname_size,
3079 int *port_ptr, char *path, int path_size, const char *url)
3081 const char *p, *ls, *at, *col, *brk;
3087 if (authorization_size > 0)
3088 authorization[0] = 0;
3089 if (hostname_size > 0)
3094 /* parse protocol */
3095 if ((p = strchr(url, ':'))) {
3096 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3103 /* no protocol means plain filename */
3104 av_strlcpy(path, url, path_size);
3108 /* separate path from hostname */
3109 ls = strchr(p, '/');
3111 ls = strchr(p, '?');
3113 av_strlcpy(path, ls, path_size);
3115 ls = &p[strlen(p)]; // XXX
3117 /* the rest is hostname, use that to parse auth/port */
3119 /* authorization (user[:pass]@hostname) */
3120 if ((at = strchr(p, '@')) && at < ls) {
3121 av_strlcpy(authorization, p,
3122 FFMIN(authorization_size, at + 1 - p));
3123 p = at + 1; /* skip '@' */
3126 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3128 av_strlcpy(hostname, p + 1,
3129 FFMIN(hostname_size, brk - p));
3130 if (brk[1] == ':' && port_ptr)
3131 *port_ptr = atoi(brk + 2);
3132 } else if ((col = strchr(p, ':')) && col < ls) {
3133 av_strlcpy(hostname, p,
3134 FFMIN(col + 1 - p, hostname_size));
3136 *port_ptr = atoi(col + 1);
3138 av_strlcpy(hostname, p,
3139 FFMIN(ls + 1 - p, hostname_size));
3143 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3146 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3149 'C', 'D', 'E', 'F' };
3150 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3153 'c', 'd', 'e', 'f' };
3154 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3156 for (i = 0; i < s; i++) {
3157 buff[i * 2] = hex_table[src[i] >> 4];
3158 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3164 int ff_hex_to_data(uint8_t *data, const char *p)
3171 p += strspn(p, SPACE_CHARS);
3174 c = av_toupper((unsigned char) *p++);
3175 if (c >= '0' && c <= '9')
3177 else if (c >= 'A' && c <= 'F')
3192 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3193 unsigned int pts_num, unsigned int pts_den)
3196 if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
3197 if (new_tb.num != pts_num)
3198 av_log(NULL, AV_LOG_DEBUG,
3199 "st:%d removing common factor %d from timebase\n",
3200 s->index, pts_num / new_tb.num);
3202 av_log(NULL, AV_LOG_WARNING,
3203 "st:%d has too large timebase, reducing\n", s->index);
3205 if (new_tb.num <= 0 || new_tb.den <= 0) {
3206 av_log(NULL, AV_LOG_ERROR,
3207 "Ignoring attempt to set invalid timebase for st:%d\n",
3211 s->time_base = new_tb;
3212 s->pts_wrap_bits = pts_wrap_bits;
3215 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3218 const char *ptr = str;
3220 /* Parse key=value pairs. */
3223 char *dest = NULL, *dest_end;
3224 int key_len, dest_len = 0;
3226 /* Skip whitespace and potential commas. */
3227 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3234 if (!(ptr = strchr(key, '=')))
3237 key_len = ptr - key;
3239 callback_get_buf(context, key, key_len, &dest, &dest_len);
3240 dest_end = dest + dest_len - 1;
3244 while (*ptr && *ptr != '\"') {
3248 if (dest && dest < dest_end)
3252 if (dest && dest < dest_end)
3260 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3261 if (dest && dest < dest_end)
3269 int ff_find_stream_index(AVFormatContext *s, int id)
3272 for (i = 0; i < s->nb_streams; i++)
3273 if (s->streams[i]->id == id)
3278 int64_t ff_iso8601_to_unix_time(const char *datestr)
3281 struct tm time1 = { 0 }, time2 = { 0 };
3283 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3284 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3286 return av_timegm(&time2);
3288 return av_timegm(&time1);
3290 av_log(NULL, AV_LOG_WARNING,
3291 "strptime() unavailable on this system, cannot convert "
3292 "the date string.\n");
3297 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id,
3301 if (ofmt->query_codec)
3302 return ofmt->query_codec(codec_id, std_compliance);
3303 else if (ofmt->codec_tag)
3304 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3305 else if (codec_id == ofmt->video_codec ||
3306 codec_id == ofmt->audio_codec ||
3307 codec_id == ofmt->subtitle_codec)
3310 return AVERROR_PATCHWELCOME;
3313 int avformat_network_init(void)
3317 ff_network_inited_globally = 1;
3318 if ((ret = ff_network_init()) < 0)
3325 int avformat_network_deinit(void)
3334 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3335 uint64_t channel_layout, int32_t sample_rate,
3336 int32_t width, int32_t height)
3342 return AVERROR(EINVAL);
3345 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3347 if (channel_layout) {
3349 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3353 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3355 if (width || height) {
3357 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3359 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3361 return AVERROR(ENOMEM);
3362 bytestream_put_le32(&data, flags);
3364 bytestream_put_le32(&data, channels);
3366 bytestream_put_le64(&data, channel_layout);
3368 bytestream_put_le32(&data, sample_rate);
3369 if (width || height) {
3370 bytestream_put_le32(&data, width);
3371 bytestream_put_le32(&data, height);
3376 int ff_generate_avci_extradata(AVStream *st)
3378 static const uint8_t avci100_1080p_extradata[] = {
3380 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3381 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
3382 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
3383 0x18, 0x21, 0x02, 0x56, 0xb9, 0x3d, 0x7d, 0x7e,
3384 0x4f, 0xe3, 0x3f, 0x11, 0xf1, 0x9e, 0x08, 0xb8,
3385 0x8c, 0x54, 0x43, 0xc0, 0x78, 0x02, 0x27, 0xe2,
3386 0x70, 0x1e, 0x30, 0x10, 0x10, 0x14, 0x00, 0x00,
3387 0x03, 0x00, 0x04, 0x00, 0x00, 0x03, 0x00, 0xca,
3388 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3390 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
3393 static const uint8_t avci100_1080i_extradata[] = {
3395 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3396 0xb6, 0xd4, 0x20, 0x22, 0x33, 0x19, 0xc6, 0x63,
3397 0x23, 0x21, 0x01, 0x11, 0x98, 0xce, 0x33, 0x19,
3398 0x18, 0x21, 0x03, 0x3a, 0x46, 0x65, 0x6a, 0x65,
3399 0x24, 0xad, 0xe9, 0x12, 0x32, 0x14, 0x1a, 0x26,
3400 0x34, 0xad, 0xa4, 0x41, 0x82, 0x23, 0x01, 0x50,
3401 0x2b, 0x1a, 0x24, 0x69, 0x48, 0x30, 0x40, 0x2e,
3402 0x11, 0x12, 0x08, 0xc6, 0x8c, 0x04, 0x41, 0x28,
3403 0x4c, 0x34, 0xf0, 0x1e, 0x01, 0x13, 0xf2, 0xe0,
3404 0x3c, 0x60, 0x20, 0x20, 0x28, 0x00, 0x00, 0x03,
3405 0x00, 0x08, 0x00, 0x00, 0x03, 0x01, 0x94, 0x00,
3407 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x33, 0x48,
3410 static const uint8_t avci50_1080i_extradata[] = {
3412 0x00, 0x00, 0x00, 0x01, 0x67, 0x6e, 0x10, 0x28,
3413 0xa6, 0xd4, 0x20, 0x32, 0x33, 0x0c, 0x71, 0x18,
3414 0x88, 0x62, 0x10, 0x19, 0x19, 0x86, 0x38, 0x8c,
3415 0x44, 0x30, 0x21, 0x02, 0x56, 0x4e, 0x6e, 0x61,
3416 0x87, 0x3e, 0x73, 0x4d, 0x98, 0x0c, 0x03, 0x06,
3417 0x9c, 0x0b, 0x73, 0xe6, 0xc0, 0xb5, 0x18, 0x63,
3418 0x0d, 0x39, 0xe0, 0x5b, 0x02, 0xd4, 0xc6, 0x19,
3419 0x1a, 0x79, 0x8c, 0x32, 0x34, 0x24, 0xf0, 0x16,
3420 0x81, 0x13, 0xf7, 0xff, 0x80, 0x01, 0x80, 0x02,
3421 0x71, 0x80, 0x80, 0x80, 0xa0, 0x00, 0x00, 0x03,
3422 0x00, 0x20, 0x00, 0x00, 0x06, 0x50, 0x80, 0x00,
3424 0x00, 0x00, 0x00, 0x01, 0x68, 0xee, 0x31, 0x12,
3427 static const uint8_t avci100_720p_extradata[] = {
3429 0x00, 0x00, 0x00, 0x01, 0x67, 0x7a, 0x10, 0x29,
3430 0xb6, 0xd4, 0x20, 0x2a, 0x33, 0x1d, 0xc7, 0x62,
3431 0xa1, 0x08, 0x40, 0x54, 0x66, 0x3b, 0x8e, 0xc5,
3432 0x42, 0x02, 0x10, 0x25, 0x64, 0x2c, 0x89, 0xe8,
3433 0x85, 0xe4, 0x21, 0x4b, 0x90, 0x83, 0x06, 0x95,
3434 0xd1, 0x06, 0x46, 0x97, 0x20, 0xc8, 0xd7, 0x43,
3435 0x08, 0x11, 0xc2, 0x1e, 0x4c, 0x91, 0x0f, 0x01,
3436 0x40, 0x16, 0xec, 0x07, 0x8c, 0x04, 0x04, 0x05,
3437 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03,
3438 0x00, 0x64, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00,
3440 0x00, 0x00, 0x00, 0x01, 0x68, 0xce, 0x31, 0x12,
3444 const uint8_t *data = NULL;
3447 if (st->codec->width == 1920) {
3448 if (st->codec->field_order == AV_FIELD_PROGRESSIVE) {
3449 data = avci100_1080p_extradata;
3450 size = sizeof(avci100_1080p_extradata);
3452 data = avci100_1080i_extradata;
3453 size = sizeof(avci100_1080i_extradata);
3455 } else if (st->codec->width == 1440) {
3456 data = avci50_1080i_extradata;
3457 size = sizeof(avci50_1080i_extradata);
3458 } else if (st->codec->width == 1280) {
3459 data = avci100_720p_extradata;
3460 size = sizeof(avci100_720p_extradata);
3466 av_freep(&st->codec->extradata);
3467 st->codec->extradata_size = 0;
3468 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
3469 if (!st->codec->extradata)
3470 return AVERROR(ENOMEM);
3472 memcpy(st->codec->extradata, data, size);
3473 st->codec->extradata_size = size;