2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/dict.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/time.h"
38 #include "libavutil/timestamp.h"
40 #include "libavcodec/bytestream.h"
41 #include "libavcodec/internal.h"
42 #include "libavcodec/raw.h"
44 #include "audiointerleave.h"
46 #include "avio_internal.h"
58 * various utility functions for use within FFmpeg
61 unsigned avformat_version(void)
63 av_assert0(LIBAVFORMAT_VERSION_MICRO >= 100);
64 return LIBAVFORMAT_VERSION_INT;
67 const char *avformat_configuration(void)
69 return FFMPEG_CONFIGURATION;
72 const char *avformat_license(void)
74 #define LICENSE_PREFIX "libavformat license: "
75 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
78 #define RELATIVE_TS_BASE (INT64_MAX - (1LL<<48))
80 static int is_relative(int64_t ts) {
81 return ts > (RELATIVE_TS_BASE - (1LL<<48));
85 * Wrap a given time stamp, if there is an indication for an overflow
88 * @param timestamp the time stamp to wrap
89 * @return resulting time stamp
91 static int64_t wrap_timestamp(AVStream *st, int64_t timestamp)
93 if (st->pts_wrap_behavior != AV_PTS_WRAP_IGNORE &&
94 st->pts_wrap_reference != AV_NOPTS_VALUE && timestamp != AV_NOPTS_VALUE) {
95 if (st->pts_wrap_behavior == AV_PTS_WRAP_ADD_OFFSET &&
96 timestamp < st->pts_wrap_reference)
97 return timestamp + (1ULL << st->pts_wrap_bits);
98 else if (st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET &&
99 timestamp >= st->pts_wrap_reference)
100 return timestamp - (1ULL << st->pts_wrap_bits);
105 MAKE_ACCESSORS(AVStream, stream, AVRational, r_frame_rate)
106 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, video_codec)
107 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, audio_codec)
108 MAKE_ACCESSORS(AVFormatContext, format, AVCodec *, subtitle_codec)
109 MAKE_ACCESSORS(AVFormatContext, format, int, metadata_header_padding)
110 MAKE_ACCESSORS(AVFormatContext, format, void *, opaque)
111 MAKE_ACCESSORS(AVFormatContext, format, av_format_control_message, control_message_cb)
113 void av_format_inject_global_side_data(AVFormatContext *s)
116 s->internal->inject_global_side_data = 1;
117 for (i = 0; i < s->nb_streams; i++) {
118 AVStream *st = s->streams[i];
119 st->inject_global_side_data = 1;
123 static const AVCodec *find_decoder(AVFormatContext *s, AVStream *st, enum AVCodecID codec_id)
125 if (st->codec->codec)
126 return st->codec->codec;
128 switch (st->codec->codec_type) {
129 case AVMEDIA_TYPE_VIDEO:
130 if (s->video_codec) return s->video_codec;
132 case AVMEDIA_TYPE_AUDIO:
133 if (s->audio_codec) return s->audio_codec;
135 case AVMEDIA_TYPE_SUBTITLE:
136 if (s->subtitle_codec) return s->subtitle_codec;
140 return avcodec_find_decoder(codec_id);
143 int av_format_get_probe_score(const AVFormatContext *s)
145 return s->probe_score;
148 /* an arbitrarily chosen "sane" max packet size -- 50M */
149 #define SANE_CHUNK_SIZE (50000000)
151 int ffio_limit(AVIOContext *s, int size)
153 if (s->maxsize>= 0) {
154 int64_t remaining= s->maxsize - avio_tell(s);
155 if (remaining < size) {
156 int64_t newsize = avio_size(s);
157 if (!s->maxsize || s->maxsize<newsize)
158 s->maxsize = newsize - !newsize;
159 remaining= s->maxsize - avio_tell(s);
160 remaining= FFMAX(remaining, 0);
163 if (s->maxsize>= 0 && remaining+1 < size) {
164 av_log(NULL, remaining ? AV_LOG_ERROR : AV_LOG_DEBUG, "Truncating packet of size %d to %"PRId64"\n", size, remaining+1);
171 /* Read the data in sane-sized chunks and append to pkt.
172 * Return the number of bytes read or an error. */
173 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
175 int64_t orig_pos = pkt->pos; // av_grow_packet might reset pos
176 int orig_size = pkt->size;
180 int prev_size = pkt->size;
183 /* When the caller requests a lot of data, limit it to the amount
184 * left in file or SANE_CHUNK_SIZE when it is not known. */
186 if (read_size > SANE_CHUNK_SIZE/10) {
187 read_size = ffio_limit(s, read_size);
188 // If filesize/maxsize is unknown, limit to SANE_CHUNK_SIZE
190 read_size = FFMIN(read_size, SANE_CHUNK_SIZE);
193 ret = av_grow_packet(pkt, read_size);
197 ret = avio_read(s, pkt->data + prev_size, read_size);
198 if (ret != read_size) {
199 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
206 pkt->flags |= AV_PKT_FLAG_CORRUPT;
211 return pkt->size > orig_size ? pkt->size - orig_size : ret;
214 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
219 pkt->pos = avio_tell(s);
221 return append_packet_chunked(s, pkt, size);
224 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
227 return av_get_packet(s, pkt, size);
228 return append_packet_chunked(s, pkt, size);
231 int av_filename_number_test(const char *filename)
235 (av_get_frame_filename(buf, sizeof(buf), filename, 1) >= 0);
238 AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened,
241 AVProbeData lpd = *pd;
242 AVInputFormat *fmt1 = NULL, *fmt;
243 int score, nodat = 0, score_max = 0;
244 const static uint8_t zerobuffer[AVPROBE_PADDING_SIZE];
247 lpd.buf = zerobuffer;
249 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
250 int id3len = ff_id3v2_tag_len(lpd.buf);
251 if (lpd.buf_size > id3len + 16) {
253 lpd.buf_size -= id3len;
254 } else if (id3len >= PROBE_BUF_MAX) {
261 while ((fmt1 = av_iformat_next(fmt1))) {
262 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
265 if (fmt1->read_probe) {
266 score = fmt1->read_probe(&lpd);
267 if (fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
268 score = FFMAX(score, nodat ? AVPROBE_SCORE_EXTENSION / 2 - 1 : 1);
269 } else if (fmt1->extensions) {
270 if (av_match_ext(lpd.filename, fmt1->extensions))
271 score = AVPROBE_SCORE_EXTENSION;
273 if (score > score_max) {
276 } else if (score == score_max)
280 score_max = FFMIN(AVPROBE_SCORE_EXTENSION / 2 - 1, score_max);
281 *score_ret = score_max;
286 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
289 AVInputFormat *fmt = av_probe_input_format3(pd, is_opened, &score_ret);
290 if (score_ret > *score_max) {
291 *score_max = score_ret;
297 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
300 return av_probe_input_format2(pd, is_opened, &score);
303 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st,
306 static const struct {
309 enum AVMediaType type;
311 { "aac", AV_CODEC_ID_AAC, AVMEDIA_TYPE_AUDIO },
312 { "ac3", AV_CODEC_ID_AC3, AVMEDIA_TYPE_AUDIO },
313 { "dts", AV_CODEC_ID_DTS, AVMEDIA_TYPE_AUDIO },
314 { "eac3", AV_CODEC_ID_EAC3, AVMEDIA_TYPE_AUDIO },
315 { "h264", AV_CODEC_ID_H264, AVMEDIA_TYPE_VIDEO },
316 { "hevc", AV_CODEC_ID_HEVC, AVMEDIA_TYPE_VIDEO },
317 { "loas", AV_CODEC_ID_AAC_LATM, AVMEDIA_TYPE_AUDIO },
318 { "m4v", AV_CODEC_ID_MPEG4, AVMEDIA_TYPE_VIDEO },
319 { "mp3", AV_CODEC_ID_MP3, AVMEDIA_TYPE_AUDIO },
320 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
324 AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
326 if (fmt && st->request_probe <= score) {
328 av_log(s, AV_LOG_DEBUG,
329 "Probe with size=%d, packets=%d detected %s with score=%d\n",
330 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets,
332 for (i = 0; fmt_id_type[i].name; i++) {
333 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
334 st->codec->codec_id = fmt_id_type[i].id;
335 st->codec->codec_type = fmt_id_type[i].type;
343 /************************************************************/
344 /* input media file */
346 int av_demuxer_open(AVFormatContext *ic) {
349 if (ic->iformat->read_header) {
350 err = ic->iformat->read_header(ic);
355 if (ic->pb && !ic->data_offset)
356 ic->data_offset = avio_tell(ic->pb);
362 int av_probe_input_buffer2(AVIOContext *pb, AVInputFormat **fmt,
363 const char *filename, void *logctx,
364 unsigned int offset, unsigned int max_probe_size)
366 AVProbeData pd = { filename ? filename : "" };
369 int ret = 0, probe_size, buf_offset = 0;
373 max_probe_size = PROBE_BUF_MAX;
374 else if (max_probe_size > PROBE_BUF_MAX)
375 max_probe_size = PROBE_BUF_MAX;
376 else if (max_probe_size < PROBE_BUF_MIN) {
377 av_log(logctx, AV_LOG_ERROR,
378 "Specified probe size value %u cannot be < %u\n", max_probe_size, PROBE_BUF_MIN);
379 return AVERROR(EINVAL);
382 if (offset >= max_probe_size)
383 return AVERROR(EINVAL);
385 if (!*fmt && pb->av_class && av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type) >= 0 && mime_type) {
386 if (!av_strcasecmp(mime_type, "audio/aacp")) {
387 *fmt = av_find_input_format("aac");
389 av_freep(&mime_type);
392 for (probe_size = PROBE_BUF_MIN; probe_size <= max_probe_size && !*fmt;
393 probe_size = FFMIN(probe_size << 1,
394 FFMAX(max_probe_size, probe_size + 1))) {
395 score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;
397 /* Read probe data. */
398 if ((ret = av_reallocp(&buf, probe_size + AVPROBE_PADDING_SIZE)) < 0)
400 if ((ret = avio_read(pb, buf + buf_offset,
401 probe_size - buf_offset)) < 0) {
402 /* Fail if error was not end of file, otherwise, lower score. */
403 if (ret != AVERROR_EOF) {
408 ret = 0; /* error was end of file, nothing read */
411 if (buf_offset < offset)
413 pd.buf_size = buf_offset - offset;
414 pd.buf = &buf[offset];
416 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
418 /* Guess file format. */
419 *fmt = av_probe_input_format2(&pd, 1, &score);
421 /* This can only be true in the last iteration. */
422 if (score <= AVPROBE_SCORE_RETRY) {
423 av_log(logctx, AV_LOG_WARNING,
424 "Format %s detected only with low score of %d, "
425 "misdetection possible!\n", (*fmt)->name, score);
427 av_log(logctx, AV_LOG_DEBUG,
428 "Format %s probed with size=%d and score=%d\n",
429 (*fmt)->name, probe_size, score);
431 FILE *f = fopen("probestat.tmp", "ab");
432 fprintf(f, "probe_size:%d format:%s score:%d filename:%s\n", probe_size, (*fmt)->name, score, filename);
440 return AVERROR_INVALIDDATA;
443 /* Rewind. Reuse probe buffer to avoid seeking. */
444 ret = ffio_rewind_with_probe_data(pb, &buf, buf_offset);
446 return ret < 0 ? ret : score;
449 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
450 const char *filename, void *logctx,
451 unsigned int offset, unsigned int max_probe_size)
453 int ret = av_probe_input_buffer2(pb, fmt, filename, logctx, offset, max_probe_size);
454 return ret < 0 ? ret : 0;
457 /* Open input file and probe the format if necessary. */
458 static int init_input(AVFormatContext *s, const char *filename,
459 AVDictionary **options)
462 AVProbeData pd = { filename, NULL, 0 };
463 int score = AVPROBE_SCORE_RETRY;
466 s->flags |= AVFMT_FLAG_CUSTOM_IO;
468 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
470 else if (s->iformat->flags & AVFMT_NOFILE)
471 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
472 "will be ignored with AVFMT_NOFILE format.\n");
476 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
477 (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))
480 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,
481 &s->interrupt_callback, options)) < 0)
485 return av_probe_input_buffer2(s->pb, &s->iformat, filename,
489 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
490 AVPacketList **plast_pktl)
492 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
497 (*plast_pktl)->next = pktl;
499 *packet_buffer = pktl;
501 /* Add the packet in the buffered packet list. */
507 int avformat_queue_attached_pictures(AVFormatContext *s)
510 for (i = 0; i < s->nb_streams; i++)
511 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
512 s->streams[i]->discard < AVDISCARD_ALL) {
513 AVPacket copy = s->streams[i]->attached_pic;
514 copy.buf = av_buffer_ref(copy.buf);
516 return AVERROR(ENOMEM);
518 add_to_pktbuf(&s->raw_packet_buffer, ©,
519 &s->raw_packet_buffer_end);
524 int avformat_open_input(AVFormatContext **ps, const char *filename,
525 AVInputFormat *fmt, AVDictionary **options)
527 AVFormatContext *s = *ps;
529 AVDictionary *tmp = NULL;
530 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
532 if (!s && !(s = avformat_alloc_context()))
533 return AVERROR(ENOMEM);
535 av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");
536 return AVERROR(EINVAL);
542 av_dict_copy(&tmp, *options, 0);
544 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
547 if ((ret = init_input(s, filename, &tmp)) < 0)
549 s->probe_score = ret;
550 avio_skip(s->pb, s->skip_initial_bytes);
552 /* Check filename in case an image number is expected. */
553 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
554 if (!av_filename_number_test(filename)) {
555 ret = AVERROR(EINVAL);
560 s->duration = s->start_time = AV_NOPTS_VALUE;
561 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
563 /* Allocate private data. */
564 if (s->iformat->priv_data_size > 0) {
565 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
566 ret = AVERROR(ENOMEM);
569 if (s->iformat->priv_class) {
570 *(const AVClass **) s->priv_data = s->iformat->priv_class;
571 av_opt_set_defaults(s->priv_data);
572 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
577 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
579 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, 0);
581 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
582 if ((ret = s->iformat->read_header(s)) < 0)
585 if (id3v2_extra_meta) {
586 if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||
587 !strcmp(s->iformat->name, "tta")) {
588 if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
591 av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");
593 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
595 if ((ret = avformat_queue_attached_pictures(s)) < 0)
598 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
599 s->data_offset = avio_tell(s->pb);
601 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
604 av_dict_free(options);
611 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
613 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
615 avformat_free_context(s);
620 /*******************************************************/
622 static void force_codec_ids(AVFormatContext *s, AVStream *st)
624 switch (st->codec->codec_type) {
625 case AVMEDIA_TYPE_VIDEO:
626 if (s->video_codec_id)
627 st->codec->codec_id = s->video_codec_id;
629 case AVMEDIA_TYPE_AUDIO:
630 if (s->audio_codec_id)
631 st->codec->codec_id = s->audio_codec_id;
633 case AVMEDIA_TYPE_SUBTITLE:
634 if (s->subtitle_codec_id)
635 st->codec->codec_id = s->subtitle_codec_id;
640 static int probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
642 if (st->request_probe>0) {
643 AVProbeData *pd = &st->probe_data;
645 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
649 uint8_t *new_buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
651 av_log(s, AV_LOG_WARNING,
652 "Failed to reallocate probe buffer for stream %d\n",
657 memcpy(pd->buf + pd->buf_size, pkt->data, pkt->size);
658 pd->buf_size += pkt->size;
659 memset(pd->buf + pd->buf_size, 0, AVPROBE_PADDING_SIZE);
662 st->probe_packets = 0;
664 av_log(s, AV_LOG_WARNING,
665 "nothing to probe for stream %d\n", st->index);
669 end= s->raw_packet_buffer_remaining_size <= 0
670 || st->probe_packets<= 0;
672 if (end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
673 int score = set_codec_from_probe_data(s, st, pd);
674 if ( (st->codec->codec_id != AV_CODEC_ID_NONE && score > AVPROBE_SCORE_STREAM_RETRY)
678 st->request_probe = -1;
679 if (st->codec->codec_id != AV_CODEC_ID_NONE) {
680 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
682 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
684 force_codec_ids(s, st);
690 static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index, AVPacket *pkt)
692 int64_t ref = pkt->dts;
693 int i, pts_wrap_behavior;
694 int64_t pts_wrap_reference;
695 AVProgram *first_program;
697 if (ref == AV_NOPTS_VALUE)
699 if (st->pts_wrap_reference != AV_NOPTS_VALUE || st->pts_wrap_bits >= 63 || ref == AV_NOPTS_VALUE || !s->correct_ts_overflow)
701 ref &= (1LL << st->pts_wrap_bits)-1;
703 // reference time stamp should be 60 s before first time stamp
704 pts_wrap_reference = ref - av_rescale(60, st->time_base.den, st->time_base.num);
705 // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset
706 pts_wrap_behavior = (ref < (1LL << st->pts_wrap_bits) - (1LL << st->pts_wrap_bits-3)) ||
707 (ref < (1LL << st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?
708 AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;
710 first_program = av_find_program_from_stream(s, NULL, stream_index);
712 if (!first_program) {
713 int default_stream_index = av_find_default_stream_index(s);
714 if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {
715 for (i = 0; i < s->nb_streams; i++) {
716 s->streams[i]->pts_wrap_reference = pts_wrap_reference;
717 s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;
721 st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;
722 st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;
726 AVProgram *program = first_program;
728 if (program->pts_wrap_reference != AV_NOPTS_VALUE) {
729 pts_wrap_reference = program->pts_wrap_reference;
730 pts_wrap_behavior = program->pts_wrap_behavior;
733 program = av_find_program_from_stream(s, program, stream_index);
736 // update every program with differing pts_wrap_reference
737 program = first_program;
739 if (program->pts_wrap_reference != pts_wrap_reference) {
740 for (i = 0; i<program->nb_stream_indexes; i++) {
741 s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;
742 s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;
745 program->pts_wrap_reference = pts_wrap_reference;
746 program->pts_wrap_behavior = pts_wrap_behavior;
748 program = av_find_program_from_stream(s, program, stream_index);
754 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
760 AVPacketList *pktl = s->raw_packet_buffer;
764 st = s->streams[pkt->stream_index];
765 if (s->raw_packet_buffer_remaining_size <= 0)
766 if ((err = probe_codec(s, st, NULL)) < 0)
768 if (st->request_probe <= 0) {
769 s->raw_packet_buffer = pktl->next;
770 s->raw_packet_buffer_remaining_size += pkt->size;
779 ret = s->iformat->read_packet(s, pkt);
781 if (!pktl || ret == AVERROR(EAGAIN))
783 for (i = 0; i < s->nb_streams; i++) {
785 if (st->probe_packets)
786 if ((err = probe_codec(s, st, NULL)) < 0)
788 av_assert0(st->request_probe <= 0);
793 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
794 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
795 av_log(s, AV_LOG_WARNING,
796 "Dropped corrupted packet (stream = %d)\n",
802 if (pkt->stream_index >= (unsigned)s->nb_streams) {
803 av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
807 st = s->streams[pkt->stream_index];
809 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
810 // correct first time stamps to negative values
811 if (!is_relative(st->first_dts))
812 st->first_dts = wrap_timestamp(st, st->first_dts);
813 if (!is_relative(st->start_time))
814 st->start_time = wrap_timestamp(st, st->start_time);
815 if (!is_relative(st->cur_dts))
816 st->cur_dts = wrap_timestamp(st, st->cur_dts);
819 pkt->dts = wrap_timestamp(st, pkt->dts);
820 pkt->pts = wrap_timestamp(st, pkt->pts);
822 force_codec_ids(s, st);
824 /* TODO: audio: time filter; video: frame reordering (pts != dts) */
825 if (s->use_wallclock_as_timestamps)
826 pkt->dts = pkt->pts = av_rescale_q(av_gettime(), AV_TIME_BASE_Q, st->time_base);
828 if (!pktl && st->request_probe <= 0)
831 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
832 s->raw_packet_buffer_remaining_size -= pkt->size;
834 if ((err = probe_codec(s, st, pkt)) < 0)
839 #if FF_API_READ_PACKET
840 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
842 return ff_read_packet(s, pkt);
847 /**********************************************************/
849 static int determinable_frame_size(AVCodecContext *avctx)
851 if (/*avctx->codec_id == AV_CODEC_ID_AAC ||*/
852 avctx->codec_id == AV_CODEC_ID_MP1 ||
853 avctx->codec_id == AV_CODEC_ID_MP2 ||
854 avctx->codec_id == AV_CODEC_ID_MP3/* ||
855 avctx->codec_id == AV_CODEC_ID_CELT*/)
861 * Get the number of samples of an audio frame. Return -1 on error.
863 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
867 /* give frame_size priority if demuxing */
868 if (!mux && enc->frame_size > 1)
869 return enc->frame_size;
871 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
874 /* Fall back on using frame_size if muxing. */
875 if (enc->frame_size > 1)
876 return enc->frame_size;
878 //For WMA we currently have no other means to calculate duration thus we
879 //do it here by assuming CBR, which is true for all known cases.
880 if (!mux && enc->bit_rate>0 && size>0 && enc->sample_rate>0 && enc->block_align>1) {
881 if (enc->codec_id == AV_CODEC_ID_WMAV1 || enc->codec_id == AV_CODEC_ID_WMAV2)
882 return ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
889 * Return the frame duration in seconds. Return 0 if not available.
891 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
892 AVCodecParserContext *pc, AVPacket *pkt)
898 switch (st->codec->codec_type) {
899 case AVMEDIA_TYPE_VIDEO:
900 if (st->r_frame_rate.num && !pc) {
901 *pnum = st->r_frame_rate.den;
902 *pden = st->r_frame_rate.num;
903 } else if (st->time_base.num * 1000LL > st->time_base.den) {
904 *pnum = st->time_base.num;
905 *pden = st->time_base.den;
906 } else if (st->codec->time_base.num * 1000LL > st->codec->time_base.den) {
907 *pnum = st->codec->time_base.num;
908 *pden = st->codec->time_base.den;
909 if (pc && pc->repeat_pict) {
910 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
911 *pden /= 1 + pc->repeat_pict;
913 *pnum *= 1 + pc->repeat_pict;
915 /* If this codec can be interlaced or progressive then we need
916 * a parser to compute duration of a packet. Thus if we have
917 * no parser in such case leave duration undefined. */
918 if (st->codec->ticks_per_frame > 1 && !pc)
922 case AVMEDIA_TYPE_AUDIO:
923 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
924 if (frame_size <= 0 || st->codec->sample_rate <= 0)
927 *pden = st->codec->sample_rate;
934 static int is_intra_only(AVCodecContext *enc) {
935 const AVCodecDescriptor *desc;
937 if (enc->codec_type != AVMEDIA_TYPE_VIDEO)
940 desc = av_codec_get_codec_descriptor(enc);
942 desc = avcodec_descriptor_get(enc->codec_id);
943 av_codec_set_codec_descriptor(enc, desc);
946 return !!(desc->props & AV_CODEC_PROP_INTRA_ONLY);
950 static int has_decode_delay_been_guessed(AVStream *st)
952 if (st->codec->codec_id != AV_CODEC_ID_H264) return 1;
953 if (!st->info) // if we have left find_stream_info then nb_decoded_frames won't increase anymore for stream copy
955 #if CONFIG_H264_DECODER
956 if (st->codec->has_b_frames &&
957 avpriv_h264_has_num_reorder_frames(st->codec) == st->codec->has_b_frames)
960 if (st->codec->has_b_frames<3)
961 return st->nb_decoded_frames >= 7;
962 else if (st->codec->has_b_frames<4)
963 return st->nb_decoded_frames >= 18;
965 return st->nb_decoded_frames >= 20;
968 static AVPacketList *get_next_pkt(AVFormatContext *s, AVStream *st, AVPacketList *pktl)
972 if (pktl == s->packet_buffer_end)
973 return s->parse_queue;
977 static int64_t select_from_pts_buffer(AVStream *st, int64_t *pts_buffer, int64_t dts) {
978 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
979 st->codec->codec_id != AV_CODEC_ID_HEVC;
982 int delay = st->codec->has_b_frames;
985 if (dts == AV_NOPTS_VALUE) {
986 int64_t best_score = INT64_MAX;
987 for (i = 0; i<delay; i++) {
988 if (st->pts_reorder_error_count[i]) {
989 int64_t score = st->pts_reorder_error[i] / st->pts_reorder_error_count[i];
990 if (score < best_score) {
997 for (i = 0; i<delay; i++) {
998 if (pts_buffer[i] != AV_NOPTS_VALUE) {
999 int64_t diff = FFABS(pts_buffer[i] - dts)
1000 + (uint64_t)st->pts_reorder_error[i];
1001 diff = FFMAX(diff, st->pts_reorder_error[i]);
1002 st->pts_reorder_error[i] = diff;
1003 st->pts_reorder_error_count[i]++;
1004 if (st->pts_reorder_error_count[i] > 250) {
1005 st->pts_reorder_error[i] >>= 1;
1006 st->pts_reorder_error_count[i] >>= 1;
1013 if (dts == AV_NOPTS_VALUE)
1014 dts = pts_buffer[0];
1019 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
1020 int64_t dts, int64_t pts, AVPacket *pkt)
1022 AVStream *st = s->streams[stream_index];
1023 AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
1024 int64_t pts_buffer[MAX_REORDER_DELAY+1];
1028 if (st->first_dts != AV_NOPTS_VALUE ||
1029 dts == AV_NOPTS_VALUE ||
1030 st->cur_dts == AV_NOPTS_VALUE ||
1034 delay = st->codec->has_b_frames;
1035 st->first_dts = dts - (st->cur_dts - RELATIVE_TS_BASE);
1037 shift = st->first_dts - RELATIVE_TS_BASE;
1039 for (i = 0; i<MAX_REORDER_DELAY+1; i++)
1040 pts_buffer[i] = AV_NOPTS_VALUE;
1042 if (is_relative(pts))
1045 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1046 if (pktl->pkt.stream_index != stream_index)
1048 if (is_relative(pktl->pkt.pts))
1049 pktl->pkt.pts += shift;
1051 if (is_relative(pktl->pkt.dts))
1052 pktl->pkt.dts += shift;
1054 if (st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
1055 st->start_time = pktl->pkt.pts;
1057 if (pktl->pkt.pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
1058 pts_buffer[0] = pktl->pkt.pts;
1059 for (i = 0; i<delay && pts_buffer[i] > pts_buffer[i + 1]; i++)
1060 FFSWAP(int64_t, pts_buffer[i], pts_buffer[i + 1]);
1062 pktl->pkt.dts = select_from_pts_buffer(st, pts_buffer, pktl->pkt.dts);
1066 if (st->start_time == AV_NOPTS_VALUE)
1067 st->start_time = pts;
1070 static void update_initial_durations(AVFormatContext *s, AVStream *st,
1071 int stream_index, int duration)
1073 AVPacketList *pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
1074 int64_t cur_dts = RELATIVE_TS_BASE;
1076 if (st->first_dts != AV_NOPTS_VALUE) {
1077 if (st->update_initial_durations_done)
1079 st->update_initial_durations_done = 1;
1080 cur_dts = st->first_dts;
1081 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1082 if (pktl->pkt.stream_index == stream_index) {
1083 if (pktl->pkt.pts != pktl->pkt.dts ||
1084 pktl->pkt.dts != AV_NOPTS_VALUE ||
1087 cur_dts -= duration;
1090 if (pktl && pktl->pkt.dts != st->first_dts) {
1091 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %d) in the queue\n",
1092 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
1096 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
1099 pktl = s->packet_buffer ? s->packet_buffer : s->parse_queue;
1100 st->first_dts = cur_dts;
1101 } else if (st->cur_dts != RELATIVE_TS_BASE)
1104 for (; pktl; pktl = get_next_pkt(s, st, pktl)) {
1105 if (pktl->pkt.stream_index != stream_index)
1107 if (pktl->pkt.pts == pktl->pkt.dts &&
1108 (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&
1109 !pktl->pkt.duration) {
1110 pktl->pkt.dts = cur_dts;
1111 if (!st->codec->has_b_frames)
1112 pktl->pkt.pts = cur_dts;
1113 // if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1114 pktl->pkt.duration = duration;
1117 cur_dts = pktl->pkt.dts + pktl->pkt.duration;
1120 st->cur_dts = cur_dts;
1123 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1124 AVCodecParserContext *pc, AVPacket *pkt)
1126 int num, den, presentation_delayed, delay, i;
1128 AVRational duration;
1129 int onein_oneout = st->codec->codec_id != AV_CODEC_ID_H264 &&
1130 st->codec->codec_id != AV_CODEC_ID_HEVC;
1132 if (s->flags & AVFMT_FLAG_NOFILLIN)
1135 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && pkt->dts != AV_NOPTS_VALUE) {
1136 if (pkt->dts == pkt->pts && st->last_dts_for_order_check != AV_NOPTS_VALUE) {
1137 if (st->last_dts_for_order_check <= pkt->dts) {
1140 av_log(s, st->dts_misordered ? AV_LOG_DEBUG : AV_LOG_WARNING,
1141 "DTS %"PRIi64" < %"PRIi64" out of order\n",
1143 st->last_dts_for_order_check);
1144 st->dts_misordered++;
1146 if (st->dts_ordered + st->dts_misordered > 250) {
1147 st->dts_ordered >>= 1;
1148 st->dts_misordered >>= 1;
1152 st->last_dts_for_order_check = pkt->dts;
1153 if (st->dts_ordered < 8*st->dts_misordered && pkt->dts == pkt->pts)
1154 pkt->dts = AV_NOPTS_VALUE;
1157 if ((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1158 pkt->dts = AV_NOPTS_VALUE;
1160 if (pc && pc->pict_type == AV_PICTURE_TYPE_B
1161 && !st->codec->has_b_frames)
1162 //FIXME Set low_delay = 0 when has_b_frames = 1
1163 st->codec->has_b_frames = 1;
1165 /* do we have a video B-frame ? */
1166 delay = st->codec->has_b_frames;
1167 presentation_delayed = 0;
1169 /* XXX: need has_b_frame, but cannot get it if the codec is
1170 * not initialized */
1172 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1173 presentation_delayed = 1;
1175 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
1176 st->pts_wrap_bits < 63 &&
1177 pkt->dts - (1LL << (st->pts_wrap_bits - 1)) > pkt->pts) {
1178 if (is_relative(st->cur_dts) || pkt->dts - (1LL<<(st->pts_wrap_bits - 1)) > st->cur_dts) {
1179 pkt->dts -= 1LL << st->pts_wrap_bits;
1181 pkt->pts += 1LL << st->pts_wrap_bits;
1184 /* Some MPEG-2 in MPEG-PS lack dts (issue #171 / input_file.mpg).
1185 * We take the conservative approach and discard both.
1186 * Note: If this is misbehaving for an H.264 file, then possibly
1187 * presentation_delayed is not set correctly. */
1188 if (delay == 1 && pkt->dts == pkt->pts &&
1189 pkt->dts != AV_NOPTS_VALUE && presentation_delayed) {
1190 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1191 if ( strcmp(s->iformat->name, "mov,mp4,m4a,3gp,3g2,mj2")
1192 && strcmp(s->iformat->name, "flv")) // otherwise we discard correct timestamps for vc1-wmapro.ism
1193 pkt->dts = AV_NOPTS_VALUE;
1196 duration = av_mul_q((AVRational) {pkt->duration, 1}, st->time_base);
1197 if (pkt->duration == 0) {
1198 ff_compute_frame_duration(&num, &den, st, pc, pkt);
1200 duration = (AVRational) {num, den};
1201 pkt->duration = av_rescale_rnd(1,
1202 num * (int64_t) st->time_base.den,
1203 den * (int64_t) st->time_base.num,
1208 if (pkt->duration != 0 && (s->packet_buffer || s->parse_queue))
1209 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
1211 /* Correct timestamps with byte offset if demuxers only have timestamps
1212 * on packet boundaries */
1213 if (pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size) {
1214 /* this will estimate bitrate based on this frame's duration and size */
1215 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1216 if (pkt->pts != AV_NOPTS_VALUE)
1218 if (pkt->dts != AV_NOPTS_VALUE)
1222 /* This may be redundant, but it should not hurt. */
1223 if (pkt->dts != AV_NOPTS_VALUE &&
1224 pkt->pts != AV_NOPTS_VALUE &&
1225 pkt->pts > pkt->dts)
1226 presentation_delayed = 1;
1229 "IN delayed:%d pts:%s, dts:%s cur_dts:%s st:%d pc:%p duration:%d\n",
1230 presentation_delayed, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts),
1231 pkt->stream_index, pc, pkt->duration);
1232 /* Interpolate PTS and DTS if they are not present. We skip H264
1233 * currently because delay and has_b_frames are not reliably set. */
1234 if ((delay == 0 || (delay == 1 && pc)) &&
1236 if (presentation_delayed) {
1237 /* DTS = decompression timestamp */
1238 /* PTS = presentation timestamp */
1239 if (pkt->dts == AV_NOPTS_VALUE)
1240 pkt->dts = st->last_IP_pts;
1241 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1242 if (pkt->dts == AV_NOPTS_VALUE)
1243 pkt->dts = st->cur_dts;
1245 /* This is tricky: the dts must be incremented by the duration
1246 * of the frame we are displaying, i.e. the last I- or P-frame. */
1247 if (st->last_IP_duration == 0)
1248 st->last_IP_duration = pkt->duration;
1249 if (pkt->dts != AV_NOPTS_VALUE)
1250 st->cur_dts = pkt->dts + st->last_IP_duration;
1251 st->last_IP_duration = pkt->duration;
1252 st->last_IP_pts = pkt->pts;
1253 /* Cannot compute PTS if not present (we can compute it only
1254 * by knowing the future. */
1255 } else if (pkt->pts != AV_NOPTS_VALUE ||
1256 pkt->dts != AV_NOPTS_VALUE ||
1259 /* presentation is not delayed : PTS and DTS are the same */
1260 if (pkt->pts == AV_NOPTS_VALUE)
1261 pkt->pts = pkt->dts;
1262 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
1264 if (pkt->pts == AV_NOPTS_VALUE)
1265 pkt->pts = st->cur_dts;
1266 pkt->dts = pkt->pts;
1267 if (pkt->pts != AV_NOPTS_VALUE)
1268 st->cur_dts = av_add_stable(st->time_base, pkt->pts, duration, 1);
1272 if (pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY && has_decode_delay_been_guessed(st)) {
1273 st->pts_buffer[0] = pkt->pts;
1274 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
1275 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
1277 pkt->dts = select_from_pts_buffer(st, st->pts_buffer, pkt->dts);
1279 // We skipped it above so we try here.
1281 // This should happen on the first packet
1282 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts, pkt);
1283 if (pkt->dts > st->cur_dts)
1284 st->cur_dts = pkt->dts;
1286 av_dlog(NULL, "OUTdelayed:%d/%d pts:%s, dts:%s cur_dts:%s\n",
1287 presentation_delayed, delay, av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts));
1290 if (is_intra_only(st->codec))
1291 pkt->flags |= AV_PKT_FLAG_KEY;
1293 pkt->convergence_duration = pc->convergence_duration;
1296 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1299 AVPacketList *pktl = *pkt_buf;
1300 *pkt_buf = pktl->next;
1301 av_free_packet(&pktl->pkt);
1304 *pkt_buf_end = NULL;
1308 * Parse a packet, add all split parts to parse_queue.
1310 * @param pkt Packet to parse, NULL when flushing the parser at end of stream.
1312 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1314 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1315 AVStream *st = s->streams[stream_index];
1316 uint8_t *data = pkt ? pkt->data : NULL;
1317 int size = pkt ? pkt->size : 0;
1318 int ret = 0, got_output = 0;
1321 av_init_packet(&flush_pkt);
1324 } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {
1325 // preserve 0-size sync packets
1326 compute_pkt_fields(s, st, st->parser, pkt);
1329 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1332 av_init_packet(&out_pkt);
1333 len = av_parser_parse2(st->parser, st->codec,
1334 &out_pkt.data, &out_pkt.size, data, size,
1335 pkt->pts, pkt->dts, pkt->pos);
1337 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1339 /* increment read pointer */
1343 got_output = !!out_pkt.size;
1348 if (pkt->side_data) {
1349 out_pkt.side_data = pkt->side_data;
1350 out_pkt.side_data_elems = pkt->side_data_elems;
1351 pkt->side_data = NULL;
1352 pkt->side_data_elems = 0;
1355 /* set the duration */
1356 out_pkt.duration = 0;
1357 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1358 if (st->codec->sample_rate > 0) {
1360 av_rescale_q_rnd(st->parser->duration,
1361 (AVRational) { 1, st->codec->sample_rate },
1367 out_pkt.stream_index = st->index;
1368 out_pkt.pts = st->parser->pts;
1369 out_pkt.dts = st->parser->dts;
1370 out_pkt.pos = st->parser->pos;
1372 if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1373 out_pkt.pos = st->parser->frame_offset;
1375 if (st->parser->key_frame == 1 ||
1376 (st->parser->key_frame == -1 &&
1377 st->parser->pict_type == AV_PICTURE_TYPE_I))
1378 out_pkt.flags |= AV_PKT_FLAG_KEY;
1380 if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))
1381 out_pkt.flags |= AV_PKT_FLAG_KEY;
1383 compute_pkt_fields(s, st, st->parser, &out_pkt);
1385 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1386 out_pkt.buf = pkt->buf;
1388 #if FF_API_DESTRUCT_PACKET
1389 FF_DISABLE_DEPRECATION_WARNINGS
1390 out_pkt.destruct = pkt->destruct;
1391 pkt->destruct = NULL;
1392 FF_ENABLE_DEPRECATION_WARNINGS
1395 if ((ret = av_dup_packet(&out_pkt)) < 0)
1398 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1399 av_free_packet(&out_pkt);
1400 ret = AVERROR(ENOMEM);
1405 /* end of the stream => close and free the parser */
1406 if (pkt == &flush_pkt) {
1407 av_parser_close(st->parser);
1412 av_free_packet(pkt);
1416 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1417 AVPacketList **pkt_buffer_end,
1421 av_assert0(*pkt_buffer);
1424 *pkt_buffer = pktl->next;
1426 *pkt_buffer_end = NULL;
1431 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1433 int ret = 0, i, got_packet = 0;
1435 av_init_packet(pkt);
1437 while (!got_packet && !s->parse_queue) {
1441 /* read next packet */
1442 ret = ff_read_packet(s, &cur_pkt);
1444 if (ret == AVERROR(EAGAIN))
1446 /* flush the parsers */
1447 for (i = 0; i < s->nb_streams; i++) {
1449 if (st->parser && st->need_parsing)
1450 parse_packet(s, NULL, st->index);
1452 /* all remaining packets are now in parse_queue =>
1453 * really terminate parsing */
1457 st = s->streams[cur_pkt.stream_index];
1459 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1460 cur_pkt.dts != AV_NOPTS_VALUE &&
1461 cur_pkt.pts < cur_pkt.dts) {
1462 av_log(s, AV_LOG_WARNING,
1463 "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",
1464 cur_pkt.stream_index,
1465 av_ts2str(cur_pkt.pts),
1466 av_ts2str(cur_pkt.dts),
1469 if (s->debug & FF_FDEBUG_TS)
1470 av_log(s, AV_LOG_DEBUG,
1471 "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",
1472 cur_pkt.stream_index,
1473 av_ts2str(cur_pkt.pts),
1474 av_ts2str(cur_pkt.dts),
1475 cur_pkt.size, cur_pkt.duration, cur_pkt.flags);
1477 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1478 st->parser = av_parser_init(st->codec->codec_id);
1480 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1481 "%s, packets or times may be invalid.\n",
1482 avcodec_get_name(st->codec->codec_id));
1483 /* no parser available: just output the raw packets */
1484 st->need_parsing = AVSTREAM_PARSE_NONE;
1485 } else if (st->need_parsing == AVSTREAM_PARSE_HEADERS)
1486 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1487 else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)
1488 st->parser->flags |= PARSER_FLAG_ONCE;
1489 else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)
1490 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
1493 if (!st->need_parsing || !st->parser) {
1494 /* no parsing needed: we just output the packet as is */
1496 compute_pkt_fields(s, st, NULL, pkt);
1497 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1498 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1499 ff_reduce_index(s, st->index);
1500 av_add_index_entry(st, pkt->pos, pkt->dts,
1501 0, 0, AVINDEX_KEYFRAME);
1504 } else if (st->discard < AVDISCARD_ALL) {
1505 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1509 av_free_packet(&cur_pkt);
1511 if (pkt->flags & AV_PKT_FLAG_KEY)
1512 st->skip_to_keyframe = 0;
1513 if (st->skip_to_keyframe) {
1514 av_free_packet(&cur_pkt);
1522 if (!got_packet && s->parse_queue)
1523 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1526 AVStream *st = s->streams[pkt->stream_index];
1527 if (st->skip_samples) {
1528 uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1530 AV_WL32(p, st->skip_samples);
1531 av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d\n", st->skip_samples);
1533 st->skip_samples = 0;
1536 if (st->inject_global_side_data) {
1537 for (i = 0; i < st->nb_side_data; i++) {
1538 AVPacketSideData *src_sd = &st->side_data[i];
1541 if (av_packet_get_side_data(pkt, src_sd->type, NULL))
1544 dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
1546 av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");
1550 memcpy(dst_data, src_sd->data, src_sd->size);
1552 st->inject_global_side_data = 0;
1555 if (!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
1556 av_packet_merge_side_data(pkt);
1559 if (s->debug & FF_FDEBUG_TS)
1560 av_log(s, AV_LOG_DEBUG,
1561 "read_frame_internal stream=%d, pts=%s, dts=%s, "
1562 "size=%d, duration=%d, flags=%d\n",
1564 av_ts2str(pkt->pts),
1565 av_ts2str(pkt->dts),
1566 pkt->size, pkt->duration, pkt->flags);
1571 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1573 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1579 ret = s->packet_buffer
1580 ? read_from_packet_buffer(&s->packet_buffer,
1581 &s->packet_buffer_end, pkt)
1582 : read_frame_internal(s, pkt);
1589 AVPacketList *pktl = s->packet_buffer;
1592 AVPacket *next_pkt = &pktl->pkt;
1594 if (next_pkt->dts != AV_NOPTS_VALUE) {
1595 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1596 // last dts seen for this stream. if any of packets following
1597 // current one had no dts, we will set this to AV_NOPTS_VALUE.
1598 int64_t last_dts = next_pkt->dts;
1599 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1600 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1601 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {
1602 if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {
1604 next_pkt->pts = pktl->pkt.dts;
1606 if (last_dts != AV_NOPTS_VALUE) {
1607 // Once last dts was set to AV_NOPTS_VALUE, we don't change it.
1608 last_dts = pktl->pkt.dts;
1613 if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {
1614 // Fixing the last reference frame had none pts issue (For MXF etc).
1615 // We only do this when
1617 // 2. we are not able to resolve a pts value for current packet.
1618 // 3. the packets for this stream at the end of the files had valid dts.
1619 next_pkt->pts = last_dts + next_pkt->duration;
1621 pktl = s->packet_buffer;
1624 /* read packet from packet buffer, if there is data */
1625 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1626 next_pkt->dts != AV_NOPTS_VALUE && !eof)) {
1627 ret = read_from_packet_buffer(&s->packet_buffer,
1628 &s->packet_buffer_end, pkt);
1633 ret = read_frame_internal(s, pkt);
1635 if (pktl && ret != AVERROR(EAGAIN)) {
1642 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1643 &s->packet_buffer_end)) < 0)
1644 return AVERROR(ENOMEM);
1649 st = s->streams[pkt->stream_index];
1650 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {
1651 ff_reduce_index(s, st->index);
1652 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1655 if (is_relative(pkt->dts))
1656 pkt->dts -= RELATIVE_TS_BASE;
1657 if (is_relative(pkt->pts))
1658 pkt->pts -= RELATIVE_TS_BASE;
1663 /* XXX: suppress the packet queue */
1664 static void flush_packet_queue(AVFormatContext *s)
1666 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1667 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1668 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1670 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1673 /*******************************************************/
1676 int av_find_default_stream_index(AVFormatContext *s)
1678 int first_audio_index = -1;
1682 if (s->nb_streams <= 0)
1684 for (i = 0; i < s->nb_streams; i++) {
1686 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1687 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1690 if (first_audio_index < 0 &&
1691 st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1692 first_audio_index = i;
1694 return first_audio_index >= 0 ? first_audio_index : 0;
1697 /** Flush the frame reader. */
1698 void ff_read_frame_flush(AVFormatContext *s)
1703 flush_packet_queue(s);
1705 /* Reset read state for each stream. */
1706 for (i = 0; i < s->nb_streams; i++) {
1710 av_parser_close(st->parser);
1713 st->last_IP_pts = AV_NOPTS_VALUE;
1714 st->last_dts_for_order_check = AV_NOPTS_VALUE;
1715 if (st->first_dts == AV_NOPTS_VALUE)
1716 st->cur_dts = RELATIVE_TS_BASE;
1718 /* We set the current DTS to an unspecified origin. */
1719 st->cur_dts = AV_NOPTS_VALUE;
1721 st->probe_packets = MAX_PROBE_PACKETS;
1723 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
1724 st->pts_buffer[j] = AV_NOPTS_VALUE;
1726 if (s->internal->inject_global_side_data)
1727 st->inject_global_side_data = 1;
1731 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1735 for (i = 0; i < s->nb_streams; i++) {
1736 AVStream *st = s->streams[i];
1739 av_rescale(timestamp,
1740 st->time_base.den * (int64_t) ref_st->time_base.num,
1741 st->time_base.num * (int64_t) ref_st->time_base.den);
1745 void ff_reduce_index(AVFormatContext *s, int stream_index)
1747 AVStream *st = s->streams[stream_index];
1748 unsigned int max_entries = s->max_index_size / sizeof(AVIndexEntry);
1750 if ((unsigned) st->nb_index_entries >= max_entries) {
1752 for (i = 0; 2 * i < st->nb_index_entries; i++)
1753 st->index_entries[i] = st->index_entries[2 * i];
1754 st->nb_index_entries = i;
1758 int ff_add_index_entry(AVIndexEntry **index_entries,
1759 int *nb_index_entries,
1760 unsigned int *index_entries_allocated_size,
1761 int64_t pos, int64_t timestamp,
1762 int size, int distance, int flags)
1764 AVIndexEntry *entries, *ie;
1767 if ((unsigned) *nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1770 if (timestamp == AV_NOPTS_VALUE)
1771 return AVERROR(EINVAL);
1773 if (size < 0 || size > 0x3FFFFFFF)
1774 return AVERROR(EINVAL);
1776 if (is_relative(timestamp)) //FIXME this maintains previous behavior but we should shift by the correct offset once known
1777 timestamp -= RELATIVE_TS_BASE;
1779 entries = av_fast_realloc(*index_entries,
1780 index_entries_allocated_size,
1781 (*nb_index_entries + 1) *
1782 sizeof(AVIndexEntry));
1786 *index_entries = entries;
1788 index = ff_index_search_timestamp(*index_entries, *nb_index_entries,
1789 timestamp, AVSEEK_FLAG_ANY);
1792 index = (*nb_index_entries)++;
1793 ie = &entries[index];
1794 av_assert0(index == 0 || ie[-1].timestamp < timestamp);
1796 ie = &entries[index];
1797 if (ie->timestamp != timestamp) {
1798 if (ie->timestamp <= timestamp)
1800 memmove(entries + index + 1, entries + index,
1801 sizeof(AVIndexEntry) * (*nb_index_entries - index));
1802 (*nb_index_entries)++;
1803 } else if (ie->pos == pos && distance < ie->min_distance)
1804 // do not reduce the distance
1805 distance = ie->min_distance;
1809 ie->timestamp = timestamp;
1810 ie->min_distance = distance;
1817 int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
1818 int size, int distance, int flags)
1820 timestamp = wrap_timestamp(st, timestamp);
1821 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1822 &st->index_entries_allocated_size, pos,
1823 timestamp, size, distance, flags);
1826 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1827 int64_t wanted_timestamp, int flags)
1835 // Optimize appending index entries at the end.
1836 if (b && entries[b - 1].timestamp < wanted_timestamp)
1841 timestamp = entries[m].timestamp;
1842 if (timestamp >= wanted_timestamp)
1844 if (timestamp <= wanted_timestamp)
1847 m = (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1849 if (!(flags & AVSEEK_FLAG_ANY))
1850 while (m >= 0 && m < nb_entries &&
1851 !(entries[m].flags & AVINDEX_KEYFRAME))
1852 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1854 if (m == nb_entries)
1859 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp, int flags)
1861 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1862 wanted_timestamp, flags);
1865 static int64_t ff_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit,
1866 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1868 int64_t ts = read_timestamp(s, stream_index, ppos, pos_limit);
1869 if (stream_index >= 0)
1870 ts = wrap_timestamp(s->streams[stream_index], ts);
1874 int ff_seek_frame_binary(AVFormatContext *s, int stream_index,
1875 int64_t target_ts, int flags)
1877 AVInputFormat *avif = s->iformat;
1878 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1879 int64_t ts_min, ts_max, ts;
1884 if (stream_index < 0)
1887 av_dlog(s, "read_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1890 ts_min = AV_NOPTS_VALUE;
1891 pos_limit = -1; // GCC falsely says it may be uninitialized.
1893 st = s->streams[stream_index];
1894 if (st->index_entries) {
1897 /* FIXME: Whole function must be checked for non-keyframe entries in
1898 * index case, especially read_timestamp(). */
1899 index = av_index_search_timestamp(st, target_ts,
1900 flags | AVSEEK_FLAG_BACKWARD);
1901 index = FFMAX(index, 0);
1902 e = &st->index_entries[index];
1904 if (e->timestamp <= target_ts || e->pos == e->min_distance) {
1906 ts_min = e->timestamp;
1907 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%s\n",
1908 pos_min, av_ts2str(ts_min));
1910 av_assert1(index == 0);
1913 index = av_index_search_timestamp(st, target_ts,
1914 flags & ~AVSEEK_FLAG_BACKWARD);
1915 av_assert0(index < st->nb_index_entries);
1917 e = &st->index_entries[index];
1918 av_assert1(e->timestamp >= target_ts);
1920 ts_max = e->timestamp;
1921 pos_limit = pos_max - e->min_distance;
1922 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64
1923 " dts_max=%s\n", pos_max, pos_limit, av_ts2str(ts_max));
1927 pos = ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit,
1928 ts_min, ts_max, flags, &ts, avif->read_timestamp);
1933 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1936 ff_read_frame_flush(s);
1937 ff_update_cur_dts(s, st, ts);
1942 int ff_find_last_ts(AVFormatContext *s, int stream_index, int64_t *ts, int64_t *pos,
1943 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1945 int64_t step = 1024;
1946 int64_t limit, ts_max;
1947 int64_t filesize = avio_size(s->pb);
1948 int64_t pos_max = filesize - 1;
1951 pos_max = FFMAX(0, (pos_max) - step);
1952 ts_max = ff_read_timestamp(s, stream_index,
1953 &pos_max, limit, read_timestamp);
1955 } while (ts_max == AV_NOPTS_VALUE && 2*limit > step);
1956 if (ts_max == AV_NOPTS_VALUE)
1960 int64_t tmp_pos = pos_max + 1;
1961 int64_t tmp_ts = ff_read_timestamp(s, stream_index,
1962 &tmp_pos, INT64_MAX, read_timestamp);
1963 if (tmp_ts == AV_NOPTS_VALUE)
1965 av_assert0(tmp_pos > pos_max);
1968 if (tmp_pos >= filesize)
1980 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1981 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1982 int64_t ts_min, int64_t ts_max,
1983 int flags, int64_t *ts_ret,
1984 int64_t (*read_timestamp)(struct AVFormatContext *, int,
1985 int64_t *, int64_t))
1992 av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));
1994 if (ts_min == AV_NOPTS_VALUE) {
1995 pos_min = s->data_offset;
1996 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
1997 if (ts_min == AV_NOPTS_VALUE)
2001 if (ts_min >= target_ts) {
2006 if (ts_max == AV_NOPTS_VALUE) {
2007 if ((ret = ff_find_last_ts(s, stream_index, &ts_max, &pos_max, read_timestamp)) < 0)
2009 pos_limit = pos_max;
2012 if (ts_max <= target_ts) {
2017 if (ts_min > ts_max)
2019 else if (ts_min == ts_max)
2020 pos_limit = pos_min;
2023 while (pos_min < pos_limit) {
2025 "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",
2026 pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));
2027 assert(pos_limit <= pos_max);
2029 if (no_change == 0) {
2030 int64_t approximate_keyframe_distance = pos_max - pos_limit;
2031 // interpolate position (better than dichotomy)
2032 pos = av_rescale(target_ts - ts_min, pos_max - pos_min,
2034 pos_min - approximate_keyframe_distance;
2035 } else if (no_change == 1) {
2036 // bisection if interpolation did not change min / max pos last time
2037 pos = (pos_min + pos_limit) >> 1;
2039 /* linear search if bisection failed, can only happen if there
2040 * are very few or no keyframes between min/max */
2045 else if (pos > pos_limit)
2049 // May pass pos_limit instead of -1.
2050 ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp);
2055 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s"
2056 " target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",
2057 pos_min, pos, pos_max,
2058 av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),
2059 pos_limit, start_pos, no_change);
2060 if (ts == AV_NOPTS_VALUE) {
2061 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
2064 assert(ts != AV_NOPTS_VALUE);
2065 if (target_ts <= ts) {
2066 pos_limit = start_pos - 1;
2070 if (target_ts >= ts) {
2076 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
2077 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
2080 ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2082 ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);
2083 av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",
2084 pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));
2090 static int seek_frame_byte(AVFormatContext *s, int stream_index,
2091 int64_t pos, int flags)
2093 int64_t pos_min, pos_max;
2095 pos_min = s->data_offset;
2096 pos_max = avio_size(s->pb) - 1;
2100 else if (pos > pos_max)
2103 avio_seek(s->pb, pos, SEEK_SET);
2105 s->io_repositioned = 1;
2110 static int seek_frame_generic(AVFormatContext *s, int stream_index,
2111 int64_t timestamp, int flags)
2118 st = s->streams[stream_index];
2120 index = av_index_search_timestamp(st, timestamp, flags);
2122 if (index < 0 && st->nb_index_entries &&
2123 timestamp < st->index_entries[0].timestamp)
2126 if (index < 0 || index == st->nb_index_entries - 1) {
2130 if (st->nb_index_entries) {
2131 av_assert0(st->index_entries);
2132 ie = &st->index_entries[st->nb_index_entries - 1];
2133 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2135 ff_update_cur_dts(s, st, ie->timestamp);
2137 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
2143 read_status = av_read_frame(s, &pkt);
2144 } while (read_status == AVERROR(EAGAIN));
2145 if (read_status < 0)
2147 av_free_packet(&pkt);
2148 if (stream_index == pkt.stream_index && pkt.dts > timestamp) {
2149 if (pkt.flags & AV_PKT_FLAG_KEY)
2151 if (nonkey++ > 1000 && st->codec->codec_id != AV_CODEC_ID_CDGRAPHICS) {
2152 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);
2157 index = av_index_search_timestamp(st, timestamp, flags);
2162 ff_read_frame_flush(s);
2163 if (s->iformat->read_seek)
2164 if (s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
2166 ie = &st->index_entries[index];
2167 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
2169 ff_update_cur_dts(s, st, ie->timestamp);
2174 static int seek_frame_internal(AVFormatContext *s, int stream_index,
2175 int64_t timestamp, int flags)
2180 if (flags & AVSEEK_FLAG_BYTE) {
2181 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
2183 ff_read_frame_flush(s);
2184 return seek_frame_byte(s, stream_index, timestamp, flags);
2187 if (stream_index < 0) {
2188 stream_index = av_find_default_stream_index(s);
2189 if (stream_index < 0)
2192 st = s->streams[stream_index];
2193 /* timestamp for default must be expressed in AV_TIME_BASE units */
2194 timestamp = av_rescale(timestamp, st->time_base.den,
2195 AV_TIME_BASE * (int64_t) st->time_base.num);
2198 /* first, we try the format specific seek */
2199 if (s->iformat->read_seek) {
2200 ff_read_frame_flush(s);
2201 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
2207 if (s->iformat->read_timestamp &&
2208 !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
2209 ff_read_frame_flush(s);
2210 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
2211 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
2212 ff_read_frame_flush(s);
2213 return seek_frame_generic(s, stream_index, timestamp, flags);
2218 int av_seek_frame(AVFormatContext *s, int stream_index,
2219 int64_t timestamp, int flags)
2223 if (s->iformat->read_seek2 && !s->iformat->read_seek) {
2224 int64_t min_ts = INT64_MIN, max_ts = INT64_MAX;
2225 if ((flags & AVSEEK_FLAG_BACKWARD))
2229 return avformat_seek_file(s, stream_index, min_ts, timestamp, max_ts,
2230 flags & ~AVSEEK_FLAG_BACKWARD);
2233 ret = seek_frame_internal(s, stream_index, timestamp, flags);
2236 ret = avformat_queue_attached_pictures(s);
2241 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts,
2242 int64_t ts, int64_t max_ts, int flags)
2244 if (min_ts > ts || max_ts < ts)
2246 if (stream_index < -1 || stream_index >= (int)s->nb_streams)
2247 return AVERROR(EINVAL);
2250 flags |= AVSEEK_FLAG_ANY;
2251 flags &= ~AVSEEK_FLAG_BACKWARD;
2253 if (s->iformat->read_seek2) {
2255 ff_read_frame_flush(s);
2257 if (stream_index == -1 && s->nb_streams == 1) {
2258 AVRational time_base = s->streams[0]->time_base;
2259 ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);
2260 min_ts = av_rescale_rnd(min_ts, time_base.den,
2261 time_base.num * (int64_t)AV_TIME_BASE,
2262 AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
2263 max_ts = av_rescale_rnd(max_ts, time_base.den,
2264 time_base.num * (int64_t)AV_TIME_BASE,
2265 AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
2268 ret = s->iformat->read_seek2(s, stream_index, min_ts,
2272 ret = avformat_queue_attached_pictures(s);
2276 if (s->iformat->read_timestamp) {
2277 // try to seek via read_timestamp()
2280 // Fall back on old API if new is not implemented but old is.
2281 // Note the old API has somewhat different semantics.
2282 if (s->iformat->read_seek || 1) {
2283 int dir = (ts - (uint64_t)min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0);
2284 int ret = av_seek_frame(s, stream_index, ts, flags | dir);
2285 if (ret<0 && ts != min_ts && max_ts != ts) {
2286 ret = av_seek_frame(s, stream_index, dir ? max_ts : min_ts, flags | dir);
2288 ret = av_seek_frame(s, stream_index, ts, flags | (dir^AVSEEK_FLAG_BACKWARD));
2293 // try some generic seek like seek_frame_generic() but with new ts semantics
2294 return -1; //unreachable
2297 /*******************************************************/
2300 * Return TRUE if the stream has accurate duration in any stream.
2302 * @return TRUE if the stream has accurate duration for at least one component.
2304 static int has_duration(AVFormatContext *ic)
2309 for (i = 0; i < ic->nb_streams; i++) {
2310 st = ic->streams[i];
2311 if (st->duration != AV_NOPTS_VALUE)
2314 if (ic->duration != AV_NOPTS_VALUE)
2320 * Estimate the stream timings from the one of each components.
2322 * Also computes the global bitrate if possible.
2324 static void update_stream_timings(AVFormatContext *ic)
2326 int64_t start_time, start_time1, start_time_text, end_time, end_time1;
2327 int64_t duration, duration1, filesize;
2332 start_time = INT64_MAX;
2333 start_time_text = INT64_MAX;
2334 end_time = INT64_MIN;
2335 duration = INT64_MIN;
2336 for (i = 0; i < ic->nb_streams; i++) {
2337 st = ic->streams[i];
2338 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
2339 start_time1 = av_rescale_q(st->start_time, st->time_base,
2341 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE || st->codec->codec_type == AVMEDIA_TYPE_DATA) {
2342 if (start_time1 < start_time_text)
2343 start_time_text = start_time1;
2345 start_time = FFMIN(start_time, start_time1);
2346 end_time1 = AV_NOPTS_VALUE;
2347 if (st->duration != AV_NOPTS_VALUE) {
2348 end_time1 = start_time1 +
2349 av_rescale_q(st->duration, st->time_base,
2351 end_time = FFMAX(end_time, end_time1);
2353 for (p = NULL; (p = av_find_program_from_stream(ic, p, i)); ) {
2354 if (p->start_time == AV_NOPTS_VALUE || p->start_time > start_time1)
2355 p->start_time = start_time1;
2356 if (p->end_time < end_time1)
2357 p->end_time = end_time1;
2360 if (st->duration != AV_NOPTS_VALUE) {
2361 duration1 = av_rescale_q(st->duration, st->time_base,
2363 duration = FFMAX(duration, duration1);
2366 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
2367 start_time = start_time_text;
2368 else if (start_time > start_time_text)
2369 av_log(ic, AV_LOG_VERBOSE, "Ignoring outlier non primary stream starttime %f\n", start_time_text / (float)AV_TIME_BASE);
2371 if (start_time != INT64_MAX) {
2372 ic->start_time = start_time;
2373 if (end_time != INT64_MIN) {
2374 if (ic->nb_programs) {
2375 for (i = 0; i < ic->nb_programs; i++) {
2376 p = ic->programs[i];
2377 if (p->start_time != AV_NOPTS_VALUE && p->end_time > p->start_time)
2378 duration = FFMAX(duration, p->end_time - p->start_time);
2381 duration = FFMAX(duration, end_time - start_time);
2384 if (duration != INT64_MIN && duration > 0 && ic->duration == AV_NOPTS_VALUE) {
2385 ic->duration = duration;
2387 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
2388 /* compute the bitrate */
2389 double bitrate = (double) filesize * 8.0 * AV_TIME_BASE /
2390 (double) ic->duration;
2391 if (bitrate >= 0 && bitrate <= INT_MAX)
2392 ic->bit_rate = bitrate;
2396 static void fill_all_stream_timings(AVFormatContext *ic)
2401 update_stream_timings(ic);
2402 for (i = 0; i < ic->nb_streams; i++) {
2403 st = ic->streams[i];
2404 if (st->start_time == AV_NOPTS_VALUE) {
2405 if (ic->start_time != AV_NOPTS_VALUE)
2406 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q,
2408 if (ic->duration != AV_NOPTS_VALUE)
2409 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q,
2415 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2417 int64_t filesize, duration;
2418 int i, show_warning = 0;
2421 /* if bit_rate is already set, we believe it */
2422 if (ic->bit_rate <= 0) {
2424 for (i = 0; i < ic->nb_streams; i++) {
2425 st = ic->streams[i];
2426 if (st->codec->bit_rate > 0) {
2427 if (INT_MAX - st->codec->bit_rate < bit_rate) {
2431 bit_rate += st->codec->bit_rate;
2434 ic->bit_rate = bit_rate;
2437 /* if duration is already set, we believe it */
2438 if (ic->duration == AV_NOPTS_VALUE &&
2439 ic->bit_rate != 0) {
2440 filesize = ic->pb ? avio_size(ic->pb) : 0;
2442 for (i = 0; i < ic->nb_streams; i++) {
2443 st = ic->streams[i];
2444 if ( st->time_base.num <= INT64_MAX / ic->bit_rate
2445 && st->duration == AV_NOPTS_VALUE) {
2446 duration = av_rescale(8 * filesize, st->time_base.den,
2448 (int64_t) st->time_base.num);
2449 st->duration = duration;
2456 av_log(ic, AV_LOG_WARNING,
2457 "Estimating duration from bitrate, this may be inaccurate\n");
2460 #define DURATION_MAX_READ_SIZE 250000LL
2461 #define DURATION_MAX_RETRY 4
2463 /* only usable for MPEG-PS streams */
2464 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2466 AVPacket pkt1, *pkt = &pkt1;
2468 int read_size, i, ret;
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 /* estimate the end time (duration) */
2491 /* XXX: may need to support wrapping */
2492 filesize = ic->pb ? avio_size(ic->pb) : 0;
2493 end_time = AV_NOPTS_VALUE;
2495 offset = filesize - (DURATION_MAX_READ_SIZE << retry);
2499 avio_seek(ic->pb, offset, SEEK_SET);
2502 if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))
2506 ret = ff_read_packet(ic, pkt);
2507 } while (ret == AVERROR(EAGAIN));
2510 read_size += pkt->size;
2511 st = ic->streams[pkt->stream_index];
2512 if (pkt->pts != AV_NOPTS_VALUE &&
2513 (st->start_time != AV_NOPTS_VALUE ||
2514 st->first_dts != AV_NOPTS_VALUE)) {
2515 duration = end_time = pkt->pts;
2516 if (st->start_time != AV_NOPTS_VALUE)
2517 duration -= st->start_time;
2519 duration -= st->first_dts;
2521 if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||
2522 (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))
2523 st->duration = duration;
2524 st->info->last_duration = duration;
2527 av_free_packet(pkt);
2529 } while (end_time == AV_NOPTS_VALUE &&
2530 filesize > (DURATION_MAX_READ_SIZE << retry) &&
2531 ++retry <= DURATION_MAX_RETRY);
2533 fill_all_stream_timings(ic);
2535 avio_seek(ic->pb, old_offset, SEEK_SET);
2536 for (i = 0; i < ic->nb_streams; i++) {
2539 st = ic->streams[i];
2540 st->cur_dts = st->first_dts;
2541 st->last_IP_pts = AV_NOPTS_VALUE;
2542 st->last_dts_for_order_check = AV_NOPTS_VALUE;
2543 for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
2544 st->pts_buffer[j] = AV_NOPTS_VALUE;
2548 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2552 /* get the file size, if possible */
2553 if (ic->iformat->flags & AVFMT_NOFILE) {
2556 file_size = avio_size(ic->pb);
2557 file_size = FFMAX(0, file_size);
2560 if ((!strcmp(ic->iformat->name, "mpeg") ||
2561 !strcmp(ic->iformat->name, "mpegts")) &&
2562 file_size && ic->pb->seekable) {
2563 /* get accurate estimate from the PTSes */
2564 estimate_timings_from_pts(ic, old_offset);
2565 ic->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
2566 } else if (has_duration(ic)) {
2567 /* at least one component has timings - we use them for all
2569 fill_all_stream_timings(ic);
2570 ic->duration_estimation_method = AVFMT_DURATION_FROM_STREAM;
2572 /* less precise: use bitrate info */
2573 estimate_timings_from_bit_rate(ic);
2574 ic->duration_estimation_method = AVFMT_DURATION_FROM_BITRATE;
2576 update_stream_timings(ic);
2580 AVStream av_unused *st;
2581 for (i = 0; i < ic->nb_streams; i++) {
2582 st = ic->streams[i];
2583 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2584 (double) st->start_time / AV_TIME_BASE,
2585 (double) st->duration / AV_TIME_BASE);
2588 "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2589 (double) ic->start_time / AV_TIME_BASE,
2590 (double) ic->duration / AV_TIME_BASE,
2591 ic->bit_rate / 1000);
2595 static int has_codec_parameters(AVStream *st, const char **errmsg_ptr)
2597 AVCodecContext *avctx = st->codec;
2599 #define FAIL(errmsg) do { \
2601 *errmsg_ptr = errmsg; \
2605 switch (avctx->codec_type) {
2606 case AVMEDIA_TYPE_AUDIO:
2607 if (!avctx->frame_size && determinable_frame_size(avctx))
2608 FAIL("unspecified frame size");
2609 if (st->info->found_decoder >= 0 &&
2610 avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2611 FAIL("unspecified sample format");
2612 if (!avctx->sample_rate)
2613 FAIL("unspecified sample rate");
2614 if (!avctx->channels)
2615 FAIL("unspecified number of channels");
2616 if (st->info->found_decoder >= 0 && !st->nb_decoded_frames && avctx->codec_id == AV_CODEC_ID_DTS)
2617 FAIL("no decodable DTS frames");
2619 case AVMEDIA_TYPE_VIDEO:
2621 FAIL("unspecified size");
2622 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2623 FAIL("unspecified pixel format");
2624 if (st->codec->codec_id == AV_CODEC_ID_RV30 || st->codec->codec_id == AV_CODEC_ID_RV40)
2625 if (!st->sample_aspect_ratio.num && !st->codec->sample_aspect_ratio.num && !st->codec_info_nb_frames)
2626 FAIL("no frame in rv30/40 and no sar");
2628 case AVMEDIA_TYPE_SUBTITLE:
2629 if (avctx->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && !avctx->width)
2630 FAIL("unspecified size");
2632 case AVMEDIA_TYPE_DATA:
2633 if (avctx->codec_id == AV_CODEC_ID_NONE) return 1;
2636 if (avctx->codec_id == AV_CODEC_ID_NONE)
2637 FAIL("unknown codec");
2641 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2642 static int try_decode_frame(AVFormatContext *s, AVStream *st, AVPacket *avpkt,
2643 AVDictionary **options)
2645 const AVCodec *codec;
2646 int got_picture = 1, ret = 0;
2647 AVFrame *frame = av_frame_alloc();
2648 AVSubtitle subtitle;
2649 AVPacket pkt = *avpkt;
2652 return AVERROR(ENOMEM);
2654 if (!avcodec_is_open(st->codec) &&
2655 st->info->found_decoder <= 0 &&
2656 (st->codec->codec_id != -st->info->found_decoder || !st->codec->codec_id)) {
2657 AVDictionary *thread_opt = NULL;
2659 codec = find_decoder(s, st, st->codec->codec_id);
2662 st->info->found_decoder = -st->codec->codec_id;
2667 /* Force thread count to 1 since the H.264 decoder will not extract
2668 * SPS and PPS to extradata during multi-threaded decoding. */
2669 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2670 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2672 av_dict_free(&thread_opt);
2674 st->info->found_decoder = -st->codec->codec_id;
2677 st->info->found_decoder = 1;
2678 } else if (!st->info->found_decoder)
2679 st->info->found_decoder = 1;
2681 if (st->info->found_decoder < 0) {
2686 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2688 (!has_codec_parameters(st, NULL) || !has_decode_delay_been_guessed(st) ||
2689 (!st->codec_info_nb_frames &&
2690 st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2692 switch (st->codec->codec_type) {
2693 case AVMEDIA_TYPE_VIDEO:
2694 ret = avcodec_decode_video2(st->codec, frame,
2695 &got_picture, &pkt);
2697 case AVMEDIA_TYPE_AUDIO:
2698 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2700 case AVMEDIA_TYPE_SUBTITLE:
2701 ret = avcodec_decode_subtitle2(st->codec, &subtitle,
2702 &got_picture, &pkt);
2710 st->nb_decoded_frames++;
2717 if (!pkt.data && !got_picture)
2721 av_frame_free(&frame);
2725 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2727 while (tags->id != AV_CODEC_ID_NONE) {
2735 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2738 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2739 if (tag == tags[i].tag)
2741 for (i = 0; tags[i].id != AV_CODEC_ID_NONE; i++)
2742 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2744 return AV_CODEC_ID_NONE;
2747 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2752 return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2754 return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2756 return AV_CODEC_ID_NONE;
2761 if (sflags & (1 << (bps - 1))) {
2764 return AV_CODEC_ID_PCM_S8;
2766 return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2768 return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2770 return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2772 return AV_CODEC_ID_NONE;
2777 return AV_CODEC_ID_PCM_U8;
2779 return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2781 return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2783 return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2785 return AV_CODEC_ID_NONE;
2791 unsigned int av_codec_get_tag(const AVCodecTag *const *tags, enum AVCodecID id)
2794 if (!av_codec_get_tag2(tags, id, &tag))
2799 int av_codec_get_tag2(const AVCodecTag * const *tags, enum AVCodecID id,
2803 for (i = 0; tags && tags[i]; i++) {
2804 const AVCodecTag *codec_tags = tags[i];
2805 while (codec_tags->id != AV_CODEC_ID_NONE) {
2806 if (codec_tags->id == id) {
2807 *tag = codec_tags->tag;
2816 enum AVCodecID av_codec_get_id(const AVCodecTag *const *tags, unsigned int tag)
2819 for (i = 0; tags && tags[i]; i++) {
2820 enum AVCodecID id = ff_codec_get_id(tags[i], tag);
2821 if (id != AV_CODEC_ID_NONE)
2824 return AV_CODEC_ID_NONE;
2827 static void compute_chapters_end(AVFormatContext *s)
2830 int64_t max_time = s->duration +
2831 ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2833 for (i = 0; i < s->nb_chapters; i++)
2834 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2835 AVChapter *ch = s->chapters[i];
2836 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,
2840 for (j = 0; j < s->nb_chapters; j++) {
2841 AVChapter *ch1 = s->chapters[j];
2842 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,
2844 if (j != i && next_start > ch->start && next_start < end)
2847 ch->end = (end == INT64_MAX) ? ch->start : end;
2851 static int get_std_framerate(int i)
2854 return (i + 1) * 1001;
2856 return ((const int[]) { 24, 30, 60, 12, 15, 48 })[i - 60 * 12] * 1000 * 12;
2859 /* Is the time base unreliable?
2860 * This is a heuristic to balance between quick acceptance of the values in
2861 * the headers vs. some extra checks.
2862 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2863 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2864 * And there are "variable" fps files this needs to detect as well. */
2865 static int tb_unreliable(AVCodecContext *c)
2867 if (c->time_base.den >= 101L * c->time_base.num ||
2868 c->time_base.den < 5L * c->time_base.num ||
2869 // c->codec_tag == AV_RL32("DIVX") ||
2870 // c->codec_tag == AV_RL32("XVID") ||
2871 c->codec_tag == AV_RL32("mp4v") ||
2872 c->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
2873 c->codec_id == AV_CODEC_ID_GIF ||
2874 c->codec_id == AV_CODEC_ID_H264)
2879 #if FF_API_FORMAT_PARAMETERS
2880 int av_find_stream_info(AVFormatContext *ic)
2882 return avformat_find_stream_info(ic, NULL);
2886 int ff_alloc_extradata(AVCodecContext *avctx, int size)
2890 if (size < 0 || size >= INT32_MAX - FF_INPUT_BUFFER_PADDING_SIZE) {
2891 avctx->extradata_size = 0;
2892 return AVERROR(EINVAL);
2894 avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
2895 if (avctx->extradata) {
2896 memset(avctx->extradata + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2897 avctx->extradata_size = size;
2900 avctx->extradata_size = 0;
2901 ret = AVERROR(ENOMEM);
2906 int ff_get_extradata(AVCodecContext *avctx, AVIOContext *pb, int size)
2908 int ret = ff_alloc_extradata(avctx, size);
2911 ret = avio_read(pb, avctx->extradata, size);
2913 av_freep(&avctx->extradata);
2914 avctx->extradata_size = 0;
2915 av_log(avctx, AV_LOG_ERROR, "Failed to read extradata of size %d\n", size);
2916 return ret < 0 ? ret : AVERROR_INVALIDDATA;
2922 int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t ts)
2925 int64_t last = st->info->last_dts;
2927 if ( ts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && ts > last
2928 && ts - (uint64_t)last < INT64_MAX) {
2929 double dts = (is_relative(ts) ? ts - RELATIVE_TS_BASE : ts) * av_q2d(st->time_base);
2930 int64_t duration = ts - last;
2932 if (!st->info->duration_error)
2933 st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);
2934 if (!st->info->duration_error)
2935 return AVERROR(ENOMEM);
2937 // if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2938 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2939 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2940 if (st->info->duration_error[0][1][i] < 1e10) {
2941 int framerate = get_std_framerate(i);
2942 double sdts = dts*framerate/(1001*12);
2943 for (j= 0; j<2; j++) {
2944 int64_t ticks = llrint(sdts+j*0.5);
2945 double error= sdts - ticks + j*0.5;
2946 st->info->duration_error[j][0][i] += error;
2947 st->info->duration_error[j][1][i] += error*error;
2951 st->info->duration_count++;
2952 st->info->rfps_duration_sum += duration;
2954 if (st->info->duration_count % 10 == 0) {
2955 int n = st->info->duration_count;
2956 for (i = 0; i<MAX_STD_TIMEBASES; i++) {
2957 if (st->info->duration_error[0][1][i] < 1e10) {
2958 double a0 = st->info->duration_error[0][0][i] / n;
2959 double error0 = st->info->duration_error[0][1][i] / n - a0*a0;
2960 double a1 = st->info->duration_error[1][0][i] / n;
2961 double error1 = st->info->duration_error[1][1][i] / n - a1*a1;
2962 if (error0 > 0.04 && error1 > 0.04) {
2963 st->info->duration_error[0][1][i] = 2e10;
2964 st->info->duration_error[1][1][i] = 2e10;
2970 // ignore the first 4 values, they might have some random jitter
2971 if (st->info->duration_count > 3 && is_relative(ts) == is_relative(last))
2972 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2974 if (ts != AV_NOPTS_VALUE)
2975 st->info->last_dts = ts;
2980 void ff_rfps_calculate(AVFormatContext *ic)
2984 for (i = 0; i < ic->nb_streams; i++) {
2985 AVStream *st = ic->streams[i];
2987 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
2989 // the check for tb_unreliable() is not completely correct, since this is not about handling
2990 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2991 // ipmovie.c produces.
2992 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)
2993 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);
2994 if (st->info->duration_count>1 && !st->r_frame_rate.num
2995 && tb_unreliable(st->codec)) {
2997 double best_error= 0.01;
2998 AVRational ref_rate = st->r_frame_rate.num ? st->r_frame_rate : av_inv_q(st->time_base);
3000 for (j= 0; j<MAX_STD_TIMEBASES; j++) {
3003 if (st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
3005 if (!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
3008 if (av_q2d(st->time_base) * st->info->rfps_duration_sum / st->info->duration_count < (1001*12.0 * 0.8)/get_std_framerate(j))
3011 for (k= 0; k<2; k++) {
3012 int n = st->info->duration_count;
3013 double a= st->info->duration_error[k][0][j] / n;
3014 double error= st->info->duration_error[k][1][j]/n - a*a;
3016 if (error < best_error && best_error> 0.000000001) {
3018 num = get_std_framerate(j);
3021 av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
3024 // do not increase frame rate by more than 1 % in order to match a standard rate.
3025 if (num && (!ref_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(ref_rate)))
3026 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
3028 if ( !st->avg_frame_rate.num
3029 && st->r_frame_rate.num && st->info->rfps_duration_sum
3030 && st->info->codec_info_duration <= 0
3031 && st->info->duration_count > 2
3032 && 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
3034 av_log(ic, AV_LOG_DEBUG, "Setting avg frame rate based on r frame rate\n");
3035 st->avg_frame_rate = st->r_frame_rate;
3038 av_freep(&st->info->duration_error);
3039 st->info->last_dts = AV_NOPTS_VALUE;
3040 st->info->duration_count = 0;
3041 st->info->rfps_duration_sum = 0;
3045 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
3047 int i, count, ret = 0, j;
3050 AVPacket pkt1, *pkt;
3051 int64_t old_offset = avio_tell(ic->pb);
3052 // new streams might appear, no options for those
3053 int orig_nb_streams = ic->nb_streams;
3054 int flush_codecs = ic->probesize > 0;
3057 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d\n",
3058 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count);
3060 for (i = 0; i < ic->nb_streams; i++) {
3061 const AVCodec *codec;
3062 AVDictionary *thread_opt = NULL;
3063 st = ic->streams[i];
3065 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3066 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3067 /* if (!st->time_base.num)
3069 if (!st->codec->time_base.num)
3070 st->codec->time_base = st->time_base;
3072 // only for the split stuff
3073 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
3074 st->parser = av_parser_init(st->codec->codec_id);
3076 if (st->need_parsing == AVSTREAM_PARSE_HEADERS) {
3077 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
3078 } else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {
3079 st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
3081 } else if (st->need_parsing) {
3082 av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "
3083 "%s, packets or times may be invalid.\n",
3084 avcodec_get_name(st->codec->codec_id));
3087 codec = find_decoder(ic, st, st->codec->codec_id);
3089 /* Force thread count to 1 since the H.264 decoder will not extract
3090 * SPS and PPS to extradata during multi-threaded decoding. */
3091 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
3093 /* Ensure that subtitle_header is properly set. */
3094 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
3095 && codec && !st->codec->codec) {
3096 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3097 av_log(ic, AV_LOG_WARNING,
3098 "Failed to open codec in av_find_stream_info\n");
3101 // Try to just open decoders, in case this is enough to get parameters.
3102 if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {
3103 if (codec && !st->codec->codec)
3104 if (avcodec_open2(st->codec, codec, options ? &options[i] : &thread_opt) < 0)
3105 av_log(ic, AV_LOG_WARNING,
3106 "Failed to open codec in av_find_stream_info\n");
3109 av_dict_free(&thread_opt);
3112 for (i = 0; i < ic->nb_streams; i++) {
3113 #if FF_API_R_FRAME_RATE
3114 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
3116 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
3117 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
3123 if (ff_check_interrupt(&ic->interrupt_callback)) {
3125 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
3129 /* check if one codec still needs to be handled */
3130 for (i = 0; i < ic->nb_streams; i++) {
3131 int fps_analyze_framecount = 20;
3133 st = ic->streams[i];
3134 if (!has_codec_parameters(st, NULL))
3136 /* If the timebase is coarse (like the usual millisecond precision
3137 * of mkv), we need to analyze more frames to reliably arrive at
3138 * the correct fps. */
3139 if (av_q2d(st->time_base) > 0.0005)
3140 fps_analyze_framecount *= 2;
3141 if (!tb_unreliable(st->codec))
3142 fps_analyze_framecount = 0;
3143 if (ic->fps_probe_size >= 0)
3144 fps_analyze_framecount = ic->fps_probe_size;
3145 if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3146 fps_analyze_framecount = 0;
3147 /* variable fps and no guess at the real fps */
3148 if (!(st->r_frame_rate.num && st->avg_frame_rate.num) &&
3149 st->info->duration_count < fps_analyze_framecount &&
3150 st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
3152 if (st->parser && st->parser->parser->split &&
3153 !st->codec->extradata)
3155 if (st->first_dts == AV_NOPTS_VALUE &&
3156 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3157 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
3160 if (i == ic->nb_streams) {
3161 /* NOTE: If the format has no header, then we need to read some
3162 * packets to get most of the streams, so we cannot stop here. */
3163 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
3164 /* If we found the info for all the codecs, we can stop. */
3166 av_log(ic, AV_LOG_DEBUG, "All info found\n");
3171 /* We did not get all the codec info, but we read too much data. */
3172 if (read_size >= ic->probesize) {
3174 av_log(ic, AV_LOG_DEBUG,
3175 "Probe buffer size limit of %d bytes reached\n", ic->probesize);
3176 for (i = 0; i < ic->nb_streams; i++)
3177 if (!ic->streams[i]->r_frame_rate.num &&
3178 ic->streams[i]->info->duration_count <= 1 &&
3179 ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3180 strcmp(ic->iformat->name, "image2"))
3181 av_log(ic, AV_LOG_WARNING,
3182 "Stream #%d: not enough frames to estimate rate; "
3183 "consider increasing probesize\n", i);
3187 /* NOTE: A new stream can be added there if no header in file
3188 * (AVFMTCTX_NOHEADER). */
3189 ret = read_frame_internal(ic, &pkt1);
3190 if (ret == AVERROR(EAGAIN))
3198 if (ic->flags & AVFMT_FLAG_NOBUFFER)
3199 free_packet_buffer(&ic->packet_buffer, &ic->packet_buffer_end);
3201 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
3202 &ic->packet_buffer_end);
3204 ret = AVERROR(ENOMEM);
3205 goto find_stream_info_err;
3207 if ((ret = av_dup_packet(pkt)) < 0)
3208 goto find_stream_info_err;
3211 st = ic->streams[pkt->stream_index];
3212 if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
3213 read_size += pkt->size;
3215 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
3216 /* check for non-increasing dts */
3217 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3218 st->info->fps_last_dts >= pkt->dts) {
3219 av_log(ic, AV_LOG_DEBUG,
3220 "Non-increasing DTS in stream %d: packet %d with DTS "
3221 "%"PRId64", packet %d with DTS %"PRId64"\n",
3222 st->index, st->info->fps_last_dts_idx,
3223 st->info->fps_last_dts, st->codec_info_nb_frames,
3225 st->info->fps_first_dts =
3226 st->info->fps_last_dts = AV_NOPTS_VALUE;
3228 /* Check for a discontinuity in dts. If the difference in dts
3229 * is more than 1000 times the average packet duration in the
3230 * sequence, we treat it as a discontinuity. */
3231 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
3232 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
3233 (pkt->dts - st->info->fps_last_dts) / 1000 >
3234 (st->info->fps_last_dts - st->info->fps_first_dts) /
3235 (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
3236 av_log(ic, AV_LOG_WARNING,
3237 "DTS discontinuity in stream %d: packet %d with DTS "
3238 "%"PRId64", packet %d with DTS %"PRId64"\n",
3239 st->index, st->info->fps_last_dts_idx,
3240 st->info->fps_last_dts, st->codec_info_nb_frames,
3242 st->info->fps_first_dts =
3243 st->info->fps_last_dts = AV_NOPTS_VALUE;
3246 /* update stored dts values */
3247 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
3248 st->info->fps_first_dts = pkt->dts;
3249 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
3251 st->info->fps_last_dts = pkt->dts;
3252 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
3254 if (st->codec_info_nb_frames>1) {
3256 if (st->time_base.den > 0)
3257 t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);
3258 if (st->avg_frame_rate.num > 0)
3259 t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));
3262 && st->codec_info_nb_frames>30
3263 && st->info->fps_first_dts != AV_NOPTS_VALUE
3264 && st->info->fps_last_dts != AV_NOPTS_VALUE)
3265 t = FFMAX(t, av_rescale_q(st->info->fps_last_dts - st->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));
3267 if (t >= ic->max_analyze_duration) {
3268 av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %d reached at %"PRId64" microseconds\n",
3269 ic->max_analyze_duration,
3273 if (pkt->duration) {
3274 st->info->codec_info_duration += pkt->duration;
3275 st->info->codec_info_duration_fields += st->parser && st->need_parsing && st->codec->ticks_per_frame ==2 ? st->parser->repeat_pict + 1 : 2;
3278 #if FF_API_R_FRAME_RATE
3279 ff_rfps_add_frame(ic, st, pkt->dts);
3281 if (st->parser && st->parser->parser->split && !st->codec->extradata) {
3282 int i = st->parser->parser->split(st->codec, pkt->data, pkt->size);
3283 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
3284 if (ff_alloc_extradata(st->codec, i))
3285 return AVERROR(ENOMEM);
3286 memcpy(st->codec->extradata, pkt->data,
3287 st->codec->extradata_size);
3291 /* If still no information, we try to open the codec and to
3292 * decompress the frame. We try to avoid that in most cases as
3293 * it takes longer and uses more memory. For MPEG-4, we need to
3294 * decompress for QuickTime.
3296 * If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
3297 * least one frame of codec data, this makes sure the codec initializes
3298 * the channel configuration and does not only trust the values from
3300 try_decode_frame(ic, st, pkt,
3301 (options && i < orig_nb_streams) ? &options[i] : NULL);
3303 st->codec_info_nb_frames++;
3308 AVPacket empty_pkt = { 0 };
3310 av_init_packet(&empty_pkt);
3312 for (i = 0; i < ic->nb_streams; i++) {
3314 st = ic->streams[i];
3316 /* flush the decoders */
3317 if (st->info->found_decoder == 1) {
3319 err = try_decode_frame(ic, st, &empty_pkt,
3320 (options && i < orig_nb_streams)
3321 ? &options[i] : NULL);
3322 } while (err > 0 && !has_codec_parameters(st, NULL));
3325 av_log(ic, AV_LOG_INFO,
3326 "decoding for stream %d failed\n", st->index);
3332 // close codecs which were opened in try_decode_frame()
3333 for (i = 0; i < ic->nb_streams; i++) {
3334 st = ic->streams[i];
3335 avcodec_close(st->codec);
3338 ff_rfps_calculate(ic);
3340 for (i = 0; i < ic->nb_streams; i++) {
3341 st = ic->streams[i];
3342 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3343 if (st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample) {
3344 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
3345 if (avpriv_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
3346 st->codec->codec_tag= tag;
3349 /* estimate average framerate if not set by demuxer */
3350 if (st->info->codec_info_duration_fields &&
3351 !st->avg_frame_rate.num &&
3352 st->info->codec_info_duration) {
3354 double best_error = 0.01;
3356 if (st->info->codec_info_duration >= INT64_MAX / st->time_base.num / 2||
3357 st->info->codec_info_duration_fields >= INT64_MAX / st->time_base.den ||
3358 st->info->codec_info_duration < 0)
3360 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3361 st->info->codec_info_duration_fields * (int64_t) st->time_base.den,
3362 st->info->codec_info_duration * 2 * (int64_t) st->time_base.num, 60000);
3364 /* Round guessed framerate to a "standard" framerate if it's
3365 * within 1% of the original estimate. */
3366 for (j = 0; j < MAX_STD_TIMEBASES; j++) {
3367 AVRational std_fps = { get_std_framerate(j), 12 * 1001 };
3368 double error = fabs(av_q2d(st->avg_frame_rate) /
3369 av_q2d(std_fps) - 1);
3371 if (error < best_error) {
3373 best_fps = std_fps.num;
3377 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
3378 best_fps, 12 * 1001, INT_MAX);
3381 if (!st->r_frame_rate.num) {
3382 if ( st->codec->time_base.den * (int64_t) st->time_base.num
3383 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t) st->time_base.den) {
3384 st->r_frame_rate.num = st->codec->time_base.den;
3385 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
3387 st->r_frame_rate.num = st->time_base.den;
3388 st->r_frame_rate.den = st->time_base.num;
3391 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
3392 if (!st->codec->bits_per_coded_sample)
3393 st->codec->bits_per_coded_sample =
3394 av_get_bits_per_sample(st->codec->codec_id);
3395 // set stream disposition based on audio service type
3396 switch (st->codec->audio_service_type) {
3397 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
3398 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;
3400 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
3401 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;
3403 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
3404 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED;
3406 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
3407 st->disposition = AV_DISPOSITION_COMMENT;
3409 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
3410 st->disposition = AV_DISPOSITION_KARAOKE;
3417 estimate_timings(ic, old_offset);
3419 if (ret >= 0 && ic->nb_streams)
3420 /* We could not have all the codec parameters before EOF. */
3422 for (i = 0; i < ic->nb_streams; i++) {
3424 st = ic->streams[i];
3425 if (!has_codec_parameters(st, &errmsg)) {
3427 avcodec_string(buf, sizeof(buf), st->codec, 0);
3428 av_log(ic, AV_LOG_WARNING,
3429 "Could not find codec parameters for stream %d (%s): %s\n"
3430 "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",
3437 compute_chapters_end(ic);
3439 find_stream_info_err:
3440 for (i = 0; i < ic->nb_streams; i++) {
3441 st = ic->streams[i];
3442 if (ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
3443 ic->streams[i]->codec->thread_count = 0;
3445 av_freep(&st->info->duration_error);
3446 av_freep(&ic->streams[i]->info);
3449 av_log(ic, AV_LOG_DEBUG, "After avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d frames:%d\n",
3450 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, count);
3454 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
3458 for (i = 0; i < ic->nb_programs; i++) {
3459 if (ic->programs[i] == last) {
3463 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
3464 if (ic->programs[i]->stream_index[j] == s)
3465 return ic->programs[i];
3471 int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
3472 int wanted_stream_nb, int related_stream,
3473 AVCodec **decoder_ret, int flags)
3475 int i, nb_streams = ic->nb_streams;
3476 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;
3477 unsigned *program = NULL;
3478 const AVCodec *decoder = NULL, *best_decoder = NULL;
3480 if (related_stream >= 0 && wanted_stream_nb < 0) {
3481 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
3483 program = p->stream_index;
3484 nb_streams = p->nb_stream_indexes;
3487 for (i = 0; i < nb_streams; i++) {
3488 int real_stream_index = program ? program[i] : i;
3489 AVStream *st = ic->streams[real_stream_index];
3490 AVCodecContext *avctx = st->codec;
3491 if (avctx->codec_type != type)
3493 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
3495 if (wanted_stream_nb != real_stream_index &&
3496 st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |
3497 AV_DISPOSITION_VISUAL_IMPAIRED))
3499 if (type == AVMEDIA_TYPE_AUDIO && !avctx->channels)
3502 decoder = find_decoder(ic, st, st->codec->codec_id);
3505 ret = AVERROR_DECODER_NOT_FOUND;
3509 count = st->codec_info_nb_frames;
3510 bitrate = avctx->bit_rate;
3511 multiframe = FFMIN(5, count);
3512 if ((best_multiframe > multiframe) ||
3513 (best_multiframe == multiframe && best_bitrate > bitrate) ||
3514 (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
3517 best_bitrate = bitrate;