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
25 #include "avio_internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/pixdesc.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
40 #include "audiointerleave.h"
52 * various utility functions for use within Libav
55 unsigned avformat_version(void)
57 return LIBAVFORMAT_VERSION_INT;
60 const char *avformat_configuration(void)
62 return LIBAV_CONFIGURATION;
65 const char *avformat_license(void)
67 #define LICENSE_PREFIX "libavformat license: "
68 return LICENSE_PREFIX LIBAV_LICENSE + sizeof(LICENSE_PREFIX) - 1;
71 /** head of registered input format linked list */
72 static AVInputFormat *first_iformat = NULL;
73 /** head of registered output format linked list */
74 static AVOutputFormat *first_oformat = NULL;
76 AVInputFormat *av_iformat_next(AVInputFormat *f)
79 else return first_iformat;
82 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
85 else return first_oformat;
88 void av_register_input_format(AVInputFormat *format)
92 while (*p != NULL) p = &(*p)->next;
97 void av_register_output_format(AVOutputFormat *format)
101 while (*p != NULL) p = &(*p)->next;
106 int av_match_ext(const char *filename, const char *extensions)
114 ext = strrchr(filename, '.');
120 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
123 if (!av_strcasecmp(ext1, ext))
133 static int match_format(const char *name, const char *names)
141 namelen = strlen(name);
142 while ((p = strchr(names, ','))) {
143 len = FFMAX(p - names, namelen);
144 if (!av_strncasecmp(name, names, len))
148 return !av_strcasecmp(name, names);
151 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
152 const char *mime_type)
154 AVOutputFormat *fmt = NULL, *fmt_found;
155 int score_max, score;
157 /* specific test for image sequences */
158 #if CONFIG_IMAGE2_MUXER
159 if (!short_name && filename &&
160 av_filename_number_test(filename) &&
161 ff_guess_image2_codec(filename) != AV_CODEC_ID_NONE) {
162 return av_guess_format("image2", NULL, NULL);
165 /* Find the proper file type. */
168 while ((fmt = av_oformat_next(fmt))) {
170 if (fmt->name && short_name && !av_strcasecmp(fmt->name, short_name))
172 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
174 if (filename && fmt->extensions &&
175 av_match_ext(filename, fmt->extensions)) {
178 if (score > score_max) {
186 enum AVCodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
187 const char *filename, const char *mime_type, enum AVMediaType type){
188 if(type == AVMEDIA_TYPE_VIDEO){
189 enum AVCodecID codec_id= AV_CODEC_ID_NONE;
191 #if CONFIG_IMAGE2_MUXER
192 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
193 codec_id= ff_guess_image2_codec(filename);
196 if(codec_id == AV_CODEC_ID_NONE)
197 codec_id= fmt->video_codec;
199 }else if(type == AVMEDIA_TYPE_AUDIO)
200 return fmt->audio_codec;
201 else if (type == AVMEDIA_TYPE_SUBTITLE)
202 return fmt->subtitle_codec;
204 return AV_CODEC_ID_NONE;
207 AVInputFormat *av_find_input_format(const char *short_name)
209 AVInputFormat *fmt = NULL;
210 while ((fmt = av_iformat_next(fmt))) {
211 if (match_format(short_name, fmt->name))
218 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
220 int ret= av_new_packet(pkt, size);
225 pkt->pos= avio_tell(s);
227 ret= avio_read(s, pkt->data, size);
231 av_shrink_packet(pkt, ret);
236 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
241 return av_get_packet(s, pkt, size);
242 old_size = pkt->size;
243 ret = av_grow_packet(pkt, size);
246 ret = avio_read(s, pkt->data + old_size, size);
247 av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
252 int av_filename_number_test(const char *filename)
255 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
258 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
260 AVProbeData lpd = *pd;
261 AVInputFormat *fmt1 = NULL, *fmt;
264 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
265 int id3len = ff_id3v2_tag_len(lpd.buf);
266 if (lpd.buf_size > id3len + 16) {
268 lpd.buf_size -= id3len;
274 while ((fmt1 = av_iformat_next(fmt1))) {
275 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
278 if (fmt1->read_probe) {
279 score = fmt1->read_probe(&lpd);
280 } else if (fmt1->extensions) {
281 if (av_match_ext(lpd.filename, fmt1->extensions)) {
285 if (score > *score_max) {
288 }else if (score == *score_max)
292 /* a hack for files with huge id3v2 tags -- try to guess by file extension. */
293 if (!fmt && is_opened && *score_max < AVPROBE_SCORE_MAX/4) {
294 while ((fmt = av_iformat_next(fmt)))
295 if (fmt->extensions && av_match_ext(lpd.filename, fmt->extensions)) {
296 *score_max = AVPROBE_SCORE_MAX/4;
301 if (!fmt && id3 && *score_max < AVPROBE_SCORE_MAX/4-1) {
302 while ((fmt = av_iformat_next(fmt)))
303 if (fmt->extensions && av_match_ext("mp3", fmt->extensions)) {
304 *score_max = AVPROBE_SCORE_MAX/4-1;
312 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
314 return av_probe_input_format2(pd, is_opened, &score);
317 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd, int score)
319 static const struct {
320 const char *name; enum AVCodecID id; enum AVMediaType type;
322 { "aac" , AV_CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
323 { "ac3" , AV_CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
324 { "dts" , AV_CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
325 { "eac3" , AV_CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
326 { "h264" , AV_CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
327 { "m4v" , AV_CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
328 { "mp3" , AV_CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
329 { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
332 AVInputFormat *fmt = av_probe_input_format2(pd, 1, &score);
336 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
337 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
338 for (i = 0; fmt_id_type[i].name; i++) {
339 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
340 st->codec->codec_id = fmt_id_type[i].id;
341 st->codec->codec_type = fmt_id_type[i].type;
349 /************************************************************/
350 /* input media file */
352 /** size of probe buffer, for guessing file type from file contents */
353 #define PROBE_BUF_MIN 2048
354 #define PROBE_BUF_MAX (1<<20)
356 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
357 const char *filename, void *logctx,
358 unsigned int offset, unsigned int max_probe_size)
360 AVProbeData pd = { filename ? filename : "", NULL, -offset };
361 unsigned char *buf = NULL;
362 int ret = 0, probe_size;
364 if (!max_probe_size) {
365 max_probe_size = PROBE_BUF_MAX;
366 } else if (max_probe_size > PROBE_BUF_MAX) {
367 max_probe_size = PROBE_BUF_MAX;
368 } else if (max_probe_size < PROBE_BUF_MIN) {
369 return AVERROR(EINVAL);
372 if (offset >= max_probe_size) {
373 return AVERROR(EINVAL);
376 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
377 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
378 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
379 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
381 if (probe_size < offset) {
385 /* read probe data */
386 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
387 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
388 /* fail if error was not end of file, otherwise, lower score */
389 if (ret != AVERROR_EOF) {
394 ret = 0; /* error was end of file, nothing read */
397 pd.buf = &buf[offset];
399 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
401 /* guess file format */
402 *fmt = av_probe_input_format2(&pd, 1, &score);
404 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
405 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
407 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
413 return AVERROR_INVALIDDATA;
416 /* rewind. reuse probe buffer to avoid seeking */
417 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
423 /* open input file and probe the format if necessary */
424 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
427 AVProbeData pd = {filename, NULL, 0};
430 s->flags |= AVFMT_FLAG_CUSTOM_IO;
432 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
433 else if (s->iformat->flags & AVFMT_NOFILE)
434 return AVERROR(EINVAL);
438 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
439 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
442 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
443 &s->interrupt_callback, options)) < 0)
447 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, s->probesize);
450 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
451 AVPacketList **plast_pktl){
452 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
457 (*plast_pktl)->next = pktl;
459 *packet_buffer = pktl;
461 /* add the packet in the buffered packet list */
467 static void queue_attached_pictures(AVFormatContext *s)
470 for (i = 0; i < s->nb_streams; i++)
471 if (s->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC &&
472 s->streams[i]->discard < AVDISCARD_ALL) {
473 AVPacket copy = s->streams[i]->attached_pic;
474 copy.destruct = NULL;
475 add_to_pktbuf(&s->raw_packet_buffer, ©, &s->raw_packet_buffer_end);
479 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
481 AVFormatContext *s = *ps;
483 AVDictionary *tmp = NULL;
484 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
486 if (!s && !(s = avformat_alloc_context()))
487 return AVERROR(ENOMEM);
492 av_dict_copy(&tmp, *options, 0);
494 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
497 if ((ret = init_input(s, filename, &tmp)) < 0)
500 /* check filename in case an image number is expected */
501 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
502 if (!av_filename_number_test(filename)) {
503 ret = AVERROR(EINVAL);
508 s->duration = s->start_time = AV_NOPTS_VALUE;
509 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
511 /* allocate private data */
512 if (s->iformat->priv_data_size > 0) {
513 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
514 ret = AVERROR(ENOMEM);
517 if (s->iformat->priv_class) {
518 *(const AVClass**)s->priv_data = s->iformat->priv_class;
519 av_opt_set_defaults(s->priv_data);
520 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
525 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
527 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
529 if (s->iformat->read_header)
530 if ((ret = s->iformat->read_header(s)) < 0)
533 if (id3v2_extra_meta &&
534 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
536 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
538 queue_attached_pictures(s);
540 if (s->pb && !s->data_offset)
541 s->data_offset = avio_tell(s->pb);
543 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
546 av_dict_free(options);
553 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
555 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
557 avformat_free_context(s);
562 /*******************************************************/
564 static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
566 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
567 AVProbeData *pd = &st->probe_data;
568 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
572 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
573 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
574 pd->buf_size += pkt->size;
575 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
577 st->probe_packets = 0;
579 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
585 if (!st->probe_packets ||
586 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
587 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
588 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
591 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
597 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
603 AVPacketList *pktl = s->raw_packet_buffer;
607 st = s->streams[pkt->stream_index];
608 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
609 s->raw_packet_buffer_remaining_size < pkt->size) {
611 if (st->probe_packets) {
612 probe_codec(s, st, NULL);
614 pd = &st->probe_data;
617 s->raw_packet_buffer = pktl->next;
618 s->raw_packet_buffer_remaining_size += pkt->size;
627 ret= s->iformat->read_packet(s, pkt);
629 if (!pktl || ret == AVERROR(EAGAIN))
631 for (i = 0; i < s->nb_streams; i++) {
633 if (st->probe_packets) {
634 probe_codec(s, st, NULL);
640 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
641 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
642 av_log(s, AV_LOG_WARNING,
643 "Dropped corrupted packet (stream = %d)\n",
649 st= s->streams[pkt->stream_index];
651 switch(st->codec->codec_type){
652 case AVMEDIA_TYPE_VIDEO:
653 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
655 case AVMEDIA_TYPE_AUDIO:
656 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
658 case AVMEDIA_TYPE_SUBTITLE:
659 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
663 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
667 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
668 s->raw_packet_buffer_remaining_size -= pkt->size;
670 probe_codec(s, st, pkt);
674 #if FF_API_READ_PACKET
675 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
677 return ff_read_packet(s, pkt);
682 /**********************************************************/
685 * Get the number of samples of an audio frame. Return -1 on error.
687 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
691 /* give frame_size priority if demuxing */
692 if (!mux && enc->frame_size > 1)
693 return enc->frame_size;
695 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
698 /* fallback to using frame_size if muxing */
699 if (enc->frame_size > 1)
700 return enc->frame_size;
707 * Return the frame duration in seconds. Return 0 if not available.
709 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
710 AVCodecParserContext *pc, AVPacket *pkt)
716 switch(st->codec->codec_type) {
717 case AVMEDIA_TYPE_VIDEO:
718 if (st->avg_frame_rate.num) {
719 *pnum = st->avg_frame_rate.den;
720 *pden = st->avg_frame_rate.num;
721 } else if(st->time_base.num*1000LL > st->time_base.den) {
722 *pnum = st->time_base.num;
723 *pden = st->time_base.den;
724 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
725 *pnum = st->codec->time_base.num;
726 *pden = st->codec->time_base.den;
727 if (pc && pc->repeat_pict) {
728 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
729 *pden /= 1 + pc->repeat_pict;
731 *pnum *= 1 + pc->repeat_pict;
733 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
734 //Thus if we have no parser in such case leave duration undefined.
735 if(st->codec->ticks_per_frame>1 && !pc){
740 case AVMEDIA_TYPE_AUDIO:
741 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
742 if (frame_size <= 0 || st->codec->sample_rate <= 0)
745 *pden = st->codec->sample_rate;
752 static int is_intra_only(enum AVCodecID id)
754 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
757 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
762 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
763 int64_t dts, int64_t pts)
765 AVStream *st= s->streams[stream_index];
766 AVPacketList *pktl= s->packet_buffer;
768 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
771 st->first_dts= dts - st->cur_dts;
774 for(; pktl; pktl= pktl->next){
775 if(pktl->pkt.stream_index != stream_index)
777 //FIXME think more about this check
778 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
779 pktl->pkt.pts += st->first_dts;
781 if(pktl->pkt.dts != AV_NOPTS_VALUE)
782 pktl->pkt.dts += st->first_dts;
784 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
785 st->start_time= pktl->pkt.pts;
787 if (st->start_time == AV_NOPTS_VALUE)
788 st->start_time = pts;
791 static void update_initial_durations(AVFormatContext *s, AVStream *st,
792 int stream_index, int duration)
794 AVPacketList *pktl= s->packet_buffer;
797 if(st->first_dts != AV_NOPTS_VALUE){
798 cur_dts= st->first_dts;
799 for(; pktl; pktl= pktl->next){
800 if(pktl->pkt.stream_index == stream_index){
801 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
806 pktl= s->packet_buffer;
807 st->first_dts = cur_dts;
808 }else if(st->cur_dts)
811 for(; pktl; pktl= pktl->next){
812 if(pktl->pkt.stream_index != stream_index)
814 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
815 && !pktl->pkt.duration){
816 pktl->pkt.dts= cur_dts;
817 if(!st->codec->has_b_frames)
818 pktl->pkt.pts= cur_dts;
820 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
821 pktl->pkt.duration = duration;
825 if(st->first_dts == AV_NOPTS_VALUE)
826 st->cur_dts= cur_dts;
829 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
830 AVCodecParserContext *pc, AVPacket *pkt)
832 int num, den, presentation_delayed, delay, i;
835 if (s->flags & AVFMT_FLAG_NOFILLIN)
838 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
839 pkt->dts= AV_NOPTS_VALUE;
841 /* do we have a video B-frame ? */
842 delay= st->codec->has_b_frames;
843 presentation_delayed = 0;
845 /* XXX: need has_b_frame, but cannot get it if the codec is
848 pc && pc->pict_type != AV_PICTURE_TYPE_B)
849 presentation_delayed = 1;
851 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
852 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
853 pkt->dts -= 1LL<<st->pts_wrap_bits;
856 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
857 // we take the conservative approach and discard both
858 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
859 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
860 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
861 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
864 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
865 ff_compute_frame_duration(&num, &den, st, pc, pkt);
867 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
869 if(pkt->duration != 0 && s->packet_buffer)
870 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
874 /* correct timestamps with byte offset if demuxers only have timestamps
875 on packet boundaries */
876 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
877 /* this will estimate bitrate based on this frame's duration and size */
878 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
879 if(pkt->pts != AV_NOPTS_VALUE)
881 if(pkt->dts != AV_NOPTS_VALUE)
885 if (pc && pc->dts_sync_point >= 0) {
886 // we have synchronization info from the parser
887 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
889 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
890 if (pkt->dts != AV_NOPTS_VALUE) {
891 // got DTS from the stream, update reference timestamp
892 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
893 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
894 } else if (st->reference_dts != AV_NOPTS_VALUE) {
895 // compute DTS based on reference timestamp
896 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
897 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
899 if (pc->dts_sync_point > 0)
900 st->reference_dts = pkt->dts; // new reference
904 /* This may be redundant, but it should not hurt. */
905 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
906 presentation_delayed = 1;
909 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
910 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
911 pkt->stream_index, pc);
912 /* interpolate PTS and DTS if they are not present */
913 //We skip H264 currently because delay and has_b_frames are not reliably set
914 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
915 if (presentation_delayed) {
916 /* DTS = decompression timestamp */
917 /* PTS = presentation timestamp */
918 if (pkt->dts == AV_NOPTS_VALUE)
919 pkt->dts = st->last_IP_pts;
920 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
921 if (pkt->dts == AV_NOPTS_VALUE)
922 pkt->dts = st->cur_dts;
924 /* this is tricky: the dts must be incremented by the duration
925 of the frame we are displaying, i.e. the last I- or P-frame */
926 if (st->last_IP_duration == 0)
927 st->last_IP_duration = pkt->duration;
928 if(pkt->dts != AV_NOPTS_VALUE)
929 st->cur_dts = pkt->dts + st->last_IP_duration;
930 st->last_IP_duration = pkt->duration;
931 st->last_IP_pts= pkt->pts;
932 /* cannot compute PTS if not present (we can compute it only
933 by knowing the future */
934 } else if (pkt->pts != AV_NOPTS_VALUE ||
935 pkt->dts != AV_NOPTS_VALUE ||
937 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
938 int duration = pkt->duration;
939 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
940 ff_compute_frame_duration(&num, &den, st, pc, pkt);
942 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
943 den * (int64_t)st->time_base.num,
945 if (duration != 0 && s->packet_buffer) {
946 update_initial_durations(s, st, pkt->stream_index,
952 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
954 /* presentation is not delayed : PTS and DTS are the same */
955 if (pkt->pts == AV_NOPTS_VALUE)
957 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
959 if (pkt->pts == AV_NOPTS_VALUE)
960 pkt->pts = st->cur_dts;
962 if (pkt->pts != AV_NOPTS_VALUE)
963 st->cur_dts = pkt->pts + duration;
968 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
969 st->pts_buffer[0]= pkt->pts;
970 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
971 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
972 if(pkt->dts == AV_NOPTS_VALUE)
973 pkt->dts= st->pts_buffer[0];
974 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
975 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
977 if(pkt->dts > st->cur_dts)
978 st->cur_dts = pkt->dts;
982 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
983 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
986 if (is_intra_only(st->codec->codec_id))
987 pkt->flags |= AV_PKT_FLAG_KEY;
989 pkt->convergence_duration = pc->convergence_duration;
992 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
995 AVPacketList *pktl = *pkt_buf;
996 *pkt_buf = pktl->next;
997 av_free_packet(&pktl->pkt);
1000 *pkt_buf_end = NULL;
1004 * Parse a packet, add all split parts to parse_queue
1006 * @param pkt packet to parse, NULL when flushing the parser at end of stream
1008 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1010 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1011 AVStream *st = s->streams[stream_index];
1012 uint8_t *data = pkt ? pkt->data : NULL;
1013 int size = pkt ? pkt->size : 0;
1014 int ret = 0, got_output = 0;
1017 av_init_packet(&flush_pkt);
1022 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1025 av_init_packet(&out_pkt);
1026 len = av_parser_parse2(st->parser, st->codec,
1027 &out_pkt.data, &out_pkt.size, data, size,
1028 pkt->pts, pkt->dts, pkt->pos);
1030 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1031 /* increment read pointer */
1035 got_output = !!out_pkt.size;
1040 /* set the duration */
1041 out_pkt.duration = 0;
1042 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1043 if (st->codec->sample_rate > 0) {
1044 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1045 (AVRational){ 1, st->codec->sample_rate },
1049 } else if (st->codec->time_base.num != 0 &&
1050 st->codec->time_base.den != 0) {
1051 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1052 st->codec->time_base,
1057 out_pkt.stream_index = st->index;
1058 out_pkt.pts = st->parser->pts;
1059 out_pkt.dts = st->parser->dts;
1060 out_pkt.pos = st->parser->pos;
1062 if (st->parser->key_frame == 1 ||
1063 (st->parser->key_frame == -1 &&
1064 st->parser->pict_type == AV_PICTURE_TYPE_I))
1065 out_pkt.flags |= AV_PKT_FLAG_KEY;
1067 compute_pkt_fields(s, st, st->parser, &out_pkt);
1069 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1070 out_pkt.flags & AV_PKT_FLAG_KEY) {
1071 ff_reduce_index(s, st->index);
1072 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
1073 0, 0, AVINDEX_KEYFRAME);
1076 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1077 out_pkt.destruct = pkt->destruct;
1078 pkt->destruct = NULL;
1080 if ((ret = av_dup_packet(&out_pkt)) < 0)
1083 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1084 av_free_packet(&out_pkt);
1085 ret = AVERROR(ENOMEM);
1091 /* end of the stream => close and free the parser */
1092 if (pkt == &flush_pkt) {
1093 av_parser_close(st->parser);
1098 av_free_packet(pkt);
1102 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1103 AVPacketList **pkt_buffer_end,
1107 av_assert0(*pkt_buffer);
1110 *pkt_buffer = pktl->next;
1112 *pkt_buffer_end = NULL;
1117 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1119 int ret = 0, i, got_packet = 0;
1121 av_init_packet(pkt);
1123 while (!got_packet && !s->parse_queue) {
1127 /* read next packet */
1128 ret = ff_read_packet(s, &cur_pkt);
1130 if (ret == AVERROR(EAGAIN))
1132 /* flush the parsers */
1133 for(i = 0; i < s->nb_streams; i++) {
1135 if (st->parser && st->need_parsing)
1136 parse_packet(s, NULL, st->index);
1138 /* all remaining packets are now in parse_queue =>
1139 * really terminate parsing */
1143 st = s->streams[cur_pkt.stream_index];
1145 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1146 cur_pkt.dts != AV_NOPTS_VALUE &&
1147 cur_pkt.pts < cur_pkt.dts) {
1148 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1149 cur_pkt.stream_index,
1154 if (s->debug & FF_FDEBUG_TS)
1155 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1156 cur_pkt.stream_index,
1163 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1164 st->parser = av_parser_init(st->codec->codec_id);
1166 /* no parser available: just output the raw packets */
1167 st->need_parsing = AVSTREAM_PARSE_NONE;
1168 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1169 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1170 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1171 st->parser->flags |= PARSER_FLAG_ONCE;
1175 if (!st->need_parsing || !st->parser) {
1176 /* no parsing needed: we just output the packet as is */
1178 compute_pkt_fields(s, st, NULL, pkt);
1179 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1180 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1181 ff_reduce_index(s, st->index);
1182 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1185 } else if (st->discard < AVDISCARD_ALL) {
1186 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1190 av_free_packet(&cur_pkt);
1194 if (!got_packet && s->parse_queue)
1195 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1197 if(s->debug & FF_FDEBUG_TS)
1198 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1209 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1211 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1215 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1216 &s->packet_buffer_end,
1218 read_frame_internal(s, pkt);
1222 AVPacketList *pktl = s->packet_buffer;
1225 AVPacket *next_pkt = &pktl->pkt;
1227 if (next_pkt->dts != AV_NOPTS_VALUE) {
1228 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1229 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1230 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1231 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1232 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1233 next_pkt->pts = pktl->pkt.dts;
1237 pktl = s->packet_buffer;
1240 /* read packet from packet buffer, if there is data */
1241 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1242 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1243 return read_from_packet_buffer(&s->packet_buffer,
1244 &s->packet_buffer_end, pkt);
1247 ret = read_frame_internal(s, pkt);
1249 if (pktl && ret != AVERROR(EAGAIN)) {
1256 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1257 &s->packet_buffer_end)) < 0)
1258 return AVERROR(ENOMEM);
1262 /* XXX: suppress the packet queue */
1263 static void flush_packet_queue(AVFormatContext *s)
1265 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1266 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1267 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1269 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1272 /*******************************************************/
1275 int av_find_default_stream_index(AVFormatContext *s)
1277 int first_audio_index = -1;
1281 if (s->nb_streams <= 0)
1283 for(i = 0; i < s->nb_streams; i++) {
1285 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1286 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1289 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1290 first_audio_index = i;
1292 return first_audio_index >= 0 ? first_audio_index : 0;
1296 * Flush the frame reader.
1298 void ff_read_frame_flush(AVFormatContext *s)
1303 flush_packet_queue(s);
1305 /* for each stream, reset read state */
1306 for(i = 0; i < s->nb_streams; i++) {
1310 av_parser_close(st->parser);
1313 st->last_IP_pts = AV_NOPTS_VALUE;
1314 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1315 st->reference_dts = AV_NOPTS_VALUE;
1317 st->probe_packets = MAX_PROBE_PACKETS;
1319 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1320 st->pts_buffer[j]= AV_NOPTS_VALUE;
1324 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1328 for(i = 0; i < s->nb_streams; i++) {
1329 AVStream *st = s->streams[i];
1331 st->cur_dts = av_rescale(timestamp,
1332 st->time_base.den * (int64_t)ref_st->time_base.num,
1333 st->time_base.num * (int64_t)ref_st->time_base.den);
1337 void ff_reduce_index(AVFormatContext *s, int stream_index)
1339 AVStream *st= s->streams[stream_index];
1340 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1342 if((unsigned)st->nb_index_entries >= max_entries){
1344 for(i=0; 2*i<st->nb_index_entries; i++)
1345 st->index_entries[i]= st->index_entries[2*i];
1346 st->nb_index_entries= i;
1350 int ff_add_index_entry(AVIndexEntry **index_entries,
1351 int *nb_index_entries,
1352 unsigned int *index_entries_allocated_size,
1353 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1355 AVIndexEntry *entries, *ie;
1358 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1361 entries = av_fast_realloc(*index_entries,
1362 index_entries_allocated_size,
1363 (*nb_index_entries + 1) *
1364 sizeof(AVIndexEntry));
1368 *index_entries= entries;
1370 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1373 index= (*nb_index_entries)++;
1374 ie= &entries[index];
1375 assert(index==0 || ie[-1].timestamp < timestamp);
1377 ie= &entries[index];
1378 if(ie->timestamp != timestamp){
1379 if(ie->timestamp <= timestamp)
1381 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1382 (*nb_index_entries)++;
1383 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1384 distance= ie->min_distance;
1388 ie->timestamp = timestamp;
1389 ie->min_distance= distance;
1396 int av_add_index_entry(AVStream *st,
1397 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1399 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1400 &st->index_entries_allocated_size, pos,
1401 timestamp, size, distance, flags);
1404 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1405 int64_t wanted_timestamp, int flags)
1413 //optimize appending index entries at the end
1414 if(b && entries[b-1].timestamp < wanted_timestamp)
1419 timestamp = entries[m].timestamp;
1420 if(timestamp >= wanted_timestamp)
1422 if(timestamp <= wanted_timestamp)
1425 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1427 if(!(flags & AVSEEK_FLAG_ANY)){
1428 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1429 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1438 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1441 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1442 wanted_timestamp, flags);
1445 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1447 AVInputFormat *avif= s->iformat;
1448 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1449 int64_t ts_min, ts_max, ts;
1454 if (stream_index < 0)
1457 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1460 ts_min= AV_NOPTS_VALUE;
1461 pos_limit= -1; //gcc falsely says it may be uninitialized
1463 st= s->streams[stream_index];
1464 if(st->index_entries){
1467 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()
1468 index= FFMAX(index, 0);
1469 e= &st->index_entries[index];
1471 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1473 ts_min= e->timestamp;
1474 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1480 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1481 assert(index < st->nb_index_entries);
1483 e= &st->index_entries[index];
1484 assert(e->timestamp >= target_ts);
1486 ts_max= e->timestamp;
1487 pos_limit= pos_max - e->min_distance;
1488 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1489 pos_max,pos_limit, ts_max);
1493 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1498 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1501 ff_update_cur_dts(s, st, ts);
1506 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1507 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1508 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1509 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1512 int64_t start_pos, filesize;
1515 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1517 if(ts_min == AV_NOPTS_VALUE){
1518 pos_min = s->data_offset;
1519 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1520 if (ts_min == AV_NOPTS_VALUE)
1524 if(ts_max == AV_NOPTS_VALUE){
1526 filesize = avio_size(s->pb);
1527 pos_max = filesize - 1;
1530 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1532 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1533 if (ts_max == AV_NOPTS_VALUE)
1537 int64_t tmp_pos= pos_max + 1;
1538 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1539 if(tmp_ts == AV_NOPTS_VALUE)
1543 if(tmp_pos >= filesize)
1549 if(ts_min > ts_max){
1551 }else if(ts_min == ts_max){
1556 while (pos_min < pos_limit) {
1557 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1558 pos_min, pos_max, ts_min, ts_max);
1559 assert(pos_limit <= pos_max);
1562 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1563 // interpolate position (better than dichotomy)
1564 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1565 + pos_min - approximate_keyframe_distance;
1566 }else if(no_change==1){
1567 // bisection, if interpolation failed to change min or max pos last time
1568 pos = (pos_min + pos_limit)>>1;
1570 /* linear search if bisection failed, can only happen if there
1571 are very few or no keyframes between min/max */
1576 else if(pos > pos_limit)
1580 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1585 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1586 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1587 pos_limit, start_pos, no_change);
1588 if(ts == AV_NOPTS_VALUE){
1589 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1592 assert(ts != AV_NOPTS_VALUE);
1593 if (target_ts <= ts) {
1594 pos_limit = start_pos - 1;
1598 if (target_ts >= ts) {
1604 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1605 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1607 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1609 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1610 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1611 pos, ts_min, target_ts, ts_max);
1616 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1617 int64_t pos_min, pos_max;
1619 pos_min = s->data_offset;
1620 pos_max = avio_size(s->pb) - 1;
1622 if (pos < pos_min) pos= pos_min;
1623 else if(pos > pos_max) pos= pos_max;
1625 avio_seek(s->pb, pos, SEEK_SET);
1630 static int seek_frame_generic(AVFormatContext *s,
1631 int stream_index, int64_t timestamp, int flags)
1638 st = s->streams[stream_index];
1640 index = av_index_search_timestamp(st, timestamp, flags);
1642 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1645 if(index < 0 || index==st->nb_index_entries-1){
1648 if(st->nb_index_entries){
1649 assert(st->index_entries);
1650 ie= &st->index_entries[st->nb_index_entries-1];
1651 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1653 ff_update_cur_dts(s, st, ie->timestamp);
1655 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1661 read_status = av_read_frame(s, &pkt);
1662 } while (read_status == AVERROR(EAGAIN));
1663 if (read_status < 0)
1665 av_free_packet(&pkt);
1666 if(stream_index == pkt.stream_index){
1667 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1671 index = av_index_search_timestamp(st, timestamp, flags);
1676 ff_read_frame_flush(s);
1677 if (s->iformat->read_seek){
1678 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1681 ie = &st->index_entries[index];
1682 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1684 ff_update_cur_dts(s, st, ie->timestamp);
1689 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1690 int64_t timestamp, int flags)
1695 if (flags & AVSEEK_FLAG_BYTE) {
1696 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1698 ff_read_frame_flush(s);
1699 return seek_frame_byte(s, stream_index, timestamp, flags);
1702 if(stream_index < 0){
1703 stream_index= av_find_default_stream_index(s);
1704 if(stream_index < 0)
1707 st= s->streams[stream_index];
1708 /* timestamp for default must be expressed in AV_TIME_BASE units */
1709 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1712 /* first, we try the format specific seek */
1713 if (s->iformat->read_seek) {
1714 ff_read_frame_flush(s);
1715 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1722 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1723 ff_read_frame_flush(s);
1724 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1725 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1726 ff_read_frame_flush(s);
1727 return seek_frame_generic(s, stream_index, timestamp, flags);
1733 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1735 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1738 queue_attached_pictures(s);
1743 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1745 if(min_ts > ts || max_ts < ts)
1748 if (s->iformat->read_seek2) {
1750 ff_read_frame_flush(s);
1751 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1754 queue_attached_pictures(s);
1758 if(s->iformat->read_timestamp){
1759 //try to seek via read_timestamp()
1762 //Fallback to old API if new is not implemented but old is
1763 //Note the old has somewat different sematics
1764 if(s->iformat->read_seek || 1)
1765 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1767 // try some generic seek like seek_frame_generic() but with new ts semantics
1770 /*******************************************************/
1773 * Return TRUE if the stream has accurate duration in any stream.
1775 * @return TRUE if the stream has accurate duration for at least one component.
1777 static int has_duration(AVFormatContext *ic)
1782 for(i = 0;i < ic->nb_streams; i++) {
1783 st = ic->streams[i];
1784 if (st->duration != AV_NOPTS_VALUE)
1787 if (ic->duration != AV_NOPTS_VALUE)
1793 * Estimate the stream timings from the one of each components.
1795 * Also computes the global bitrate if possible.
1797 static void update_stream_timings(AVFormatContext *ic)
1799 int64_t start_time, start_time1, end_time, end_time1;
1800 int64_t duration, duration1, filesize;
1804 start_time = INT64_MAX;
1805 end_time = INT64_MIN;
1806 duration = INT64_MIN;
1807 for(i = 0;i < ic->nb_streams; i++) {
1808 st = ic->streams[i];
1809 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1810 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1811 start_time = FFMIN(start_time, start_time1);
1812 if (st->duration != AV_NOPTS_VALUE) {
1813 end_time1 = start_time1
1814 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1815 end_time = FFMAX(end_time, end_time1);
1818 if (st->duration != AV_NOPTS_VALUE) {
1819 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1820 duration = FFMAX(duration, duration1);
1823 if (start_time != INT64_MAX) {
1824 ic->start_time = start_time;
1825 if (end_time != INT64_MIN)
1826 duration = FFMAX(duration, end_time - start_time);
1828 if (duration != INT64_MIN) {
1829 ic->duration = duration;
1830 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1831 /* compute the bitrate */
1832 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1833 (double)ic->duration;
1838 static void fill_all_stream_timings(AVFormatContext *ic)
1843 update_stream_timings(ic);
1844 for(i = 0;i < ic->nb_streams; i++) {
1845 st = ic->streams[i];
1846 if (st->start_time == AV_NOPTS_VALUE) {
1847 if(ic->start_time != AV_NOPTS_VALUE)
1848 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1849 if(ic->duration != AV_NOPTS_VALUE)
1850 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1855 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1857 int64_t filesize, duration;
1861 /* if bit_rate is already set, we believe it */
1862 if (ic->bit_rate <= 0) {
1864 for(i=0;i<ic->nb_streams;i++) {
1865 st = ic->streams[i];
1866 if (st->codec->bit_rate > 0)
1867 bit_rate += st->codec->bit_rate;
1869 ic->bit_rate = bit_rate;
1872 /* if duration is already set, we believe it */
1873 if (ic->duration == AV_NOPTS_VALUE &&
1874 ic->bit_rate != 0) {
1875 filesize = ic->pb ? avio_size(ic->pb) : 0;
1877 for(i = 0; i < ic->nb_streams; i++) {
1878 st = ic->streams[i];
1879 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1880 if (st->duration == AV_NOPTS_VALUE)
1881 st->duration = duration;
1887 #define DURATION_MAX_READ_SIZE 250000
1888 #define DURATION_MAX_RETRY 3
1890 /* only usable for MPEG-PS streams */
1891 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1893 AVPacket pkt1, *pkt = &pkt1;
1895 int read_size, i, ret;
1897 int64_t filesize, offset, duration;
1900 /* flush packet queue */
1901 flush_packet_queue(ic);
1903 for (i=0; i<ic->nb_streams; i++) {
1904 st = ic->streams[i];
1905 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1906 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1909 av_parser_close(st->parser);
1914 /* estimate the end time (duration) */
1915 /* XXX: may need to support wrapping */
1916 filesize = ic->pb ? avio_size(ic->pb) : 0;
1917 end_time = AV_NOPTS_VALUE;
1919 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1923 avio_seek(ic->pb, offset, SEEK_SET);
1926 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1930 ret = ff_read_packet(ic, pkt);
1931 } while(ret == AVERROR(EAGAIN));
1934 read_size += pkt->size;
1935 st = ic->streams[pkt->stream_index];
1936 if (pkt->pts != AV_NOPTS_VALUE &&
1937 (st->start_time != AV_NOPTS_VALUE ||
1938 st->first_dts != AV_NOPTS_VALUE)) {
1939 duration = end_time = pkt->pts;
1940 if (st->start_time != AV_NOPTS_VALUE)
1941 duration -= st->start_time;
1943 duration -= st->first_dts;
1945 duration += 1LL<<st->pts_wrap_bits;
1947 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1948 st->duration = duration;
1951 av_free_packet(pkt);
1953 }while( end_time==AV_NOPTS_VALUE
1954 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1955 && ++retry <= DURATION_MAX_RETRY);
1957 fill_all_stream_timings(ic);
1959 avio_seek(ic->pb, old_offset, SEEK_SET);
1960 for (i=0; i<ic->nb_streams; i++) {
1962 st->cur_dts= st->first_dts;
1963 st->last_IP_pts = AV_NOPTS_VALUE;
1964 st->reference_dts = AV_NOPTS_VALUE;
1968 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1972 /* get the file size, if possible */
1973 if (ic->iformat->flags & AVFMT_NOFILE) {
1976 file_size = avio_size(ic->pb);
1977 file_size = FFMAX(0, file_size);
1980 if ((!strcmp(ic->iformat->name, "mpeg") ||
1981 !strcmp(ic->iformat->name, "mpegts")) &&
1982 file_size && ic->pb->seekable) {
1983 /* get accurate estimate from the PTSes */
1984 estimate_timings_from_pts(ic, old_offset);
1985 } else if (has_duration(ic)) {
1986 /* at least one component has timings - we use them for all
1988 fill_all_stream_timings(ic);
1990 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1991 /* less precise: use bitrate info */
1992 estimate_timings_from_bit_rate(ic);
1994 update_stream_timings(ic);
1998 AVStream av_unused *st;
1999 for(i = 0;i < ic->nb_streams; i++) {
2000 st = ic->streams[i];
2001 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2002 (double) st->start_time / AV_TIME_BASE,
2003 (double) st->duration / AV_TIME_BASE);
2005 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2006 (double) ic->start_time / AV_TIME_BASE,
2007 (double) ic->duration / AV_TIME_BASE,
2008 ic->bit_rate / 1000);
2012 static int has_codec_parameters(AVStream *st)
2014 AVCodecContext *avctx = st->codec;
2016 switch (avctx->codec_type) {
2017 case AVMEDIA_TYPE_AUDIO:
2018 val = avctx->sample_rate && avctx->channels;
2019 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2022 case AVMEDIA_TYPE_VIDEO:
2024 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2031 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2034 static int has_decode_delay_been_guessed(AVStream *st)
2036 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2037 st->info->nb_decoded_frames >= 6;
2040 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2041 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2043 const AVCodec *codec;
2044 int got_picture = 1, ret = 0;
2045 AVFrame *frame = avcodec_alloc_frame();
2046 AVPacket pkt = *avpkt;
2049 return AVERROR(ENOMEM);
2051 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2052 AVDictionary *thread_opt = NULL;
2054 codec = st->codec->codec ? st->codec->codec :
2055 avcodec_find_decoder(st->codec->codec_id);
2058 st->info->found_decoder = -1;
2063 /* force thread count to 1 since the h264 decoder will not extract SPS
2064 * and PPS to extradata during multi-threaded decoding */
2065 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2066 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2068 av_dict_free(&thread_opt);
2070 st->info->found_decoder = -1;
2073 st->info->found_decoder = 1;
2074 } else if (!st->info->found_decoder)
2075 st->info->found_decoder = 1;
2077 if (st->info->found_decoder < 0) {
2082 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2084 (!has_codec_parameters(st) ||
2085 !has_decode_delay_been_guessed(st) ||
2086 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2088 avcodec_get_frame_defaults(frame);
2089 switch(st->codec->codec_type) {
2090 case AVMEDIA_TYPE_VIDEO:
2091 ret = avcodec_decode_video2(st->codec, frame,
2092 &got_picture, &pkt);
2094 case AVMEDIA_TYPE_AUDIO:
2095 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2102 st->info->nb_decoded_frames++;
2110 avcodec_free_frame(&frame);
2114 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2116 while (tags->id != AV_CODEC_ID_NONE) {
2124 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2127 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2128 if(tag == tags[i].tag)
2131 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2132 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2135 return AV_CODEC_ID_NONE;
2138 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2142 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2143 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2144 default: return AV_CODEC_ID_NONE;
2148 if (sflags & (1 << (bps - 1))) {
2150 case 1: return AV_CODEC_ID_PCM_S8;
2151 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2152 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2153 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2154 default: return AV_CODEC_ID_NONE;
2158 case 1: return AV_CODEC_ID_PCM_U8;
2159 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2160 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2161 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2162 default: return AV_CODEC_ID_NONE;
2168 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2171 for(i=0; tags && tags[i]; i++){
2172 int tag= ff_codec_get_tag(tags[i], id);
2178 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2181 for(i=0; tags && tags[i]; i++){
2182 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2183 if(id!=AV_CODEC_ID_NONE) return id;
2185 return AV_CODEC_ID_NONE;
2188 static void compute_chapters_end(AVFormatContext *s)
2191 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2193 for (i = 0; i < s->nb_chapters; i++)
2194 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2195 AVChapter *ch = s->chapters[i];
2196 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2199 for (j = 0; j < s->nb_chapters; j++) {
2200 AVChapter *ch1 = s->chapters[j];
2201 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2202 if (j != i && next_start > ch->start && next_start < end)
2205 ch->end = (end == INT64_MAX) ? ch->start : end;
2209 static int get_std_framerate(int i){
2210 if(i<60*12) return i*1001;
2211 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2215 * Is the time base unreliable.
2216 * This is a heuristic to balance between quick acceptance of the values in
2217 * the headers vs. some extra checks.
2218 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2219 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2220 * And there are "variable" fps files this needs to detect as well.
2222 static int tb_unreliable(AVCodecContext *c){
2223 if( c->time_base.den >= 101L*c->time_base.num
2224 || c->time_base.den < 5L*c->time_base.num
2225 /* || c->codec_tag == AV_RL32("DIVX")
2226 || c->codec_tag == AV_RL32("XVID")*/
2227 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2228 || c->codec_id == AV_CODEC_ID_H264
2234 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2236 int i, count, ret, read_size, j;
2238 AVPacket pkt1, *pkt;
2239 int64_t old_offset = avio_tell(ic->pb);
2240 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2242 for(i=0;i<ic->nb_streams;i++) {
2243 const AVCodec *codec;
2244 AVDictionary *thread_opt = NULL;
2245 st = ic->streams[i];
2247 //only for the split stuff
2248 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2249 st->parser = av_parser_init(st->codec->codec_id);
2250 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2251 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2254 codec = st->codec->codec ? st->codec->codec :
2255 avcodec_find_decoder(st->codec->codec_id);
2257 /* force thread count to 1 since the h264 decoder will not extract SPS
2258 * and PPS to extradata during multi-threaded decoding */
2259 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2261 /* Ensure that subtitle_header is properly set. */
2262 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2263 && codec && !st->codec->codec)
2264 avcodec_open2(st->codec, codec, options ? &options[i]
2267 //try to just open decoders, in case this is enough to get parameters
2268 if (!has_codec_parameters(st)) {
2269 if (codec && !st->codec->codec)
2270 avcodec_open2(st->codec, codec, options ? &options[i]
2274 av_dict_free(&thread_opt);
2277 for (i=0; i<ic->nb_streams; i++) {
2278 #if FF_API_R_FRAME_RATE
2279 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2281 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2282 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2288 if (ff_check_interrupt(&ic->interrupt_callback)){
2290 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2294 /* check if one codec still needs to be handled */
2295 for(i=0;i<ic->nb_streams;i++) {
2296 int fps_analyze_framecount = 20;
2298 st = ic->streams[i];
2299 if (!has_codec_parameters(st))
2301 /* if the timebase is coarse (like the usual millisecond precision
2302 of mkv), we need to analyze more frames to reliably arrive at
2304 if (av_q2d(st->time_base) > 0.0005)
2305 fps_analyze_framecount *= 2;
2306 if (ic->fps_probe_size >= 0)
2307 fps_analyze_framecount = ic->fps_probe_size;
2308 /* variable fps and no guess at the real fps */
2309 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2310 && st->codec_info_nb_frames < fps_analyze_framecount
2311 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2313 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2315 if (st->first_dts == AV_NOPTS_VALUE &&
2316 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2317 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2320 if (i == ic->nb_streams) {
2321 /* NOTE: if the format has no header, then we need to read
2322 some packets to get most of the streams, so we cannot
2324 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2325 /* if we found the info for all the codecs, we can stop */
2327 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2331 /* we did not get all the codec info, but we read too much data */
2332 if (read_size >= ic->probesize) {
2334 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2338 /* NOTE: a new stream can be added there if no header in file
2339 (AVFMTCTX_NOHEADER) */
2340 ret = read_frame_internal(ic, &pkt1);
2341 if (ret == AVERROR(EAGAIN))
2346 AVPacket empty_pkt = { 0 };
2348 av_init_packet(&empty_pkt);
2350 ret = -1; /* we could not have all the codec parameters before EOF */
2351 for(i=0;i<ic->nb_streams;i++) {
2352 st = ic->streams[i];
2354 /* flush the decoders */
2355 if (st->info->found_decoder == 1) {
2357 err = try_decode_frame(st, &empty_pkt,
2358 (options && i < orig_nb_streams) ?
2359 &options[i] : NULL);
2360 } while (err > 0 && !has_codec_parameters(st));
2364 av_log(ic, AV_LOG_WARNING,
2365 "decoding for stream %d failed\n", st->index);
2366 } else if (!has_codec_parameters(st)) {
2368 avcodec_string(buf, sizeof(buf), st->codec, 0);
2369 av_log(ic, AV_LOG_WARNING,
2370 "Could not find codec parameters (%s)\n", buf);
2378 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2381 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2382 &ic->packet_buffer_end);
2383 if ((ret = av_dup_packet(pkt)) < 0)
2384 goto find_stream_info_err;
2387 read_size += pkt->size;
2389 st = ic->streams[pkt->stream_index];
2390 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2391 /* check for non-increasing dts */
2392 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2393 st->info->fps_last_dts >= pkt->dts) {
2394 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2395 "packet %d with DTS %"PRId64", packet %d with DTS "
2396 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2397 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2398 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2400 /* check for a discontinuity in dts - if the difference in dts
2401 * is more than 1000 times the average packet duration in the sequence,
2402 * we treat it as a discontinuity */
2403 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2404 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2405 (pkt->dts - st->info->fps_last_dts) / 1000 >
2406 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2407 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2408 "packet %d with DTS %"PRId64", packet %d with DTS "
2409 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2410 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2411 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2414 /* update stored dts values */
2415 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2416 st->info->fps_first_dts = pkt->dts;
2417 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2419 st->info->fps_last_dts = pkt->dts;
2420 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2422 /* check max_analyze_duration */
2423 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2424 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2425 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2429 #if FF_API_R_FRAME_RATE
2431 int64_t last = st->info->last_dts;
2433 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
2434 int64_t duration= pkt->dts - last;
2435 double dur= duration * av_q2d(st->time_base);
2437 if (st->info->duration_count < 2)
2438 memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2439 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2440 int framerate= get_std_framerate(i);
2441 int ticks= lrintf(dur*framerate/(1001*12));
2442 double error = dur - (double)ticks*1001*12 / framerate;
2443 st->info->duration_error[i] += error*error;
2445 st->info->duration_count++;
2446 // ignore the first 4 values, they might have some random jitter
2447 if (st->info->duration_count > 3)
2448 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2450 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2451 st->info->last_dts = pkt->dts;
2454 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2455 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2456 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2457 st->codec->extradata_size= i;
2458 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2459 if (!st->codec->extradata)
2460 return AVERROR(ENOMEM);
2461 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2462 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2466 /* if still no information, we try to open the codec and to
2467 decompress the frame. We try to avoid that in most cases as
2468 it takes longer and uses more memory. For MPEG-4, we need to
2469 decompress for QuickTime.
2471 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2472 least one frame of codec data, this makes sure the codec initializes
2473 the channel configuration and does not only trust the values from the container.
2475 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2477 st->codec_info_nb_frames++;
2481 // close codecs which were opened in try_decode_frame()
2482 for(i=0;i<ic->nb_streams;i++) {
2483 st = ic->streams[i];
2484 avcodec_close(st->codec);
2486 for(i=0;i<ic->nb_streams;i++) {
2487 st = ic->streams[i];
2488 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2489 /* estimate average framerate if not set by demuxer */
2490 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2491 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2492 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2494 double best_error = 0.01;
2496 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2497 delta_packets*(int64_t)st->time_base.den,
2498 delta_dts*(int64_t)st->time_base.num, 60000);
2500 /* round guessed framerate to a "standard" framerate if it's
2501 * within 1% of the original estimate*/
2502 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2503 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2504 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2506 if (error < best_error) {
2508 best_fps = std_fps.num;
2512 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2513 best_fps, 12*1001, INT_MAX);
2516 #if FF_API_R_FRAME_RATE
2517 // the check for tb_unreliable() is not completely correct, since this is not about handling
2518 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2519 // ipmovie.c produces.
2520 if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2521 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);
2522 if (st->info->duration_count && !st->r_frame_rate.num
2523 && tb_unreliable(st->codec)) {
2525 double best_error= 2*av_q2d(st->time_base);
2526 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2528 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2529 double error = st->info->duration_error[j] * get_std_framerate(j);
2530 if(error < best_error){
2532 num = get_std_framerate(j);
2535 // do not increase frame rate by more than 1 % in order to match a standard rate.
2536 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2537 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2540 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2541 if(!st->codec->bits_per_coded_sample)
2542 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2543 // set stream disposition based on audio service type
2544 switch (st->codec->audio_service_type) {
2545 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2546 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2547 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2548 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2549 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2550 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2551 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2552 st->disposition = AV_DISPOSITION_COMMENT; break;
2553 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2554 st->disposition = AV_DISPOSITION_KARAOKE; break;
2559 estimate_timings(ic, old_offset);
2561 compute_chapters_end(ic);
2563 find_stream_info_err:
2564 for (i=0; i < ic->nb_streams; i++) {
2565 if (ic->streams[i]->codec)
2566 ic->streams[i]->codec->thread_count = 0;
2567 av_freep(&ic->streams[i]->info);
2572 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2576 for (i = 0; i < ic->nb_programs; i++)
2577 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2578 if (ic->programs[i]->stream_index[j] == s)
2579 return ic->programs[i];
2583 int av_find_best_stream(AVFormatContext *ic,
2584 enum AVMediaType type,
2585 int wanted_stream_nb,
2587 AVCodec **decoder_ret,
2590 int i, nb_streams = ic->nb_streams;
2591 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2592 unsigned *program = NULL;
2593 AVCodec *decoder = NULL, *best_decoder = NULL;
2595 if (related_stream >= 0 && wanted_stream_nb < 0) {
2596 AVProgram *p = find_program_from_stream(ic, related_stream);
2598 program = p->stream_index;
2599 nb_streams = p->nb_stream_indexes;
2602 for (i = 0; i < nb_streams; i++) {
2603 int real_stream_index = program ? program[i] : i;
2604 AVStream *st = ic->streams[real_stream_index];
2605 AVCodecContext *avctx = st->codec;
2606 if (avctx->codec_type != type)
2608 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2610 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2613 decoder = avcodec_find_decoder(st->codec->codec_id);
2616 ret = AVERROR_DECODER_NOT_FOUND;
2620 if (best_count >= st->codec_info_nb_frames)
2622 best_count = st->codec_info_nb_frames;
2623 ret = real_stream_index;
2624 best_decoder = decoder;
2625 if (program && i == nb_streams - 1 && ret < 0) {
2627 nb_streams = ic->nb_streams;
2628 i = 0; /* no related stream found, try again with everything */
2632 *decoder_ret = best_decoder;
2636 /*******************************************************/
2638 int av_read_play(AVFormatContext *s)
2640 if (s->iformat->read_play)
2641 return s->iformat->read_play(s);
2643 return avio_pause(s->pb, 0);
2644 return AVERROR(ENOSYS);
2647 int av_read_pause(AVFormatContext *s)
2649 if (s->iformat->read_pause)
2650 return s->iformat->read_pause(s);
2652 return avio_pause(s->pb, 1);
2653 return AVERROR(ENOSYS);
2656 void avformat_free_context(AVFormatContext *s)
2662 if (s->iformat && s->iformat->priv_class && s->priv_data)
2663 av_opt_free(s->priv_data);
2665 for(i=0;i<s->nb_streams;i++) {
2666 /* free all data in a stream component */
2669 av_parser_close(st->parser);
2671 if (st->attached_pic.data)
2672 av_free_packet(&st->attached_pic);
2673 av_dict_free(&st->metadata);
2674 av_free(st->index_entries);
2675 av_free(st->codec->extradata);
2676 av_free(st->codec->subtitle_header);
2678 av_free(st->priv_data);
2682 for(i=s->nb_programs-1; i>=0; i--) {
2683 av_dict_free(&s->programs[i]->metadata);
2684 av_freep(&s->programs[i]->stream_index);
2685 av_freep(&s->programs[i]);
2687 av_freep(&s->programs);
2688 av_freep(&s->priv_data);
2689 while(s->nb_chapters--) {
2690 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2691 av_free(s->chapters[s->nb_chapters]);
2693 av_freep(&s->chapters);
2694 av_dict_free(&s->metadata);
2695 av_freep(&s->streams);
2699 #if FF_API_CLOSE_INPUT_FILE
2700 void av_close_input_file(AVFormatContext *s)
2702 avformat_close_input(&s);
2706 void avformat_close_input(AVFormatContext **ps)
2708 AVFormatContext *s = *ps;
2709 AVIOContext *pb = s->pb;
2711 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2712 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2715 flush_packet_queue(s);
2718 if (s->iformat->read_close)
2719 s->iformat->read_close(s);
2722 avformat_free_context(s);
2729 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2735 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2737 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2740 s->streams = streams;
2742 st = av_mallocz(sizeof(AVStream));
2745 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2750 st->codec = avcodec_alloc_context3(c);
2752 /* no default bitrate if decoding */
2753 st->codec->bit_rate = 0;
2755 st->index = s->nb_streams;
2756 st->start_time = AV_NOPTS_VALUE;
2757 st->duration = AV_NOPTS_VALUE;
2758 /* we set the current DTS to 0 so that formats without any timestamps
2759 but durations get some timestamps, formats with some unknown
2760 timestamps have their first few packets buffered and the
2761 timestamps corrected before they are returned to the user */
2763 st->first_dts = AV_NOPTS_VALUE;
2764 st->probe_packets = MAX_PROBE_PACKETS;
2766 /* default pts setting is MPEG-like */
2767 avpriv_set_pts_info(st, 33, 1, 90000);
2768 st->last_IP_pts = AV_NOPTS_VALUE;
2769 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2770 st->pts_buffer[i]= AV_NOPTS_VALUE;
2771 st->reference_dts = AV_NOPTS_VALUE;
2773 st->sample_aspect_ratio = (AVRational){0,1};
2775 #if FF_API_R_FRAME_RATE
2776 st->info->last_dts = AV_NOPTS_VALUE;
2778 st->info->fps_first_dts = AV_NOPTS_VALUE;
2779 st->info->fps_last_dts = AV_NOPTS_VALUE;
2781 s->streams[s->nb_streams++] = st;
2785 AVProgram *av_new_program(AVFormatContext *ac, int id)
2787 AVProgram *program=NULL;
2790 av_dlog(ac, "new_program: id=0x%04x\n", id);
2792 for(i=0; i<ac->nb_programs; i++)
2793 if(ac->programs[i]->id == id)
2794 program = ac->programs[i];
2797 program = av_mallocz(sizeof(AVProgram));
2800 dynarray_add(&ac->programs, &ac->nb_programs, program);
2801 program->discard = AVDISCARD_NONE;
2808 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2810 AVChapter *chapter = NULL;
2813 for(i=0; i<s->nb_chapters; i++)
2814 if(s->chapters[i]->id == id)
2815 chapter = s->chapters[i];
2818 chapter= av_mallocz(sizeof(AVChapter));
2821 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2823 av_dict_set(&chapter->metadata, "title", title, 0);
2825 chapter->time_base= time_base;
2826 chapter->start = start;
2832 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2835 AVProgram *program=NULL;
2838 if (idx >= ac->nb_streams) {
2839 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2843 for(i=0; i<ac->nb_programs; i++){
2844 if(ac->programs[i]->id != progid)
2846 program = ac->programs[i];
2847 for(j=0; j<program->nb_stream_indexes; j++)
2848 if(program->stream_index[j] == idx)
2851 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2854 program->stream_index = tmp;
2855 program->stream_index[program->nb_stream_indexes++] = idx;
2860 static void print_fps(double d, const char *postfix){
2861 uint64_t v= lrintf(d*100);
2862 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2863 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2864 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2867 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2869 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2870 AVDictionaryEntry *tag=NULL;
2872 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2873 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2874 if(strcmp("language", tag->key))
2875 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2880 /* "user interface" functions */
2881 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2884 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2885 AVStream *st = ic->streams[i];
2886 int g = av_gcd(st->time_base.num, st->time_base.den);
2887 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2888 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2889 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2890 /* the pid is an important information, so we display it */
2891 /* XXX: add a generic system */
2892 if (flags & AVFMT_SHOW_IDS)
2893 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2895 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2896 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2897 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2898 if (st->sample_aspect_ratio.num && // default
2899 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2900 AVRational display_aspect_ratio;
2901 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2902 st->codec->width*st->sample_aspect_ratio.num,
2903 st->codec->height*st->sample_aspect_ratio.den,
2905 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2906 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2907 display_aspect_ratio.num, display_aspect_ratio.den);
2909 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2910 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2911 print_fps(av_q2d(st->avg_frame_rate), "fps");
2912 #if FF_API_R_FRAME_RATE
2913 if(st->r_frame_rate.den && st->r_frame_rate.num)
2914 print_fps(av_q2d(st->r_frame_rate), "tbr");
2916 if(st->time_base.den && st->time_base.num)
2917 print_fps(1/av_q2d(st->time_base), "tbn");
2918 if(st->codec->time_base.den && st->codec->time_base.num)
2919 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2921 if (st->disposition & AV_DISPOSITION_DEFAULT)
2922 av_log(NULL, AV_LOG_INFO, " (default)");
2923 if (st->disposition & AV_DISPOSITION_DUB)
2924 av_log(NULL, AV_LOG_INFO, " (dub)");
2925 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2926 av_log(NULL, AV_LOG_INFO, " (original)");
2927 if (st->disposition & AV_DISPOSITION_COMMENT)
2928 av_log(NULL, AV_LOG_INFO, " (comment)");
2929 if (st->disposition & AV_DISPOSITION_LYRICS)
2930 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2931 if (st->disposition & AV_DISPOSITION_KARAOKE)
2932 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2933 if (st->disposition & AV_DISPOSITION_FORCED)
2934 av_log(NULL, AV_LOG_INFO, " (forced)");
2935 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2936 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2937 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2938 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2939 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2940 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2941 av_log(NULL, AV_LOG_INFO, "\n");
2942 dump_metadata(NULL, st->metadata, " ");
2945 void av_dump_format(AVFormatContext *ic,
2951 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2952 if (ic->nb_streams && !printed)
2955 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2956 is_output ? "Output" : "Input",
2958 is_output ? ic->oformat->name : ic->iformat->name,
2959 is_output ? "to" : "from", url);
2960 dump_metadata(NULL, ic->metadata, " ");
2962 av_log(NULL, AV_LOG_INFO, " Duration: ");
2963 if (ic->duration != AV_NOPTS_VALUE) {
2964 int hours, mins, secs, us;
2965 secs = ic->duration / AV_TIME_BASE;
2966 us = ic->duration % AV_TIME_BASE;
2971 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2972 (100 * us) / AV_TIME_BASE);
2974 av_log(NULL, AV_LOG_INFO, "N/A");
2976 if (ic->start_time != AV_NOPTS_VALUE) {
2978 av_log(NULL, AV_LOG_INFO, ", start: ");
2979 secs = ic->start_time / AV_TIME_BASE;
2980 us = abs(ic->start_time % AV_TIME_BASE);
2981 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2982 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2984 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2986 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2988 av_log(NULL, AV_LOG_INFO, "N/A");
2990 av_log(NULL, AV_LOG_INFO, "\n");
2992 for (i = 0; i < ic->nb_chapters; i++) {
2993 AVChapter *ch = ic->chapters[i];
2994 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2995 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2996 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2998 dump_metadata(NULL, ch->metadata, " ");
3000 if(ic->nb_programs) {
3001 int j, k, total = 0;
3002 for(j=0; j<ic->nb_programs; j++) {
3003 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
3005 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3006 name ? name->value : "");
3007 dump_metadata(NULL, ic->programs[j]->metadata, " ");
3008 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3009 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3010 printed[ic->programs[j]->stream_index[k]] = 1;
3012 total += ic->programs[j]->nb_stream_indexes;
3014 if (total < ic->nb_streams)
3015 av_log(NULL, AV_LOG_INFO, " No Program\n");
3017 for(i=0;i<ic->nb_streams;i++)
3019 dump_stream_format(ic, i, index, is_output);
3024 #if FF_API_AV_GETTIME && CONFIG_SHARED && HAVE_SYMVER
3025 FF_SYMVER(int64_t, av_gettime, (void), "LIBAVFORMAT_54")
3027 return av_gettime();
3031 uint64_t ff_ntp_time(void)
3033 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3036 int av_get_frame_filename(char *buf, int buf_size,
3037 const char *path, int number)
3040 char *q, buf1[20], c;
3041 int nd, len, percentd_found;
3053 while (isdigit(*p)) {
3054 nd = nd * 10 + *p++ - '0';
3057 } while (isdigit(c));
3066 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3068 if ((q - buf + len) > buf_size - 1)
3070 memcpy(q, buf1, len);
3078 if ((q - buf) < buf_size - 1)
3082 if (!percentd_found)
3091 static void hex_dump_internal(void *avcl, FILE *f, int level,
3092 const uint8_t *buf, int size)
3095 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3097 for(i=0;i<size;i+=16) {
3104 PRINT(" %02x", buf[i+j]);
3109 for(j=0;j<len;j++) {
3111 if (c < ' ' || c > '~')
3120 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3122 hex_dump_internal(NULL, f, 0, buf, size);
3125 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3127 hex_dump_internal(avcl, NULL, level, buf, size);
3130 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3132 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3133 PRINT("stream #%d:\n", pkt->stream_index);
3134 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3135 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3136 /* DTS is _always_ valid after av_read_frame() */
3138 if (pkt->dts == AV_NOPTS_VALUE)
3141 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3142 /* PTS may not be known if B-frames are present. */
3144 if (pkt->pts == AV_NOPTS_VALUE)
3147 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3149 PRINT(" size=%d\n", pkt->size);
3152 av_hex_dump(f, pkt->data, pkt->size);
3155 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3157 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3160 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3163 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3166 void av_url_split(char *proto, int proto_size,
3167 char *authorization, int authorization_size,
3168 char *hostname, int hostname_size,
3170 char *path, int path_size,
3173 const char *p, *ls, *at, *col, *brk;
3175 if (port_ptr) *port_ptr = -1;
3176 if (proto_size > 0) proto[0] = 0;
3177 if (authorization_size > 0) authorization[0] = 0;
3178 if (hostname_size > 0) hostname[0] = 0;
3179 if (path_size > 0) path[0] = 0;
3181 /* parse protocol */
3182 if ((p = strchr(url, ':'))) {
3183 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3188 /* no protocol means plain filename */
3189 av_strlcpy(path, url, path_size);
3193 /* separate path from hostname */
3194 ls = strchr(p, '/');
3196 ls = strchr(p, '?');
3198 av_strlcpy(path, ls, path_size);
3200 ls = &p[strlen(p)]; // XXX
3202 /* the rest is hostname, use that to parse auth/port */
3204 /* authorization (user[:pass]@hostname) */
3205 if ((at = strchr(p, '@')) && at < ls) {
3206 av_strlcpy(authorization, p,
3207 FFMIN(authorization_size, at + 1 - p));
3208 p = at + 1; /* skip '@' */
3211 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3213 av_strlcpy(hostname, p + 1,
3214 FFMIN(hostname_size, brk - p));
3215 if (brk[1] == ':' && port_ptr)
3216 *port_ptr = atoi(brk + 2);
3217 } else if ((col = strchr(p, ':')) && col < ls) {
3218 av_strlcpy(hostname, p,
3219 FFMIN(col + 1 - p, hostname_size));
3220 if (port_ptr) *port_ptr = atoi(col + 1);
3222 av_strlcpy(hostname, p,
3223 FFMIN(ls + 1 - p, hostname_size));
3227 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3230 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3233 'C', 'D', 'E', 'F' };
3234 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3237 'c', 'd', 'e', 'f' };
3238 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3240 for(i = 0; i < s; i++) {
3241 buff[i * 2] = hex_table[src[i] >> 4];
3242 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3248 int ff_hex_to_data(uint8_t *data, const char *p)
3255 p += strspn(p, SPACE_CHARS);
3258 c = toupper((unsigned char) *p++);
3259 if (c >= '0' && c <= '9')
3261 else if (c >= 'A' && c <= 'F')
3276 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3277 unsigned int pts_num, unsigned int pts_den)
3280 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3281 if(new_tb.num != pts_num)
3282 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3284 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3286 if(new_tb.num <= 0 || new_tb.den <= 0) {
3287 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3290 s->time_base = new_tb;
3291 s->pts_wrap_bits = pts_wrap_bits;
3294 int ff_url_join(char *str, int size, const char *proto,
3295 const char *authorization, const char *hostname,
3296 int port, const char *fmt, ...)
3299 struct addrinfo hints = { 0 }, *ai;
3304 av_strlcatf(str, size, "%s://", proto);
3305 if (authorization && authorization[0])
3306 av_strlcatf(str, size, "%s@", authorization);
3307 #if CONFIG_NETWORK && defined(AF_INET6)
3308 /* Determine if hostname is a numerical IPv6 address,
3309 * properly escape it within [] in that case. */
3310 hints.ai_flags = AI_NUMERICHOST;
3311 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3312 if (ai->ai_family == AF_INET6) {
3313 av_strlcat(str, "[", size);
3314 av_strlcat(str, hostname, size);
3315 av_strlcat(str, "]", size);
3317 av_strlcat(str, hostname, size);
3322 /* Not an IPv6 address, just output the plain string. */
3323 av_strlcat(str, hostname, size);
3326 av_strlcatf(str, size, ":%d", port);
3329 int len = strlen(str);
3332 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3338 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3339 AVFormatContext *src)
3344 local_pkt.stream_index = dst_stream;
3345 if (pkt->pts != AV_NOPTS_VALUE)
3346 local_pkt.pts = av_rescale_q(pkt->pts,
3347 src->streams[pkt->stream_index]->time_base,
3348 dst->streams[dst_stream]->time_base);
3349 if (pkt->dts != AV_NOPTS_VALUE)
3350 local_pkt.dts = av_rescale_q(pkt->dts,
3351 src->streams[pkt->stream_index]->time_base,
3352 dst->streams[dst_stream]->time_base);
3353 return av_write_frame(dst, &local_pkt);
3356 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3359 const char *ptr = str;
3361 /* Parse key=value pairs. */
3364 char *dest = NULL, *dest_end;
3365 int key_len, dest_len = 0;
3367 /* Skip whitespace and potential commas. */
3368 while (*ptr && (isspace(*ptr) || *ptr == ','))
3375 if (!(ptr = strchr(key, '=')))
3378 key_len = ptr - key;
3380 callback_get_buf(context, key, key_len, &dest, &dest_len);
3381 dest_end = dest + dest_len - 1;
3385 while (*ptr && *ptr != '\"') {
3389 if (dest && dest < dest_end)
3393 if (dest && dest < dest_end)
3401 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3402 if (dest && dest < dest_end)
3410 int ff_find_stream_index(AVFormatContext *s, int id)
3413 for (i = 0; i < s->nb_streams; i++) {
3414 if (s->streams[i]->id == id)
3420 void ff_make_absolute_url(char *buf, int size, const char *base,
3423 char *sep, *path_query;
3424 /* Absolute path, relative to the current server */
3425 if (base && strstr(base, "://") && rel[0] == '/') {
3427 av_strlcpy(buf, base, size);
3428 sep = strstr(buf, "://");
3430 /* Take scheme from base url */
3431 if (rel[1] == '/') {
3434 /* Take scheme and host from base url */
3436 sep = strchr(sep, '/');
3441 av_strlcat(buf, rel, size);
3444 /* If rel actually is an absolute url, just copy it */
3445 if (!base || strstr(rel, "://") || rel[0] == '/') {
3446 av_strlcpy(buf, rel, size);
3450 av_strlcpy(buf, base, size);
3452 /* Strip off any query string from base */
3453 path_query = strchr(buf, '?');
3454 if (path_query != NULL)
3457 /* Is relative path just a new query part? */
3458 if (rel[0] == '?') {
3459 av_strlcat(buf, rel, size);
3463 /* Remove the file name from the base url */
3464 sep = strrchr(buf, '/');
3469 while (av_strstart(rel, "../", NULL) && sep) {
3470 /* Remove the path delimiter at the end */
3472 sep = strrchr(buf, '/');
3473 /* If the next directory name to pop off is "..", break here */
3474 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3475 /* Readd the slash we just removed */
3476 av_strlcat(buf, "/", size);
3479 /* Cut off the directory name */
3486 av_strlcat(buf, rel, size);
3489 int64_t ff_iso8601_to_unix_time(const char *datestr)
3492 struct tm time1 = {0}, time2 = {0};
3494 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3495 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3497 return av_timegm(&time2);
3499 return av_timegm(&time1);
3501 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3502 "the date string.\n");
3507 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3510 if (ofmt->query_codec)
3511 return ofmt->query_codec(codec_id, std_compliance);
3512 else if (ofmt->codec_tag)
3513 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3514 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3515 codec_id == ofmt->subtitle_codec)
3518 return AVERROR_PATCHWELCOME;
3521 int avformat_network_init(void)
3525 ff_network_inited_globally = 1;
3526 if ((ret = ff_network_init()) < 0)
3533 int avformat_network_deinit(void)
3542 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3543 uint64_t channel_layout, int32_t sample_rate,
3544 int32_t width, int32_t height)
3550 return AVERROR(EINVAL);
3553 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3555 if (channel_layout) {
3557 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3561 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3563 if (width || height) {
3565 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3567 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3569 return AVERROR(ENOMEM);
3570 bytestream_put_le32(&data, flags);
3572 bytestream_put_le32(&data, channels);
3574 bytestream_put_le64(&data, channel_layout);
3576 bytestream_put_le32(&data, sample_rate);
3577 if (width || height) {
3578 bytestream_put_le32(&data, width);
3579 bytestream_put_le32(&data, height);
3584 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3586 return ff_codec_bmp_tags;
3588 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3590 return ff_codec_wav_tags;