2 * various utility functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "avio_internal.h"
25 #include "libavcodec/internal.h"
26 #include "libavcodec/bytestream.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/pixdesc.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/time.h"
38 #include "audiointerleave.h"
50 * various utility functions for use within Libav
53 unsigned avformat_version(void)
55 return LIBAVFORMAT_VERSION_INT;
58 const char *avformat_configuration(void)
60 return LIBAV_CONFIGURATION;
63 const char *avformat_license(void)
65 #define LICENSE_PREFIX "libavformat license: "
66 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
69 /** head of registered input format linked list */
70 static AVInputFormat *first_iformat = NULL;
71 /** head of registered output format linked list */
72 static AVOutputFormat *first_oformat = NULL;
74 AVInputFormat *av_iformat_next(AVInputFormat *f)
77 else return first_iformat;
80 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
83 else return first_oformat;
86 void av_register_input_format(AVInputFormat *format)
90 while (*p != NULL) p = &(*p)->next;
95 void av_register_output_format(AVOutputFormat *format)
99 while (*p != NULL) p = &(*p)->next;
104 int av_match_ext(const char *filename, const char *extensions)
112 ext = strrchr(filename, '.');
118 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
121 if (!av_strcasecmp(ext1, ext))
131 static int match_format(const char *name, const char *names)
139 namelen = strlen(name);
140 while ((p = strchr(names, ','))) {
141 len = FFMAX(p - names, namelen);
142 if (!av_strncasecmp(name, names, len))
146 return !av_strcasecmp(name, names);
149 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
150 const char *mime_type)
152 AVOutputFormat *fmt = NULL, *fmt_found;
153 int score_max, score;
155 /* specific test for image sequences */
156 #if CONFIG_IMAGE2_MUXER
157 if (!short_name && filename &&
158 av_filename_number_test(filename) &&
159 ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {
160 return av_guess_format("image2", NULL, NULL);
163 /* Find the proper file type. */
166 while ((fmt = av_oformat_next(fmt))) {
168 if (fmt->name && short_name && !av_strcasecmp(fmt->name, short_name))
170 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
172 if (filename && fmt->extensions &&
173 av_match_ext(filename, fmt->extensions)) {
176 if (score > score_max) {
184 enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
185 const char *filename, const char *mime_type, enum AVMediaType type){
186 if(type == AVMEDIA_TYPE_VIDEO){
187 enum AVCodecID codec_id= AV_CODEC_ID_NONE;
189 #if CONFIG_IMAGE2_MUXER
190 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
191 codec_id= ff_guess_image2_codec(filename);
194 if(codec_id == AV_CODEC_ID_NONE)
195 codec_id= fmt->video_codec;
197 }else if(type == AVMEDIA_TYPE_AUDIO)
198 return fmt->audio_codec;
199 else if (type == AVMEDIA_TYPE_SUBTITLE)
200 return fmt->subtitle_codec;
202 return AV_CODEC_ID_NONE;
205 AVInputFormat *av_find_input_format(const char *short_name)
207 AVInputFormat *fmt = NULL;
208 while ((fmt = av_iformat_next(fmt))) {
209 if (match_format(short_name, fmt->name))
215 /* an arbitrarily chosen "sane" max packet size -- 50M */
216 #define SANE_CHUNK_SIZE (50000000)
219 * Read the data in sane-sized chunks and append to pkt.
220 * Return the number of bytes read or an error.
222 static int append_packet_chunked(AVIOContext *s, AVPacket *pkt, int size)
224 int64_t chunk_size = size;
225 int orig_pos = pkt->pos; // av_grow_packet might reset pos
226 int orig_size = pkt->size;
230 int prev_size = pkt->size;
234 * When the caller requests a lot of data, limit it to the amount left
235 * in file or SANE_CHUNK_SIZE when it is not known
237 if (size > SANE_CHUNK_SIZE) {
238 int64_t filesize = avio_size(s) - avio_tell(s);
239 chunk_size = FFMAX(filesize, SANE_CHUNK_SIZE);
241 read_size = FFMIN(size, chunk_size);
243 ret = av_grow_packet(pkt, read_size);
247 ret = avio_read(s, pkt->data + prev_size, read_size);
248 if (ret != read_size) {
249 av_shrink_packet(pkt, prev_size + FFMAX(ret, 0));
259 return pkt->size > orig_size ? pkt->size - orig_size : ret;
262 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
267 pkt->pos = avio_tell(s);
269 return append_packet_chunked(s, pkt, size);
272 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
275 return av_get_packet(s, pkt, size);
276 return append_packet_chunked(s, pkt, size);
280 int av_filename_number_test(const char *filename)
283 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
286 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
288 AVProbeData lpd = *pd;
289 AVInputFormat *fmt1 = NULL, *fmt;
292 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
293 int id3len = ff_id3v2_tag_len(lpd.buf);
294 if (lpd.buf_size > id3len + 16) {
296 lpd.buf_size -= id3len;
302 while ((fmt1 = av_iformat_next(fmt1))) {
303 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
306 if (fmt1->read_probe) {
307 score = fmt1->read_probe(&lpd);
308 } else if (fmt1->extensions) {
309 if (av_match_ext(lpd.filename, fmt1->extensions)) {
310 score = AVPROBE_SCORE_EXTENSION;
313 if (score > *score_max) {
316 }else if (score == *score_max)
320 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
321 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_EXTENSION / 2) {
322 while ((fmt = av_iformat_next(fmt)))
323 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
324 *score_max = AVPROBE_SCORE_EXTENSION / 2;
329 if (!fmt && id3 && *score_max < AVPROBE_SCORE_EXTENSION / 2 - 1) {
330 while ((fmt = av_iformat_next(fmt)))
331 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
332 *score_max = AVPROBE_SCORE_EXTENSION / 2 - 1;
340 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
342 return av_probe_input_format2(pd, is_opened, &score);
345 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
347 static const struct {
348 const char *name; enum AVCodecID id; enum AVMediaType type;
350 { "aac" , AV_CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
351 { "ac3" , AV_CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
352 { "dts" , AV_CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
353 { "eac3" , AV_CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
354 { "h264" , AV_CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
355 { "m4v" , AV_CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
356 { "mp3" , AV_CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
357 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
360 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
364 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
365 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
366 for (i = 0; fmt_id_type[i].name; i++) {
367 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
368 st->codec->codec_id = fmt_id_type[i].id;
369 st->codec->codec_type = fmt_id_type[i].type;
377 /************************************************************/
378 /* input media file */
380 /** size of probe buffer, for guessing file type from file contents */
381 #define PROBE_BUF_MIN 2048
382 #define PROBE_BUF_MAX (1<<20)
384 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
385 const char *filename, void *logctx,
386 unsigned int offset, unsigned int max_probe_size)
388 AVProbeData pd = { filename ? filename : "", NULL, -offset };
389 unsigned char *buf = NULL;
390 int ret = 0, probe_size;
392 if (!max_probe_size) {
393 max_probe_size = PROBE_BUF_MAX;
394 } else if (max_probe_size > PROBE_BUF_MAX) {
395 max_probe_size = PROBE_BUF_MAX;
396 } else if (max_probe_size < PROBE_BUF_MIN) {
397 return AVERROR(EINVAL);
400 if (offset >= max_probe_size) {
401 return AVERROR(EINVAL);
404 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
405 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
406 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
407 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
409 if (probe_size < offset) {
413 /* read probe data */
414 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
415 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
416 /* fail if error was not end of file, otherwise, lower score */
417 if (ret != AVERROR_EOF) {
422 ret = 0; /* error was end of file, nothing read */
425 pd.buf = &buf[offset];
427 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
429 /* guess file format */
430 *fmt = av_probe_input_format2(&pd, 1, &score);
432 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
433 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
435 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
441 return AVERROR_INVALIDDATA;
444 /* rewind. reuse probe buffer to avoid seeking */
445 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
451 /* open input file and probe the format if necessary */
452 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
455 AVProbeData pd = {filename, NULL, 0};
458 s->flags |= AVFMT_FLAG_CUSTOM_IO;
460 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
461 else if (s->iformat->flags & AVFMT_NOFILE)
462 return AVERROR(EINVAL);
466 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
467 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
470 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
471 &s->interrupt_callback, options)) < 0)
475 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
478 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
479 AVPacketList **plast_pktl){
480 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
485 (*plast_pktl)->next = pktl;
487 *packet_buffer = pktl;
489 /* add the packet in the buffered packet list */
495 static int queue_attached_pictures(AVFormatContext *s)
498 for (i = 0; i < s->nb_streams; i++)
499 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
500 s->streams[i]->discard < AVDISCARD_ALL) {
501 AVPacket copy = s->streams[i]->attached_pic;
502 copy.buf = av_buffer_ref(copy.buf);
504 return AVERROR(ENOMEM);
506 add_to_pktbuf(&s->raw_packet_buffer, ©, &s->raw_packet_buffer_end);
511 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
513 AVFormatContext *s = *ps;
515 AVDictionary *tmp = NULL;
516 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
518 if (!s && !(s = avformat_alloc_context()))
519 return AVERROR(ENOMEM);
524 av_dict_copy(&tmp, *options, 0);
526 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
529 if ((ret = init_input(s, filename, &tmp)) < 0)
532 /* check filename in case an image number is expected */
533 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
534 if (!av_filename_number_test(filename)) {
535 ret = AVERROR(EINVAL);
540 s->duration = s->start_time = AV_NOPTS_VALUE;
541 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
543 /* allocate private data */
544 if (s->iformat->priv_data_size > 0) {
545 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
546 ret = AVERROR(ENOMEM);
549 if (s->iformat->priv_class) {
550 *(const AVClass**)s->priv_data = s->iformat->priv_class;
551 av_opt_set_defaults(s->priv_data);
552 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
557 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
559 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
561 if (s->iformat->read_header)
562 if ((ret = s->iformat->read_header(s)) < 0)
565 if (id3v2_extra_meta &&
566 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
568 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
570 if ((ret = queue_attached_pictures(s)) < 0)
573 if (s->pb && !s->data_offset)
574 s->data_offset = avio_tell(s->pb);
576 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
579 av_dict_free(options);
586 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
588 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
590 avformat_free_context(s);
595 /*******************************************************/
597 static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
599 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
600 AVProbeData *pd = &st->probe_data;
601 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
605 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
606 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
607 pd->buf_size += pkt->size;
608 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
610 st->probe_packets = 0;
612 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
618 if (!st->probe_packets ||
619 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
620 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
621 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
624 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
630 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
636 AVPacketList *pktl = s->raw_packet_buffer;
640 st = s->streams[pkt->stream_index];
641 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
642 s->raw_packet_buffer_remaining_size < pkt->size) {
644 if (st->probe_packets) {
645 probe_codec(s, st, NULL);
647 pd = &st->probe_data;
650 s->raw_packet_buffer = pktl->next;
651 s->raw_packet_buffer_remaining_size += pkt->size;
660 ret= s->iformat->read_packet(s, pkt);
662 if (!pktl || ret == AVERROR(EAGAIN))
664 for (i = 0; i < s->nb_streams; i++) {
666 if (st->probe_packets) {
667 probe_codec(s, st, NULL);
673 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
674 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
675 av_log(s, AV_LOG_WARNING,
676 "Dropped corrupted packet (stream = %d)\n",
682 st= s->streams[pkt->stream_index];
684 switch(st->codec->codec_type){
685 case AVMEDIA_TYPE_VIDEO:
686 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
688 case AVMEDIA_TYPE_AUDIO:
689 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
691 case AVMEDIA_TYPE_SUBTITLE:
692 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
696 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
700 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
701 s->raw_packet_buffer_remaining_size -= pkt->size;
703 probe_codec(s, st, pkt);
707 /**********************************************************/
710 * Get the number of samples of an audio frame. Return -1 on error.
712 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
716 /* give frame_size priority if demuxing */
717 if (!mux && enc->frame_size > 1)
718 return enc->frame_size;
720 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
723 /* Fall back on using frame_size if muxing. */
724 if (enc->frame_size > 1)
725 return enc->frame_size;
732 * Return the frame duration in seconds. Return 0 if not available.
734 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
735 AVCodecParserContext *pc, AVPacket *pkt)
741 switch(st->codec->codec_type) {
742 case AVMEDIA_TYPE_VIDEO:
743 if (st->avg_frame_rate.num) {
744 *pnum = st->avg_frame_rate.den;
745 *pden = st->avg_frame_rate.num;
746 } else if(st->time_base.num*1000LL > st->time_base.den) {
747 *pnum = st->time_base.num;
748 *pden = st->time_base.den;
749 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
750 *pnum = st->codec->time_base.num;
751 *pden = st->codec->time_base.den;
752 if (pc && pc->repeat_pict) {
753 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
754 *pden /= 1 + pc->repeat_pict;
756 *pnum *= 1 + pc->repeat_pict;
758 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
759 //Thus if we have no parser in such case leave duration undefined.
760 if(st->codec->ticks_per_frame>1 && !pc){
765 case AVMEDIA_TYPE_AUDIO:
766 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
767 if (frame_size <= 0 || st->codec->sample_rate <= 0)
770 *pden = st->codec->sample_rate;
777 static int is_intra_only(enum AVCodecID id)
779 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
782 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
787 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
788 int64_t dts, int64_t pts)
790 AVStream *st= s->streams[stream_index];
791 AVPacketList *pktl= s->packet_buffer;
793 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
796 st->first_dts= dts - st->cur_dts;
799 for(; pktl; pktl= pktl->next){
800 if(pktl->pkt.stream_index != stream_index)
802 //FIXME think more about this check
803 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
804 pktl->pkt.pts += st->first_dts;
806 if(pktl->pkt.dts != AV_NOPTS_VALUE)
807 pktl->pkt.dts += st->first_dts;
809 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
810 st->start_time= pktl->pkt.pts;
812 if (st->start_time == AV_NOPTS_VALUE)
813 st->start_time = pts;
816 static void update_initial_durations(AVFormatContext *s, AVStream *st,
817 int stream_index, int duration)
819 AVPacketList *pktl= s->packet_buffer;
822 if(st->first_dts != AV_NOPTS_VALUE){
823 cur_dts= st->first_dts;
824 for(; pktl; pktl= pktl->next){
825 if(pktl->pkt.stream_index == stream_index){
826 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
831 pktl= s->packet_buffer;
832 st->first_dts = cur_dts;
833 }else if(st->cur_dts)
836 for(; pktl; pktl= pktl->next){
837 if(pktl->pkt.stream_index != stream_index)
839 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
840 && !pktl->pkt.duration){
841 pktl->pkt.dts= cur_dts;
842 if(!st->codec->has_b_frames)
843 pktl->pkt.pts= cur_dts;
845 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
846 pktl->pkt.duration = duration;
850 if(st->first_dts == AV_NOPTS_VALUE)
851 st->cur_dts= cur_dts;
854 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
855 AVCodecParserContext *pc, AVPacket *pkt)
857 int num, den, presentation_delayed, delay, i;
860 if (s->flags & AVFMT_FLAG_NOFILLIN)
863 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
864 pkt->dts= AV_NOPTS_VALUE;
866 /* do we have a video B-frame ? */
867 delay= st->codec->has_b_frames;
868 presentation_delayed = 0;
870 /* XXX: need has_b_frame, but cannot get it if the codec is
873 pc && pc->pict_type != AV_PICTURE_TYPE_B)
874 presentation_delayed = 1;
876 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
877 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
878 pkt->dts -= 1LL<<st->pts_wrap_bits;
881 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
882 // we take the conservative approach and discard both
883 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
884 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
885 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
886 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
889 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
890 ff_compute_frame_duration(&num, &den, st, pc, pkt);
892 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
894 if(pkt->duration != 0 && s->packet_buffer)
895 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
899 /* correct timestamps with byte offset if demuxers only have timestamps
900 on packet boundaries */
901 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
902 /* this will estimate bitrate based on this frame's duration and size */
903 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
904 if(pkt->pts != AV_NOPTS_VALUE)
906 if(pkt->dts != AV_NOPTS_VALUE)
910 if (pc && pc->dts_sync_point >= 0) {
911 // we have synchronization info from the parser
912 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
914 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
915 if (pkt->dts != AV_NOPTS_VALUE) {
916 // got DTS from the stream, update reference timestamp
917 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
918 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
919 } else if (st->reference_dts != AV_NOPTS_VALUE) {
920 // compute DTS based on reference timestamp
921 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
922 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
924 if (pc->dts_sync_point > 0)
925 st->reference_dts = pkt->dts; // new reference
929 /* This may be redundant, but it should not hurt. */
930 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
931 presentation_delayed = 1;
934 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
935 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
936 pkt->stream_index, pc);
937 /* interpolate PTS and DTS if they are not present */
938 //We skip H264 currently because delay and has_b_frames are not reliably set
939 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
940 if (presentation_delayed) {
941 /* DTS = decompression timestamp */
942 /* PTS = presentation timestamp */
943 if (pkt->dts == AV_NOPTS_VALUE)
944 pkt->dts = st->last_IP_pts;
945 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
946 if (pkt->dts == AV_NOPTS_VALUE)
947 pkt->dts = st->cur_dts;
949 /* this is tricky: the dts must be incremented by the duration
950 of the frame we are displaying, i.e. the last I- or P-frame */
951 if (st->last_IP_duration == 0)
952 st->last_IP_duration = pkt->duration;
953 if(pkt->dts != AV_NOPTS_VALUE)
954 st->cur_dts = pkt->dts + st->last_IP_duration;
955 st->last_IP_duration = pkt->duration;
956 st->last_IP_pts= pkt->pts;
957 /* cannot compute PTS if not present (we can compute it only
958 by knowing the future */
959 } else if (pkt->pts != AV_NOPTS_VALUE ||
960 pkt->dts != AV_NOPTS_VALUE ||
962 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
963 int duration = pkt->duration;
964 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
965 ff_compute_frame_duration(&num, &den, st, pc, pkt);
967 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
968 den * (int64_t)st->time_base.num,
970 if (duration != 0 && s->packet_buffer) {
971 update_initial_durations(s, st, pkt->stream_index,
977 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
979 /* presentation is not delayed : PTS and DTS are the same */
980 if (pkt->pts == AV_NOPTS_VALUE)
982 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
984 if (pkt->pts == AV_NOPTS_VALUE)
985 pkt->pts = st->cur_dts;
987 if (pkt->pts != AV_NOPTS_VALUE)
988 st->cur_dts = pkt->pts + duration;
993 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
994 st->pts_buffer[0]= pkt->pts;
995 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
996 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
997 if(pkt->dts == AV_NOPTS_VALUE)
998 pkt->dts= st->pts_buffer[0];
999 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
1000 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1002 if(pkt->dts > st->cur_dts)
1003 st->cur_dts = pkt->dts;
1007 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
1008 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1011 if (is_intra_only(st->codec->codec_id))
1012 pkt->flags |= AV_PKT_FLAG_KEY;
1014 pkt->convergence_duration = pc->convergence_duration;
1017 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
1020 AVPacketList *pktl = *pkt_buf;
1021 *pkt_buf = pktl->next;
1022 av_free_packet(&pktl->pkt);
1025 *pkt_buf_end = NULL;
1029 * Parse a packet, add all split parts to parse_queue
1031 * @param pkt packet to parse, NULL when flushing the parser at end of stream
1033 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1035 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1036 AVStream *st = s->streams[stream_index];
1037 uint8_t *data = pkt ? pkt->data : NULL;
1038 int size = pkt ? pkt->size : 0;
1039 int ret = 0, got_output = 0;
1042 av_init_packet(&flush_pkt);
1047 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1050 av_init_packet(&out_pkt);
1051 len = av_parser_parse2(st->parser, st->codec,
1052 &out_pkt.data, &out_pkt.size, data, size,
1053 pkt->pts, pkt->dts, pkt->pos);
1055 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1056 /* increment read pointer */
1060 got_output = !!out_pkt.size;
1065 if (pkt->side_data) {
1066 out_pkt.side_data = pkt->side_data;
1067 out_pkt.side_data_elems = pkt->side_data_elems;
1068 pkt->side_data = NULL;
1069 pkt->side_data_elems = 0;
1072 /* set the duration */
1073 out_pkt.duration = 0;
1074 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1075 if (st->codec->sample_rate > 0) {
1076 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1077 (AVRational){ 1, st->codec->sample_rate },
1081 } else if (st->codec->time_base.num != 0 &&
1082 st->codec->time_base.den != 0) {
1083 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1084 st->codec->time_base,
1089 out_pkt.stream_index = st->index;
1090 out_pkt.pts = st->parser->pts;
1091 out_pkt.dts = st->parser->dts;
1092 out_pkt.pos = st->parser->pos;
1094 if (st->parser->key_frame == 1 ||
1095 (st->parser->key_frame == -1 &&
1096 st->parser->pict_type == AV_PICTURE_TYPE_I))
1097 out_pkt.flags |= AV_PKT_FLAG_KEY;
1099 compute_pkt_fields(s, st, st->parser, &out_pkt);
1101 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1102 out_pkt.flags & AV_PKT_FLAG_KEY) {
1103 ff_reduce_index(s, st->index);
1104 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
1105 0, 0, AVINDEX_KEYFRAME);
1108 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1109 out_pkt.buf = pkt->buf;
1111 #if FF_API_DESTRUCT_PACKET
1112 out_pkt.destruct = pkt->destruct;
1113 pkt->destruct = NULL;
1116 if ((ret = av_dup_packet(&out_pkt)) < 0)
1119 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1120 av_free_packet(&out_pkt);
1121 ret = AVERROR(ENOMEM);
1127 /* end of the stream => close and free the parser */
1128 if (pkt == &flush_pkt) {
1129 av_parser_close(st->parser);
1134 av_free_packet(pkt);
1138 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1139 AVPacketList **pkt_buffer_end,
1143 av_assert0(*pkt_buffer);
1146 *pkt_buffer = pktl->next;
1148 *pkt_buffer_end = NULL;
1153 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1155 int ret = 0, i, got_packet = 0;
1157 av_init_packet(pkt);
1159 while (!got_packet && !s->parse_queue) {
1163 /* read next packet */
1164 ret = ff_read_packet(s, &cur_pkt);
1166 if (ret == AVERROR(EAGAIN))
1168 /* flush the parsers */
1169 for(i = 0; i < s->nb_streams; i++) {
1171 if (st->parser && st->need_parsing)
1172 parse_packet(s, NULL, st->index);
1174 /* all remaining packets are now in parse_queue =>
1175 * really terminate parsing */
1179 st = s->streams[cur_pkt.stream_index];
1181 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1182 cur_pkt.dts != AV_NOPTS_VALUE &&
1183 cur_pkt.pts < cur_pkt.dts) {
1184 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1185 cur_pkt.stream_index,
1190 if (s->debug & FF_FDEBUG_TS)
1191 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1192 cur_pkt.stream_index,
1199 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1200 st->parser = av_parser_init(st->codec->codec_id);
1202 /* no parser available: just output the raw packets */
1203 st->need_parsing = AVSTREAM_PARSE_NONE;
1204 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1205 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1206 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1207 st->parser->flags |= PARSER_FLAG_ONCE;
1211 if (!st->need_parsing || !st->parser) {
1212 /* no parsing needed: we just output the packet as is */
1214 compute_pkt_fields(s, st, NULL, pkt);
1215 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1216 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1217 ff_reduce_index(s, st->index);
1218 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1221 } else if (st->discard < AVDISCARD_ALL) {
1222 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1226 av_free_packet(&cur_pkt);
1230 if (!got_packet && s->parse_queue)
1231 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1233 if(s->debug & FF_FDEBUG_TS)
1234 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1245 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1247 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1251 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1252 &s->packet_buffer_end,
1254 read_frame_internal(s, pkt);
1258 AVPacketList *pktl = s->packet_buffer;
1261 AVPacket *next_pkt = &pktl->pkt;
1263 if (next_pkt->dts != AV_NOPTS_VALUE) {
1264 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1265 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1266 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1267 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1268 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1269 next_pkt->pts = pktl->pkt.dts;
1273 pktl = s->packet_buffer;
1276 /* read packet from packet buffer, if there is data */
1277 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1278 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1279 return read_from_packet_buffer(&s->packet_buffer,
1280 &s->packet_buffer_end, pkt);
1283 ret = read_frame_internal(s, pkt);
1285 if (pktl && ret != AVERROR(EAGAIN)) {
1292 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1293 &s->packet_buffer_end)) < 0)
1294 return AVERROR(ENOMEM);
1298 /* XXX: suppress the packet queue */
1299 static void flush_packet_queue(AVFormatContext *s)
1301 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1302 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1303 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1305 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1308 /*******************************************************/
1311 int av_find_default_stream_index(AVFormatContext *s)
1313 int first_audio_index = -1;
1317 if (s->nb_streams <= 0)
1319 for(i = 0; i < s->nb_streams; i++) {
1321 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1322 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1325 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1326 first_audio_index = i;
1328 return first_audio_index >= 0 ? first_audio_index : 0;
1332 * Flush the frame reader.
1334 void ff_read_frame_flush(AVFormatContext *s)
1339 flush_packet_queue(s);
1341 /* for each stream, reset read state */
1342 for(i = 0; i < s->nb_streams; i++) {
1346 av_parser_close(st->parser);
1349 st->last_IP_pts = AV_NOPTS_VALUE;
1350 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1351 st->reference_dts = AV_NOPTS_VALUE;
1353 st->probe_packets = MAX_PROBE_PACKETS;
1355 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1356 st->pts_buffer[j]= AV_NOPTS_VALUE;
1360 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1364 for(i = 0; i < s->nb_streams; i++) {
1365 AVStream *st = s->streams[i];
1367 st->cur_dts = av_rescale(timestamp,
1368 st->time_base.den * (int64_t)ref_st->time_base.num,
1369 st->time_base.num * (int64_t)ref_st->time_base.den);
1373 void ff_reduce_index(AVFormatContext *s, int stream_index)
1375 AVStream *st= s->streams[stream_index];
1376 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1378 if((unsigned)st->nb_index_entries >= max_entries){
1380 for(i=0; 2*i<st->nb_index_entries; i++)
1381 st->index_entries[i]= st->index_entries[2*i];
1382 st->nb_index_entries= i;
1386 int ff_add_index_entry(AVIndexEntry **index_entries,
1387 int *nb_index_entries,
1388 unsigned int *index_entries_allocated_size,
1389 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1391 AVIndexEntry *entries, *ie;
1394 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1397 entries = av_fast_realloc(*index_entries,
1398 index_entries_allocated_size,
1399 (*nb_index_entries + 1) *
1400 sizeof(AVIndexEntry));
1404 *index_entries= entries;
1406 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1409 index= (*nb_index_entries)++;
1410 ie= &entries[index];
1411 assert(index==0 || ie[-1].timestamp < timestamp);
1413 ie= &entries[index];
1414 if(ie->timestamp != timestamp){
1415 if(ie->timestamp <= timestamp)
1417 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1418 (*nb_index_entries)++;
1419 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1420 distance= ie->min_distance;
1424 ie->timestamp = timestamp;
1425 ie->min_distance= distance;
1432 int av_add_index_entry(AVStream *st,
1433 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1435 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1436 &st->index_entries_allocated_size, pos,
1437 timestamp, size, distance, flags);
1440 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1441 int64_t wanted_timestamp, int flags)
1449 //optimize appending index entries at the end
1450 if(b && entries[b-1].timestamp < wanted_timestamp)
1455 timestamp = entries[m].timestamp;
1456 if(timestamp >= wanted_timestamp)
1458 if(timestamp <= wanted_timestamp)
1461 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1463 if(!(flags & AVSEEK_FLAG_ANY)){
1464 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1465 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1474 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1477 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1478 wanted_timestamp, flags);
1481 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1483 AVInputFormat *avif= s->iformat;
1484 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1485 int64_t ts_min, ts_max, ts;
1490 if (stream_index < 0)
1493 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1496 ts_min= AV_NOPTS_VALUE;
1497 pos_limit= -1; //gcc falsely says it may be uninitialized
1499 st= s->streams[stream_index];
1500 if(st->index_entries){
1503 index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()
1504 index= FFMAX(index, 0);
1505 e= &st->index_entries[index];
1507 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1509 ts_min= e->timestamp;
1510 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1516 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1517 assert(index < st->nb_index_entries);
1519 e= &st->index_entries[index];
1520 assert(e->timestamp >= target_ts);
1522 ts_max= e->timestamp;
1523 pos_limit= pos_max - e->min_distance;
1524 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1525 pos_max,pos_limit, ts_max);
1529 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1534 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1537 ff_update_cur_dts(s, st, ts);
1542 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1543 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1544 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1545 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1548 int64_t start_pos, filesize;
1551 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1553 if(ts_min == AV_NOPTS_VALUE){
1554 pos_min = s->data_offset;
1555 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1556 if (ts_min == AV_NOPTS_VALUE)
1560 if(ts_max == AV_NOPTS_VALUE){
1562 filesize = avio_size(s->pb);
1563 pos_max = filesize - 1;
1566 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1568 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1569 if (ts_max == AV_NOPTS_VALUE)
1573 int64_t tmp_pos= pos_max + 1;
1574 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1575 if(tmp_ts == AV_NOPTS_VALUE)
1579 if(tmp_pos >= filesize)
1585 if(ts_min > ts_max){
1587 }else if(ts_min == ts_max){
1592 while (pos_min < pos_limit) {
1593 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1594 pos_min, pos_max, ts_min, ts_max);
1595 assert(pos_limit <= pos_max);
1598 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1599 // interpolate position (better than dichotomy)
1600 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1601 + pos_min - approximate_keyframe_distance;
1602 }else if(no_change==1){
1603 // bisection, if interpolation failed to change min or max pos last time
1604 pos = (pos_min + pos_limit)>>1;
1606 /* linear search if bisection failed, can only happen if there
1607 are very few or no keyframes between min/max */
1612 else if(pos > pos_limit)
1616 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1621 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1622 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1623 pos_limit, start_pos, no_change);
1624 if(ts == AV_NOPTS_VALUE){
1625 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1628 assert(ts != AV_NOPTS_VALUE);
1629 if (target_ts <= ts) {
1630 pos_limit = start_pos - 1;
1634 if (target_ts >= ts) {
1640 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1641 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1643 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1645 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1646 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1647 pos, ts_min, target_ts, ts_max);
1652 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1653 int64_t pos_min, pos_max;
1655 pos_min = s->data_offset;
1656 pos_max = avio_size(s->pb) - 1;
1658 if (pos < pos_min) pos= pos_min;
1659 else if(pos > pos_max) pos= pos_max;
1661 avio_seek(s->pb, pos, SEEK_SET);
1666 static int seek_frame_generic(AVFormatContext *s,
1667 int stream_index, int64_t timestamp, int flags)
1674 st = s->streams[stream_index];
1676 index = av_index_search_timestamp(st, timestamp, flags);
1678 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1681 if(index < 0 || index==st->nb_index_entries-1){
1684 if(st->nb_index_entries){
1685 assert(st->index_entries);
1686 ie= &st->index_entries[st->nb_index_entries-1];
1687 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1689 ff_update_cur_dts(s, st, ie->timestamp);
1691 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1697 read_status = av_read_frame(s, &pkt);
1698 } while (read_status == AVERROR(EAGAIN));
1699 if (read_status < 0)
1701 av_free_packet(&pkt);
1702 if(stream_index == pkt.stream_index){
1703 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1707 index = av_index_search_timestamp(st, timestamp, flags);
1712 ff_read_frame_flush(s);
1713 if (s->iformat->read_seek){
1714 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1717 ie = &st->index_entries[index];
1718 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1720 ff_update_cur_dts(s, st, ie->timestamp);
1725 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1726 int64_t timestamp, int flags)
1731 if (flags & AVSEEK_FLAG_BYTE) {
1732 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1734 ff_read_frame_flush(s);
1735 return seek_frame_byte(s, stream_index, timestamp, flags);
1738 if(stream_index < 0){
1739 stream_index= av_find_default_stream_index(s);
1740 if(stream_index < 0)
1743 st= s->streams[stream_index];
1744 /* timestamp for default must be expressed in AV_TIME_BASE units */
1745 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1748 /* first, we try the format specific seek */
1749 if (s->iformat->read_seek) {
1750 ff_read_frame_flush(s);
1751 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1758 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1759 ff_read_frame_flush(s);
1760 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1761 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1762 ff_read_frame_flush(s);
1763 return seek_frame_generic(s, stream_index, timestamp, flags);
1769 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1771 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1774 ret = queue_attached_pictures(s);
1779 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1781 if(min_ts > ts || max_ts < ts)
1784 if (s->iformat->read_seek2) {
1786 ff_read_frame_flush(s);
1787 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1790 ret = queue_attached_pictures(s);
1794 if(s->iformat->read_timestamp){
1795 //try to seek via read_timestamp()
1798 // Fall back on old API if new is not implemented but old is.
1799 // Note the old API has somewhat different semantics.
1800 if(s->iformat->read_seek || 1)
1801 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1803 // try some generic seek like seek_frame_generic() but with new ts semantics
1806 /*******************************************************/
1809 * Return TRUE if the stream has accurate duration in any stream.
1811 * @return TRUE if the stream has accurate duration for at least one component.
1813 static int has_duration(AVFormatContext *ic)
1818 for(i = 0;i < ic->nb_streams; i++) {
1819 st = ic->streams[i];
1820 if (st->duration != AV_NOPTS_VALUE)
1823 if (ic->duration != AV_NOPTS_VALUE)
1829 * Estimate the stream timings from the one of each components.
1831 * Also computes the global bitrate if possible.
1833 static void update_stream_timings(AVFormatContext *ic)
1835 int64_t start_time, start_time1, end_time, end_time1;
1836 int64_t duration, duration1, filesize;
1840 start_time = INT64_MAX;
1841 end_time = INT64_MIN;
1842 duration = INT64_MIN;
1843 for(i = 0;i < ic->nb_streams; i++) {
1844 st = ic->streams[i];
1845 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1846 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1847 start_time = FFMIN(start_time, start_time1);
1848 if (st->duration != AV_NOPTS_VALUE) {
1849 end_time1 = start_time1
1850 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1851 end_time = FFMAX(end_time, end_time1);
1854 if (st->duration != AV_NOPTS_VALUE) {
1855 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1856 duration = FFMAX(duration, duration1);
1859 if (start_time != INT64_MAX) {
1860 ic->start_time = start_time;
1861 if (end_time != INT64_MIN)
1862 duration = FFMAX(duration, end_time - start_time);
1864 if (duration != INT64_MIN) {
1865 ic->duration = duration;
1866 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1867 /* compute the bitrate */
1868 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1869 (double)ic->duration;
1874 static void fill_all_stream_timings(AVFormatContext *ic)
1879 update_stream_timings(ic);
1880 for(i = 0;i < ic->nb_streams; i++) {
1881 st = ic->streams[i];
1882 if (st->start_time == AV_NOPTS_VALUE) {
1883 if(ic->start_time != AV_NOPTS_VALUE)
1884 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1885 if(ic->duration != AV_NOPTS_VALUE)
1886 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1891 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1893 int64_t filesize, duration;
1897 /* if bit_rate is already set, we believe it */
1898 if (ic->bit_rate <= 0) {
1900 for(i=0;i<ic->nb_streams;i++) {
1901 st = ic->streams[i];
1902 if (st->codec->bit_rate > 0)
1903 bit_rate += st->codec->bit_rate;
1905 ic->bit_rate = bit_rate;
1908 /* if duration is already set, we believe it */
1909 if (ic->duration == AV_NOPTS_VALUE &&
1910 ic->bit_rate != 0) {
1911 filesize = ic->pb ? avio_size(ic->pb) : 0;
1913 for(i = 0; i < ic->nb_streams; i++) {
1914 st = ic->streams[i];
1915 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1916 if (st->duration == AV_NOPTS_VALUE)
1917 st->duration = duration;
1923 #define DURATION_MAX_READ_SIZE 250000
1924 #define DURATION_MAX_RETRY 3
1926 /* only usable for MPEG-PS streams */
1927 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1929 AVPacket pkt1, *pkt = &pkt1;
1931 int read_size, i, ret;
1933 int64_t filesize, offset, duration;
1936 /* flush packet queue */
1937 flush_packet_queue(ic);
1939 for (i=0; i<ic->nb_streams; i++) {
1940 st = ic->streams[i];
1941 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1942 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1945 av_parser_close(st->parser);
1950 /* estimate the end time (duration) */
1951 /* XXX: may need to support wrapping */
1952 filesize = ic->pb ? avio_size(ic->pb) : 0;
1953 end_time = AV_NOPTS_VALUE;
1955 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1959 avio_seek(ic->pb, offset, SEEK_SET);
1962 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1966 ret = ff_read_packet(ic, pkt);
1967 } while(ret == AVERROR(EAGAIN));
1970 read_size += pkt->size;
1971 st = ic->streams[pkt->stream_index];
1972 if (pkt->pts != AV_NOPTS_VALUE &&
1973 (st->start_time != AV_NOPTS_VALUE ||
1974 st->first_dts != AV_NOPTS_VALUE)) {
1975 duration = end_time = pkt->pts;
1976 if (st->start_time != AV_NOPTS_VALUE)
1977 duration -= st->start_time;
1979 duration -= st->first_dts;
1981 duration += 1LL<<st->pts_wrap_bits;
1983 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1984 st->duration = duration;
1987 av_free_packet(pkt);
1989 }while( end_time==AV_NOPTS_VALUE
1990 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1991 && ++retry <= DURATION_MAX_RETRY);
1993 fill_all_stream_timings(ic);
1995 avio_seek(ic->pb, old_offset, SEEK_SET);
1996 for (i=0; i<ic->nb_streams; i++) {
1998 st->cur_dts= st->first_dts;
1999 st->last_IP_pts = AV_NOPTS_VALUE;
2000 st->reference_dts = AV_NOPTS_VALUE;
2004 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2008 /* get the file size, if possible */
2009 if (ic->iformat->flags & AVFMT_NOFILE) {
2012 file_size = avio_size(ic->pb);
2013 file_size = FFMAX(0, file_size);
2016 if ((!strcmp(ic->iformat->name, "mpeg") ||
2017 !strcmp(ic->iformat->name, "mpegts")) &&
2018 file_size && ic->pb->seekable) {
2019 /* get accurate estimate from the PTSes */
2020 estimate_timings_from_pts(ic, old_offset);
2021 } else if (has_duration(ic)) {
2022 /* at least one component has timings - we use them for all
2024 fill_all_stream_timings(ic);
2026 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2027 /* less precise: use bitrate info */
2028 estimate_timings_from_bit_rate(ic);
2030 update_stream_timings(ic);
2034 AVStream av_unused *st;
2035 for(i = 0;i < ic->nb_streams; i++) {
2036 st = ic->streams[i];
2037 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2038 (double) st->start_time / AV_TIME_BASE,
2039 (double) st->duration / AV_TIME_BASE);
2041 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2042 (double) ic->start_time / AV_TIME_BASE,
2043 (double) ic->duration / AV_TIME_BASE,
2044 ic->bit_rate / 1000);
2048 static int has_codec_parameters(AVStream *st)
2050 AVCodecContext *avctx = st->codec;
2052 switch (avctx->codec_type) {
2053 case AVMEDIA_TYPE_AUDIO:
2054 val = avctx->sample_rate && avctx->channels;
2055 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2058 case AVMEDIA_TYPE_VIDEO:
2060 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2067 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2070 static int has_decode_delay_been_guessed(AVStream *st)
2072 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2073 st->info->nb_decoded_frames >= 6;
2076 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2077 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2079 const AVCodec *codec;
2080 int got_picture = 1, ret = 0;
2081 AVFrame *frame = avcodec_alloc_frame();
2082 AVPacket pkt = *avpkt;
2085 return AVERROR(ENOMEM);
2087 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2088 AVDictionary *thread_opt = NULL;
2090 codec = st->codec->codec ? st->codec->codec :
2091 avcodec_find_decoder(st->codec->codec_id);
2094 st->info->found_decoder = -1;
2099 /* force thread count to 1 since the h264 decoder will not extract SPS
2100 * and PPS to extradata during multi-threaded decoding */
2101 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2102 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2104 av_dict_free(&thread_opt);
2106 st->info->found_decoder = -1;
2109 st->info->found_decoder = 1;
2110 } else if (!st->info->found_decoder)
2111 st->info->found_decoder = 1;
2113 if (st->info->found_decoder < 0) {
2118 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2120 (!has_codec_parameters(st) ||
2121 !has_decode_delay_been_guessed(st) ||
2122 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2124 avcodec_get_frame_defaults(frame);
2125 switch(st->codec->codec_type) {
2126 case AVMEDIA_TYPE_VIDEO:
2127 ret = avcodec_decode_video2(st->codec, frame,
2128 &got_picture, &pkt);
2130 case AVMEDIA_TYPE_AUDIO:
2131 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2138 st->info->nb_decoded_frames++;
2146 avcodec_free_frame(&frame);
2150 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2152 while (tags->id != AV_CODEC_ID_NONE) {
2160 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2163 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2164 if(tag == tags[i].tag)
2167 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2168 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2171 return AV_CODEC_ID_NONE;
2174 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2178 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2179 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2180 default: return AV_CODEC_ID_NONE;
2184 if (sflags & (1 << (bps - 1))) {
2186 case 1: return AV_CODEC_ID_PCM_S8;
2187 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2188 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2189 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2190 default: return AV_CODEC_ID_NONE;
2194 case 1: return AV_CODEC_ID_PCM_U8;
2195 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2196 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2197 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2198 default: return AV_CODEC_ID_NONE;
2204 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2207 for(i=0; tags && tags[i]; i++){
2208 int tag= ff_codec_get_tag(tags[i], id);
2214 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2217 for(i=0; tags && tags[i]; i++){
2218 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2219 if(id!=AV_CODEC_ID_NONE) return id;
2221 return AV_CODEC_ID_NONE;
2224 static void compute_chapters_end(AVFormatContext *s)
2227 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2229 for (i = 0; i < s->nb_chapters; i++)
2230 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2231 AVChapter *ch = s->chapters[i];
2232 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2235 for (j = 0; j < s->nb_chapters; j++) {
2236 AVChapter *ch1 = s->chapters[j];
2237 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2238 if (j != i && next_start > ch->start && next_start < end)
2241 ch->end = (end == INT64_MAX) ? ch->start : end;
2245 static int get_std_framerate(int i){
2246 if(i<60*12) return i*1001;
2247 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2251 * Is the time base unreliable.
2252 * This is a heuristic to balance between quick acceptance of the values in
2253 * the headers vs. some extra checks.
2254 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2255 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2256 * And there are "variable" fps files this needs to detect as well.
2258 static int tb_unreliable(AVCodecContext *c){
2259 if( c->time_base.den >= 101L*c->time_base.num
2260 || c->time_base.den < 5L*c->time_base.num
2261 /* || c->codec_tag == AV_RL32("DIVX")
2262 || c->codec_tag == AV_RL32("XVID")*/
2263 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2264 || c->codec_id == AV_CODEC_ID_H264
2270 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2272 int i, count, ret, read_size, j;
2274 AVPacket pkt1, *pkt;
2275 int64_t old_offset = avio_tell(ic->pb);
2276 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2278 for(i=0;i<ic->nb_streams;i++) {
2279 const AVCodec *codec;
2280 AVDictionary *thread_opt = NULL;
2281 st = ic->streams[i];
2283 //only for the split stuff
2284 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2285 st->parser = av_parser_init(st->codec->codec_id);
2286 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2287 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2290 codec = st->codec->codec ? st->codec->codec :
2291 avcodec_find_decoder(st->codec->codec_id);
2293 /* force thread count to 1 since the h264 decoder will not extract SPS
2294 * and PPS to extradata during multi-threaded decoding */
2295 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2297 /* Ensure that subtitle_header is properly set. */
2298 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2299 && codec && !st->codec->codec)
2300 avcodec_open2(st->codec, codec, options ? &options[i]
2303 //try to just open decoders, in case this is enough to get parameters
2304 if (!has_codec_parameters(st)) {
2305 if (codec && !st->codec->codec)
2306 avcodec_open2(st->codec, codec, options ? &options[i]
2310 av_dict_free(&thread_opt);
2313 for (i=0; i<ic->nb_streams; i++) {
2314 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2315 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2321 if (ff_check_interrupt(&ic->interrupt_callback)){
2323 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2327 /* check if one codec still needs to be handled */
2328 for(i=0;i<ic->nb_streams;i++) {
2329 int fps_analyze_framecount = 20;
2331 st = ic->streams[i];
2332 if (!has_codec_parameters(st))
2334 /* if the timebase is coarse (like the usual millisecond precision
2335 of mkv), we need to analyze more frames to reliably arrive at
2337 if (av_q2d(st->time_base) > 0.0005)
2338 fps_analyze_framecount *= 2;
2339 if (ic->fps_probe_size >= 0)
2340 fps_analyze_framecount = ic->fps_probe_size;
2341 /* variable fps and no guess at the real fps */
2342 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2343 && st->codec_info_nb_frames < fps_analyze_framecount
2344 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2346 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2348 if (st->first_dts == AV_NOPTS_VALUE &&
2349 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2350 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2353 if (i == ic->nb_streams) {
2354 /* NOTE: if the format has no header, then we need to read
2355 some packets to get most of the streams, so we cannot
2357 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2358 /* if we found the info for all the codecs, we can stop */
2360 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2364 /* we did not get all the codec info, but we read too much data */
2365 if (read_size >= ic->probesize) {
2367 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2371 /* NOTE: a new stream can be added there if no header in file
2372 (AVFMTCTX_NOHEADER) */
2373 ret = read_frame_internal(ic, &pkt1);
2374 if (ret == AVERROR(EAGAIN))
2379 AVPacket empty_pkt = { 0 };
2381 av_init_packet(&empty_pkt);
2383 ret = -1; /* we could not have all the codec parameters before EOF */
2384 for(i=0;i<ic->nb_streams;i++) {
2385 st = ic->streams[i];
2387 /* flush the decoders */
2388 if (st->info->found_decoder == 1) {
2390 err = try_decode_frame(st, &empty_pkt,
2391 (options && i < orig_nb_streams) ?
2392 &options[i] : NULL);
2393 } while (err > 0 && !has_codec_parameters(st));
2397 av_log(ic, AV_LOG_WARNING,
2398 "decoding for stream %d failed\n", st->index);
2399 } else if (!has_codec_parameters(st)) {
2401 avcodec_string(buf, sizeof(buf), st->codec, 0);
2402 av_log(ic, AV_LOG_WARNING,
2403 "Could not find codec parameters (%s)\n", buf);
2411 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2414 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2415 &ic->packet_buffer_end);
2416 if ((ret = av_dup_packet(pkt)) < 0)
2417 goto find_stream_info_err;
2420 read_size += pkt->size;
2422 st = ic->streams[pkt->stream_index];
2423 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2424 /* check for non-increasing dts */
2425 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2426 st->info->fps_last_dts >= pkt->dts) {
2427 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2428 "packet %d with DTS %"PRId64", packet %d with DTS "
2429 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2430 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2431 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2433 /* check for a discontinuity in dts - if the difference in dts
2434 * is more than 1000 times the average packet duration in the sequence,
2435 * we treat it as a discontinuity */
2436 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2437 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2438 (pkt->dts - st->info->fps_last_dts) / 1000 >
2439 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2440 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2441 "packet %d with DTS %"PRId64", packet %d with DTS "
2442 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2443 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2444 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2447 /* update stored dts values */
2448 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2449 st->info->fps_first_dts = pkt->dts;
2450 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2452 st->info->fps_last_dts = pkt->dts;
2453 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2455 /* check max_analyze_duration */
2456 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2457 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2458 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2462 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2463 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2464 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2465 st->codec->extradata_size= i;
2466 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2467 if (!st->codec->extradata)
2468 return AVERROR(ENOMEM);
2469 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2470 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2474 /* if still no information, we try to open the codec and to
2475 decompress the frame. We try to avoid that in most cases as
2476 it takes longer and uses more memory. For MPEG-4, we need to
2477 decompress for QuickTime.
2479 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2480 least one frame of codec data, this makes sure the codec initializes
2481 the channel configuration and does not only trust the values from the container.
2483 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2485 st->codec_info_nb_frames++;
2489 // close codecs which were opened in try_decode_frame()
2490 for(i=0;i<ic->nb_streams;i++) {
2491 st = ic->streams[i];
2492 avcodec_close(st->codec);
2494 for(i=0;i<ic->nb_streams;i++) {
2495 st = ic->streams[i];
2496 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2497 /* estimate average framerate if not set by demuxer */
2498 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2499 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2500 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2502 double best_error = 0.01;
2504 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2505 delta_packets*(int64_t)st->time_base.den,
2506 delta_dts*(int64_t)st->time_base.num, 60000);
2508 /* round guessed framerate to a "standard" framerate if it's
2509 * within 1% of the original estimate*/
2510 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2511 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2512 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2514 if (error < best_error) {
2516 best_fps = std_fps.num;
2520 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2521 best_fps, 12*1001, INT_MAX);
2524 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2525 if(!st->codec->bits_per_coded_sample)
2526 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2527 // set stream disposition based on audio service type
2528 switch (st->codec->audio_service_type) {
2529 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2530 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2531 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2532 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2533 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2534 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2535 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2536 st->disposition = AV_DISPOSITION_COMMENT; break;
2537 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2538 st->disposition = AV_DISPOSITION_KARAOKE; break;
2543 estimate_timings(ic, old_offset);
2545 compute_chapters_end(ic);
2547 find_stream_info_err:
2548 for (i=0; i < ic->nb_streams; i++) {
2549 if (ic->streams[i]->codec)
2550 ic->streams[i]->codec->thread_count = 0;
2551 av_freep(&ic->streams[i]->info);
2556 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2560 for (i = 0; i < ic->nb_programs; i++)
2561 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2562 if (ic->programs[i]->stream_index[j] == s)
2563 return ic->programs[i];
2567 int av_find_best_stream(AVFormatContext *ic,
2568 enum AVMediaType type,
2569 int wanted_stream_nb,
2571 AVCodec **decoder_ret,
2574 int i, nb_streams = ic->nb_streams;
2575 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2576 unsigned *program = NULL;
2577 AVCodec *decoder = NULL, *best_decoder = NULL;
2579 if (related_stream >= 0 && wanted_stream_nb < 0) {
2580 AVProgram *p = find_program_from_stream(ic, related_stream);
2582 program = p->stream_index;
2583 nb_streams = p->nb_stream_indexes;
2586 for (i = 0; i < nb_streams; i++) {
2587 int real_stream_index = program ? program[i] : i;
2588 AVStream *st = ic->streams[real_stream_index];
2589 AVCodecContext *avctx = st->codec;
2590 if (avctx->codec_type != type)
2592 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2594 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2597 decoder = avcodec_find_decoder(st->codec->codec_id);
2600 ret = AVERROR_DECODER_NOT_FOUND;
2604 if (best_count >= st->codec_info_nb_frames)
2606 best_count = st->codec_info_nb_frames;
2607 ret = real_stream_index;
2608 best_decoder = decoder;
2609 if (program && i == nb_streams - 1 && ret < 0) {
2611 nb_streams = ic->nb_streams;
2612 i = 0; /* no related stream found, try again with everything */
2616 *decoder_ret = best_decoder;
2620 /*******************************************************/
2622 int av_read_play(AVFormatContext *s)
2624 if (s->iformat->read_play)
2625 return s->iformat->read_play(s);
2627 return avio_pause(s->pb, 0);
2628 return AVERROR(ENOSYS);
2631 int av_read_pause(AVFormatContext *s)
2633 if (s->iformat->read_pause)
2634 return s->iformat->read_pause(s);
2636 return avio_pause(s->pb, 1);
2637 return AVERROR(ENOSYS);
2640 void avformat_free_context(AVFormatContext *s)
2646 if (s->iformat && s->iformat->priv_class && s->priv_data)
2647 av_opt_free(s->priv_data);
2649 for(i=0;i<s->nb_streams;i++) {
2650 /* free all data in a stream component */
2653 av_parser_close(st->parser);
2655 if (st->attached_pic.data)
2656 av_free_packet(&st->attached_pic);
2657 av_dict_free(&st->metadata);
2658 av_freep(&st->probe_data.buf);
2659 av_free(st->index_entries);
2660 av_free(st->codec->extradata);
2661 av_free(st->codec->subtitle_header);
2663 av_free(st->priv_data);
2667 for(i=s->nb_programs-1; i>=0; i--) {
2668 av_dict_free(&s->programs[i]->metadata);
2669 av_freep(&s->programs[i]->stream_index);
2670 av_freep(&s->programs[i]);
2672 av_freep(&s->programs);
2673 av_freep(&s->priv_data);
2674 while(s->nb_chapters--) {
2675 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2676 av_free(s->chapters[s->nb_chapters]);
2678 av_freep(&s->chapters);
2679 av_dict_free(&s->metadata);
2680 av_freep(&s->streams);
2684 void avformat_close_input(AVFormatContext **ps)
2686 AVFormatContext *s = *ps;
2687 AVIOContext *pb = s->pb;
2689 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2690 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2693 flush_packet_queue(s);
2696 if (s->iformat->read_close)
2697 s->iformat->read_close(s);
2700 avformat_free_context(s);
2707 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2713 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2715 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2718 s->streams = streams;
2720 st = av_mallocz(sizeof(AVStream));
2723 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2728 st->codec = avcodec_alloc_context3(c);
2730 /* no default bitrate if decoding */
2731 st->codec->bit_rate = 0;
2733 st->index = s->nb_streams;
2734 st->start_time = AV_NOPTS_VALUE;
2735 st->duration = AV_NOPTS_VALUE;
2736 /* we set the current DTS to 0 so that formats without any timestamps
2737 but durations get some timestamps, formats with some unknown
2738 timestamps have their first few packets buffered and the
2739 timestamps corrected before they are returned to the user */
2741 st->first_dts = AV_NOPTS_VALUE;
2742 st->probe_packets = MAX_PROBE_PACKETS;
2744 /* default pts setting is MPEG-like */
2745 avpriv_set_pts_info(st, 33, 1, 90000);
2746 st->last_IP_pts = AV_NOPTS_VALUE;
2747 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2748 st->pts_buffer[i]= AV_NOPTS_VALUE;
2749 st->reference_dts = AV_NOPTS_VALUE;
2751 st->sample_aspect_ratio = (AVRational){0,1};
2753 st->info->fps_first_dts = AV_NOPTS_VALUE;
2754 st->info->fps_last_dts = AV_NOPTS_VALUE;
2756 s->streams[s->nb_streams++] = st;
2760 AVProgram *av_new_program(AVFormatContext *ac, int id)
2762 AVProgram *program=NULL;
2765 av_dlog(ac, "new_program: id=0x%04x\n", id);
2767 for(i=0; i<ac->nb_programs; i++)
2768 if(ac->programs[i]->id == id)
2769 program = ac->programs[i];
2772 program = av_mallocz(sizeof(AVProgram));
2775 dynarray_add(&ac->programs, &ac->nb_programs, program);
2776 program->discard = AVDISCARD_NONE;
2783 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2785 AVChapter *chapter = NULL;
2788 for(i=0; i<s->nb_chapters; i++)
2789 if(s->chapters[i]->id == id)
2790 chapter = s->chapters[i];
2793 chapter= av_mallocz(sizeof(AVChapter));
2796 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2798 av_dict_set(&chapter->metadata, "title", title, 0);
2800 chapter->time_base= time_base;
2801 chapter->start = start;
2807 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2810 AVProgram *program=NULL;
2813 if (idx >= ac->nb_streams) {
2814 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2818 for(i=0; i<ac->nb_programs; i++){
2819 if(ac->programs[i]->id != progid)
2821 program = ac->programs[i];
2822 for(j=0; j<program->nb_stream_indexes; j++)
2823 if(program->stream_index[j] == idx)
2826 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2829 program->stream_index = tmp;
2830 program->stream_index[program->nb_stream_indexes++] = idx;
2835 static void print_fps(double d, const char *postfix){
2836 uint64_t v= lrintf(d*100);
2837 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2838 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2839 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2842 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2844 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2845 AVDictionaryEntry *tag=NULL;
2847 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2848 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2849 if(strcmp("language", tag->key))
2850 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2855 /* "user interface" functions */
2856 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2859 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2860 AVStream *st = ic->streams[i];
2861 int g = av_gcd(st->time_base.num, st->time_base.den);
2862 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2863 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2864 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2865 /* the pid is an important information, so we display it */
2866 /* XXX: add a generic system */
2867 if (flags & AVFMT_SHOW_IDS)
2868 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2870 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2871 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2872 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2873 if (st->sample_aspect_ratio.num && // default
2874 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2875 AVRational display_aspect_ratio;
2876 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2877 st->codec->width*st->sample_aspect_ratio.num,
2878 st->codec->height*st->sample_aspect_ratio.den,
2880 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2881 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2882 display_aspect_ratio.num, display_aspect_ratio.den);
2884 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2885 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2886 print_fps(av_q2d(st->avg_frame_rate), "fps");
2887 if(st->time_base.den && st->time_base.num)
2888 print_fps(1/av_q2d(st->time_base), "tbn");
2889 if(st->codec->time_base.den && st->codec->time_base.num)
2890 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2892 if (st->disposition & AV_DISPOSITION_DEFAULT)
2893 av_log(NULL, AV_LOG_INFO, " (default)");
2894 if (st->disposition & AV_DISPOSITION_DUB)
2895 av_log(NULL, AV_LOG_INFO, " (dub)");
2896 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2897 av_log(NULL, AV_LOG_INFO, " (original)");
2898 if (st->disposition & AV_DISPOSITION_COMMENT)
2899 av_log(NULL, AV_LOG_INFO, " (comment)");
2900 if (st->disposition & AV_DISPOSITION_LYRICS)
2901 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2902 if (st->disposition & AV_DISPOSITION_KARAOKE)
2903 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2904 if (st->disposition & AV_DISPOSITION_FORCED)
2905 av_log(NULL, AV_LOG_INFO, " (forced)");
2906 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2907 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2908 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2909 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2910 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2911 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2912 av_log(NULL, AV_LOG_INFO, "\n");
2913 dump_metadata(NULL, st->metadata, " ");
2916 void av_dump_format(AVFormatContext *ic,
2922 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2923 if (ic->nb_streams && !printed)
2926 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2927 is_output ? "Output" : "Input",
2929 is_output ? ic->oformat->name : ic->iformat->name,
2930 is_output ? "to" : "from", url);
2931 dump_metadata(NULL, ic->metadata, " ");
2933 av_log(NULL, AV_LOG_INFO, " Duration: ");
2934 if (ic->duration != AV_NOPTS_VALUE) {
2935 int hours, mins, secs, us;
2936 secs = ic->duration / AV_TIME_BASE;
2937 us = ic->duration % AV_TIME_BASE;
2942 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2943 (100 * us) / AV_TIME_BASE);
2945 av_log(NULL, AV_LOG_INFO, "N/A");
2947 if (ic->start_time != AV_NOPTS_VALUE) {
2949 av_log(NULL, AV_LOG_INFO, ", start: ");
2950 secs = ic->start_time / AV_TIME_BASE;
2951 us = abs(ic->start_time % AV_TIME_BASE);
2952 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2953 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2955 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2957 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2959 av_log(NULL, AV_LOG_INFO, "N/A");
2961 av_log(NULL, AV_LOG_INFO, "\n");
2963 for (i = 0; i < ic->nb_chapters; i++) {
2964 AVChapter *ch = ic->chapters[i];
2965 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2966 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2967 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2969 dump_metadata(NULL, ch->metadata, " ");
2971 if(ic->nb_programs) {
2972 int j, k, total = 0;
2973 for(j=0; j<ic->nb_programs; j++) {
2974 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2976 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2977 name ? name->value : "");
2978 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2979 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2980 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2981 printed[ic->programs[j]->stream_index[k]] = 1;
2983 total += ic->programs[j]->nb_stream_indexes;
2985 if (total < ic->nb_streams)
2986 av_log(NULL, AV_LOG_INFO, " No Program\n");
2988 for(i=0;i<ic->nb_streams;i++)
2990 dump_stream_format(ic, i, index, is_output);
2995 uint64_t ff_ntp_time(void)
2997 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3000 int av_get_frame_filename(char *buf, int buf_size,
3001 const char *path, int number)
3004 char *q, buf1[20], c;
3005 int nd, len, percentd_found;
3017 while (av_isdigit(*p)) {
3018 nd = nd * 10 + *p++ - '0';
3021 } while (av_isdigit(c));
3030 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3032 if ((q - buf + len) > buf_size - 1)
3034 memcpy(q, buf1, len);
3042 if ((q - buf) < buf_size - 1)
3046 if (!percentd_found)
3055 static void hex_dump_internal(void *avcl, FILE *f, int level,
3056 const uint8_t *buf, int size)
3059 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3061 for(i=0;i<size;i+=16) {
3068 PRINT(" %02x", buf[i+j]);
3073 for(j=0;j<len;j++) {
3075 if (c < ' ' || c > '~')
3084 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3086 hex_dump_internal(NULL, f, 0, buf, size);
3089 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3091 hex_dump_internal(avcl, NULL, level, buf, size);
3094 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3096 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3097 PRINT("stream #%d:\n", pkt->stream_index);
3098 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3099 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3100 /* DTS is _always_ valid after av_read_frame() */
3102 if (pkt->dts == AV_NOPTS_VALUE)
3105 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3106 /* PTS may not be known if B-frames are present. */
3108 if (pkt->pts == AV_NOPTS_VALUE)
3111 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3113 PRINT(" size=%d\n", pkt->size);
3116 av_hex_dump(f, pkt->data, pkt->size);
3119 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3121 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3124 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3127 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3130 void av_url_split(char *proto, int proto_size,
3131 char *authorization, int authorization_size,
3132 char *hostname, int hostname_size,
3134 char *path, int path_size,
3137 const char *p, *ls, *at, *col, *brk;
3139 if (port_ptr) *port_ptr = -1;
3140 if (proto_size > 0) proto[0] = 0;
3141 if (authorization_size > 0) authorization[0] = 0;
3142 if (hostname_size > 0) hostname[0] = 0;
3143 if (path_size > 0) path[0] = 0;
3145 /* parse protocol */
3146 if ((p = strchr(url, ':'))) {
3147 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3152 /* no protocol means plain filename */
3153 av_strlcpy(path, url, path_size);
3157 /* separate path from hostname */
3158 ls = strchr(p, '/');
3160 ls = strchr(p, '?');
3162 av_strlcpy(path, ls, path_size);
3164 ls = &p[strlen(p)]; // XXX
3166 /* the rest is hostname, use that to parse auth/port */
3168 /* authorization (user[:pass]@hostname) */
3169 if ((at = strchr(p, '@')) && at < ls) {
3170 av_strlcpy(authorization, p,
3171 FFMIN(authorization_size, at + 1 - p));
3172 p = at + 1; /* skip '@' */
3175 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3177 av_strlcpy(hostname, p + 1,
3178 FFMIN(hostname_size, brk - p));
3179 if (brk[1] == ':' && port_ptr)
3180 *port_ptr = atoi(brk + 2);
3181 } else if ((col = strchr(p, ':')) && col < ls) {
3182 av_strlcpy(hostname, p,
3183 FFMIN(col + 1 - p, hostname_size));
3184 if (port_ptr) *port_ptr = atoi(col + 1);
3186 av_strlcpy(hostname, p,
3187 FFMIN(ls + 1 - p, hostname_size));
3191 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3194 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3197 'C', 'D', 'E', 'F' };
3198 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3201 'c', 'd', 'e', 'f' };
3202 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3204 for(i = 0; i < s; i++) {
3205 buff[i * 2] = hex_table[src[i] >> 4];
3206 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3212 int ff_hex_to_data(uint8_t *data, const char *p)
3219 p += strspn(p, SPACE_CHARS);
3222 c = av_toupper((unsigned char) *p++);
3223 if (c >= '0' && c <= '9')
3225 else if (c >= 'A' && c <= 'F')
3240 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3241 unsigned int pts_num, unsigned int pts_den)
3244 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3245 if(new_tb.num != pts_num)
3246 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3248 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3250 if(new_tb.num <= 0 || new_tb.den <= 0) {
3251 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3254 s->time_base = new_tb;
3255 s->pts_wrap_bits = pts_wrap_bits;
3258 int ff_url_join(char *str, int size, const char *proto,
3259 const char *authorization, const char *hostname,
3260 int port, const char *fmt, ...)
3263 struct addrinfo hints = { 0 }, *ai;
3268 av_strlcatf(str, size, "%s://", proto);
3269 if (authorization && authorization[0])
3270 av_strlcatf(str, size, "%s@", authorization);
3271 #if CONFIG_NETWORK && defined(AF_INET6)
3272 /* Determine if hostname is a numerical IPv6 address,
3273 * properly escape it within [] in that case. */
3274 hints.ai_flags = AI_NUMERICHOST;
3275 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3276 if (ai->ai_family == AF_INET6) {
3277 av_strlcat(str, "[", size);
3278 av_strlcat(str, hostname, size);
3279 av_strlcat(str, "]", size);
3281 av_strlcat(str, hostname, size);
3286 /* Not an IPv6 address, just output the plain string. */
3287 av_strlcat(str, hostname, size);
3290 av_strlcatf(str, size, ":%d", port);
3293 int len = strlen(str);
3296 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3302 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3303 AVFormatContext *src)
3308 local_pkt.stream_index = dst_stream;
3309 if (pkt->pts != AV_NOPTS_VALUE)
3310 local_pkt.pts = av_rescale_q(pkt->pts,
3311 src->streams[pkt->stream_index]->time_base,
3312 dst->streams[dst_stream]->time_base);
3313 if (pkt->dts != AV_NOPTS_VALUE)
3314 local_pkt.dts = av_rescale_q(pkt->dts,
3315 src->streams[pkt->stream_index]->time_base,
3316 dst->streams[dst_stream]->time_base);
3317 return av_write_frame(dst, &local_pkt);
3320 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3323 const char *ptr = str;
3325 /* Parse key=value pairs. */
3328 char *dest = NULL, *dest_end;
3329 int key_len, dest_len = 0;
3331 /* Skip whitespace and potential commas. */
3332 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3339 if (!(ptr = strchr(key, '=')))
3342 key_len = ptr - key;
3344 callback_get_buf(context, key, key_len, &dest, &dest_len);
3345 dest_end = dest + dest_len - 1;
3349 while (*ptr && *ptr != '\"') {
3353 if (dest && dest < dest_end)
3357 if (dest && dest < dest_end)
3365 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3366 if (dest && dest < dest_end)
3374 int ff_find_stream_index(AVFormatContext *s, int id)
3377 for (i = 0; i < s->nb_streams; i++) {
3378 if (s->streams[i]->id == id)
3384 void ff_make_absolute_url(char *buf, int size, const char *base,
3387 char *sep, *path_query;
3388 /* Absolute path, relative to the current server */
3389 if (base && strstr(base, "://") && rel[0] == '/') {
3391 av_strlcpy(buf, base, size);
3392 sep = strstr(buf, "://");
3394 /* Take scheme from base url */
3395 if (rel[1] == '/') {
3398 /* Take scheme and host from base url */
3400 sep = strchr(sep, '/');
3405 av_strlcat(buf, rel, size);
3408 /* If rel actually is an absolute url, just copy it */
3409 if (!base || strstr(rel, "://") || rel[0] == '/') {
3410 av_strlcpy(buf, rel, size);
3414 av_strlcpy(buf, base, size);
3416 /* Strip off any query string from base */
3417 path_query = strchr(buf, '?');
3418 if (path_query != NULL)
3421 /* Is relative path just a new query part? */
3422 if (rel[0] == '?') {
3423 av_strlcat(buf, rel, size);
3427 /* Remove the file name from the base url */
3428 sep = strrchr(buf, '/');
3433 while (av_strstart(rel, "../", NULL) && sep) {
3434 /* Remove the path delimiter at the end */
3436 sep = strrchr(buf, '/');
3437 /* If the next directory name to pop off is "..", break here */
3438 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3439 /* Readd the slash we just removed */
3440 av_strlcat(buf, "/", size);
3443 /* Cut off the directory name */
3450 av_strlcat(buf, rel, size);
3453 int64_t ff_iso8601_to_unix_time(const char *datestr)
3456 struct tm time1 = {0}, time2 = {0};
3458 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3459 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3461 return av_timegm(&time2);
3463 return av_timegm(&time1);
3465 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3466 "the date string.\n");
3471 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3474 if (ofmt->query_codec)
3475 return ofmt->query_codec(codec_id, std_compliance);
3476 else if (ofmt->codec_tag)
3477 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3478 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3479 codec_id == ofmt->subtitle_codec)
3482 return AVERROR_PATCHWELCOME;
3485 int avformat_network_init(void)
3489 ff_network_inited_globally = 1;
3490 if ((ret = ff_network_init()) < 0)
3497 int avformat_network_deinit(void)
3506 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3507 uint64_t channel_layout, int32_t sample_rate,
3508 int32_t width, int32_t height)
3514 return AVERROR(EINVAL);
3517 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3519 if (channel_layout) {
3521 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3525 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3527 if (width || height) {
3529 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3531 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3533 return AVERROR(ENOMEM);
3534 bytestream_put_le32(&data, flags);
3536 bytestream_put_le32(&data, channels);
3538 bytestream_put_le64(&data, channel_layout);
3540 bytestream_put_le32(&data, sample_rate);
3541 if (width || height) {
3542 bytestream_put_le32(&data, width);
3543 bytestream_put_le32(&data, height);
3548 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3550 return ff_codec_bmp_tags;
3552 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3554 return ff_codec_wav_tags;
3557 static int match_host_pattern(const char *pattern, const char *hostname)
3560 if (!strcmp(pattern, "*"))
3562 // Skip a possible *. at the start of the pattern
3563 if (pattern[0] == '*')
3565 if (pattern[0] == '.')
3567 len_p = strlen(pattern);
3568 len_h = strlen(hostname);
3571 // Simply check if the end of hostname is equal to 'pattern'
3572 if (!strcmp(pattern, &hostname[len_h - len_p])) {
3574 return 1; // Exact match
3575 if (hostname[len_h - len_p - 1] == '.')
3576 return 1; // The matched substring is a domain and not just a substring of a domain
3581 int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
3589 buf = av_strdup(no_proxy);
3594 char *sep, *next = NULL;
3595 start += strspn(start, " ,");
3596 sep = start + strcspn(start, " ,");
3601 if (match_host_pattern(start, hostname)) {