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 int 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.buf = av_buffer_ref(copy.buf);
476 return AVERROR(ENOMEM);
478 add_to_pktbuf(&s->raw_packet_buffer, ©, &s->raw_packet_buffer_end);
483 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
485 AVFormatContext *s = *ps;
487 AVDictionary *tmp = NULL;
488 ID3v2ExtraMeta *id3v2_extra_meta = NULL;
490 if (!s && !(s = avformat_alloc_context()))
491 return AVERROR(ENOMEM);
496 av_dict_copy(&tmp, *options, 0);
498 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
501 if ((ret = init_input(s, filename, &tmp)) < 0)
504 /* check filename in case an image number is expected */
505 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
506 if (!av_filename_number_test(filename)) {
507 ret = AVERROR(EINVAL);
512 s->duration = s->start_time = AV_NOPTS_VALUE;
513 av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));
515 /* allocate private data */
516 if (s->iformat->priv_data_size > 0) {
517 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
518 ret = AVERROR(ENOMEM);
521 if (s->iformat->priv_class) {
522 *(const AVClass**)s->priv_data = s->iformat->priv_class;
523 av_opt_set_defaults(s->priv_data);
524 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
529 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
531 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
533 if (s->iformat->read_header)
534 if ((ret = s->iformat->read_header(s)) < 0)
537 if (id3v2_extra_meta &&
538 (ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)
540 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
542 if ((ret = queue_attached_pictures(s)) < 0)
545 if (s->pb && !s->data_offset)
546 s->data_offset = avio_tell(s->pb);
548 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
551 av_dict_free(options);
558 ff_id3v2_free_extra_meta(&id3v2_extra_meta);
560 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
562 avformat_free_context(s);
567 /*******************************************************/
569 static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
571 if(st->codec->codec_id == AV_CODEC_ID_PROBE){
572 AVProbeData *pd = &st->probe_data;
573 av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);
577 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
578 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
579 pd->buf_size += pkt->size;
580 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
582 st->probe_packets = 0;
584 av_log(s, AV_LOG_ERROR, "nothing to probe for stream %d\n",
590 if (!st->probe_packets ||
591 av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)) {
592 set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);
593 if(st->codec->codec_id != AV_CODEC_ID_PROBE){
596 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
602 int ff_read_packet(AVFormatContext *s, AVPacket *pkt)
608 AVPacketList *pktl = s->raw_packet_buffer;
612 st = s->streams[pkt->stream_index];
613 if (st->codec->codec_id != AV_CODEC_ID_PROBE || !st->probe_packets ||
614 s->raw_packet_buffer_remaining_size < pkt->size) {
616 if (st->probe_packets) {
617 probe_codec(s, st, NULL);
619 pd = &st->probe_data;
622 s->raw_packet_buffer = pktl->next;
623 s->raw_packet_buffer_remaining_size += pkt->size;
632 ret= s->iformat->read_packet(s, pkt);
634 if (!pktl || ret == AVERROR(EAGAIN))
636 for (i = 0; i < s->nb_streams; i++) {
638 if (st->probe_packets) {
639 probe_codec(s, st, NULL);
645 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
646 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
647 av_log(s, AV_LOG_WARNING,
648 "Dropped corrupted packet (stream = %d)\n",
654 st= s->streams[pkt->stream_index];
656 switch(st->codec->codec_type){
657 case AVMEDIA_TYPE_VIDEO:
658 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
660 case AVMEDIA_TYPE_AUDIO:
661 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
663 case AVMEDIA_TYPE_SUBTITLE:
664 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
668 if(!pktl && (st->codec->codec_id != AV_CODEC_ID_PROBE ||
672 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
673 s->raw_packet_buffer_remaining_size -= pkt->size;
675 probe_codec(s, st, pkt);
679 /**********************************************************/
682 * Get the number of samples of an audio frame. Return -1 on error.
684 int ff_get_audio_frame_size(AVCodecContext *enc, int size, int mux)
688 /* give frame_size priority if demuxing */
689 if (!mux && enc->frame_size > 1)
690 return enc->frame_size;
692 if ((frame_size = av_get_audio_frame_duration(enc, size)) > 0)
695 /* fallback to using frame_size if muxing */
696 if (enc->frame_size > 1)
697 return enc->frame_size;
704 * Return the frame duration in seconds. Return 0 if not available.
706 void ff_compute_frame_duration(int *pnum, int *pden, AVStream *st,
707 AVCodecParserContext *pc, AVPacket *pkt)
713 switch(st->codec->codec_type) {
714 case AVMEDIA_TYPE_VIDEO:
715 if (st->avg_frame_rate.num) {
716 *pnum = st->avg_frame_rate.den;
717 *pden = st->avg_frame_rate.num;
718 } else if(st->time_base.num*1000LL > st->time_base.den) {
719 *pnum = st->time_base.num;
720 *pden = st->time_base.den;
721 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
722 *pnum = st->codec->time_base.num;
723 *pden = st->codec->time_base.den;
724 if (pc && pc->repeat_pict) {
725 if (*pnum > INT_MAX / (1 + pc->repeat_pict))
726 *pden /= 1 + pc->repeat_pict;
728 *pnum *= 1 + pc->repeat_pict;
730 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
731 //Thus if we have no parser in such case leave duration undefined.
732 if(st->codec->ticks_per_frame>1 && !pc){
737 case AVMEDIA_TYPE_AUDIO:
738 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 0);
739 if (frame_size <= 0 || st->codec->sample_rate <= 0)
742 *pden = st->codec->sample_rate;
749 static int is_intra_only(enum AVCodecID id)
751 const AVCodecDescriptor *d = avcodec_descriptor_get(id);
754 if (d->type == AVMEDIA_TYPE_VIDEO && !(d->props & AV_CODEC_PROP_INTRA_ONLY))
759 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
760 int64_t dts, int64_t pts)
762 AVStream *st= s->streams[stream_index];
763 AVPacketList *pktl= s->packet_buffer;
765 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
768 st->first_dts= dts - st->cur_dts;
771 for(; pktl; pktl= pktl->next){
772 if(pktl->pkt.stream_index != stream_index)
774 //FIXME think more about this check
775 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
776 pktl->pkt.pts += st->first_dts;
778 if(pktl->pkt.dts != AV_NOPTS_VALUE)
779 pktl->pkt.dts += st->first_dts;
781 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
782 st->start_time= pktl->pkt.pts;
784 if (st->start_time == AV_NOPTS_VALUE)
785 st->start_time = pts;
788 static void update_initial_durations(AVFormatContext *s, AVStream *st,
789 int stream_index, int duration)
791 AVPacketList *pktl= s->packet_buffer;
794 if(st->first_dts != AV_NOPTS_VALUE){
795 cur_dts= st->first_dts;
796 for(; pktl; pktl= pktl->next){
797 if(pktl->pkt.stream_index == stream_index){
798 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
803 pktl= s->packet_buffer;
804 st->first_dts = cur_dts;
805 }else if(st->cur_dts)
808 for(; pktl; pktl= pktl->next){
809 if(pktl->pkt.stream_index != stream_index)
811 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
812 && !pktl->pkt.duration){
813 pktl->pkt.dts= cur_dts;
814 if(!st->codec->has_b_frames)
815 pktl->pkt.pts= cur_dts;
817 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
818 pktl->pkt.duration = duration;
822 if(st->first_dts == AV_NOPTS_VALUE)
823 st->cur_dts= cur_dts;
826 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
827 AVCodecParserContext *pc, AVPacket *pkt)
829 int num, den, presentation_delayed, delay, i;
832 if (s->flags & AVFMT_FLAG_NOFILLIN)
835 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
836 pkt->dts= AV_NOPTS_VALUE;
838 /* do we have a video B-frame ? */
839 delay= st->codec->has_b_frames;
840 presentation_delayed = 0;
842 /* XXX: need has_b_frame, but cannot get it if the codec is
845 pc && pc->pict_type != AV_PICTURE_TYPE_B)
846 presentation_delayed = 1;
848 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
849 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
850 pkt->dts -= 1LL<<st->pts_wrap_bits;
853 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
854 // we take the conservative approach and discard both
855 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
856 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
857 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
858 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
861 if (pkt->duration == 0 && st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
862 ff_compute_frame_duration(&num, &den, st, pc, pkt);
864 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
866 if(pkt->duration != 0 && s->packet_buffer)
867 update_initial_durations(s, st, pkt->stream_index, pkt->duration);
871 /* correct timestamps with byte offset if demuxers only have timestamps
872 on packet boundaries */
873 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
874 /* this will estimate bitrate based on this frame's duration and size */
875 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
876 if(pkt->pts != AV_NOPTS_VALUE)
878 if(pkt->dts != AV_NOPTS_VALUE)
882 if (pc && pc->dts_sync_point >= 0) {
883 // we have synchronization info from the parser
884 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
886 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
887 if (pkt->dts != AV_NOPTS_VALUE) {
888 // got DTS from the stream, update reference timestamp
889 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
890 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
891 } else if (st->reference_dts != AV_NOPTS_VALUE) {
892 // compute DTS based on reference timestamp
893 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
894 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
896 if (pc->dts_sync_point > 0)
897 st->reference_dts = pkt->dts; // new reference
901 /* This may be redundant, but it should not hurt. */
902 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
903 presentation_delayed = 1;
906 "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n",
907 presentation_delayed, pkt->pts, pkt->dts, st->cur_dts,
908 pkt->stream_index, pc);
909 /* interpolate PTS and DTS if they are not present */
910 //We skip H264 currently because delay and has_b_frames are not reliably set
911 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != AV_CODEC_ID_H264){
912 if (presentation_delayed) {
913 /* DTS = decompression timestamp */
914 /* PTS = presentation timestamp */
915 if (pkt->dts == AV_NOPTS_VALUE)
916 pkt->dts = st->last_IP_pts;
917 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
918 if (pkt->dts == AV_NOPTS_VALUE)
919 pkt->dts = st->cur_dts;
921 /* this is tricky: the dts must be incremented by the duration
922 of the frame we are displaying, i.e. the last I- or P-frame */
923 if (st->last_IP_duration == 0)
924 st->last_IP_duration = pkt->duration;
925 if(pkt->dts != AV_NOPTS_VALUE)
926 st->cur_dts = pkt->dts + st->last_IP_duration;
927 st->last_IP_duration = pkt->duration;
928 st->last_IP_pts= pkt->pts;
929 /* cannot compute PTS if not present (we can compute it only
930 by knowing the future */
931 } else if (pkt->pts != AV_NOPTS_VALUE ||
932 pkt->dts != AV_NOPTS_VALUE ||
934 st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
935 int duration = pkt->duration;
936 if (!duration && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
937 ff_compute_frame_duration(&num, &den, st, pc, pkt);
939 duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den,
940 den * (int64_t)st->time_base.num,
942 if (duration != 0 && s->packet_buffer) {
943 update_initial_durations(s, st, pkt->stream_index,
949 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE ||
951 /* presentation is not delayed : PTS and DTS are the same */
952 if (pkt->pts == AV_NOPTS_VALUE)
954 update_initial_timestamps(s, pkt->stream_index, pkt->pts,
956 if (pkt->pts == AV_NOPTS_VALUE)
957 pkt->pts = st->cur_dts;
959 if (pkt->pts != AV_NOPTS_VALUE)
960 st->cur_dts = pkt->pts + duration;
965 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
966 st->pts_buffer[0]= pkt->pts;
967 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
968 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
969 if(pkt->dts == AV_NOPTS_VALUE)
970 pkt->dts= st->pts_buffer[0];
971 if(st->codec->codec_id == AV_CODEC_ID_H264){ // we skipped it above so we try here
972 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
974 if(pkt->dts > st->cur_dts)
975 st->cur_dts = pkt->dts;
979 "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n",
980 presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
983 if (is_intra_only(st->codec->codec_id))
984 pkt->flags |= AV_PKT_FLAG_KEY;
986 pkt->convergence_duration = pc->convergence_duration;
989 static void free_packet_buffer(AVPacketList **pkt_buf, AVPacketList **pkt_buf_end)
992 AVPacketList *pktl = *pkt_buf;
993 *pkt_buf = pktl->next;
994 av_free_packet(&pktl->pkt);
1001 * Parse a packet, add all split parts to parse_queue
1003 * @param pkt packet to parse, NULL when flushing the parser at end of stream
1005 static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)
1007 AVPacket out_pkt = { 0 }, flush_pkt = { 0 };
1008 AVStream *st = s->streams[stream_index];
1009 uint8_t *data = pkt ? pkt->data : NULL;
1010 int size = pkt ? pkt->size : 0;
1011 int ret = 0, got_output = 0;
1014 av_init_packet(&flush_pkt);
1019 while (size > 0 || (pkt == &flush_pkt && got_output)) {
1022 av_init_packet(&out_pkt);
1023 len = av_parser_parse2(st->parser, st->codec,
1024 &out_pkt.data, &out_pkt.size, data, size,
1025 pkt->pts, pkt->dts, pkt->pos);
1027 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1028 /* increment read pointer */
1032 got_output = !!out_pkt.size;
1037 /* set the duration */
1038 out_pkt.duration = 0;
1039 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
1040 if (st->codec->sample_rate > 0) {
1041 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1042 (AVRational){ 1, st->codec->sample_rate },
1046 } else if (st->codec->time_base.num != 0 &&
1047 st->codec->time_base.den != 0) {
1048 out_pkt.duration = av_rescale_q_rnd(st->parser->duration,
1049 st->codec->time_base,
1054 out_pkt.stream_index = st->index;
1055 out_pkt.pts = st->parser->pts;
1056 out_pkt.dts = st->parser->dts;
1057 out_pkt.pos = st->parser->pos;
1059 if (st->parser->key_frame == 1 ||
1060 (st->parser->key_frame == -1 &&
1061 st->parser->pict_type == AV_PICTURE_TYPE_I))
1062 out_pkt.flags |= AV_PKT_FLAG_KEY;
1064 compute_pkt_fields(s, st, st->parser, &out_pkt);
1066 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1067 out_pkt.flags & AV_PKT_FLAG_KEY) {
1068 ff_reduce_index(s, st->index);
1069 av_add_index_entry(st, st->parser->frame_offset, out_pkt.dts,
1070 0, 0, AVINDEX_KEYFRAME);
1073 if (out_pkt.data == pkt->data && out_pkt.size == pkt->size) {
1074 out_pkt.buf = pkt->buf;
1076 #if FF_API_DESTRUCT_PACKET
1077 out_pkt.destruct = pkt->destruct;
1078 pkt->destruct = NULL;
1081 if ((ret = av_dup_packet(&out_pkt)) < 0)
1084 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1085 av_free_packet(&out_pkt);
1086 ret = AVERROR(ENOMEM);
1092 /* end of the stream => close and free the parser */
1093 if (pkt == &flush_pkt) {
1094 av_parser_close(st->parser);
1099 av_free_packet(pkt);
1103 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1104 AVPacketList **pkt_buffer_end,
1108 av_assert0(*pkt_buffer);
1111 *pkt_buffer = pktl->next;
1113 *pkt_buffer_end = NULL;
1118 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1120 int ret = 0, i, got_packet = 0;
1122 av_init_packet(pkt);
1124 while (!got_packet && !s->parse_queue) {
1128 /* read next packet */
1129 ret = ff_read_packet(s, &cur_pkt);
1131 if (ret == AVERROR(EAGAIN))
1133 /* flush the parsers */
1134 for(i = 0; i < s->nb_streams; i++) {
1136 if (st->parser && st->need_parsing)
1137 parse_packet(s, NULL, st->index);
1139 /* all remaining packets are now in parse_queue =>
1140 * really terminate parsing */
1144 st = s->streams[cur_pkt.stream_index];
1146 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1147 cur_pkt.dts != AV_NOPTS_VALUE &&
1148 cur_pkt.pts < cur_pkt.dts) {
1149 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1150 cur_pkt.stream_index,
1155 if (s->debug & FF_FDEBUG_TS)
1156 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1157 cur_pkt.stream_index,
1164 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1165 st->parser = av_parser_init(st->codec->codec_id);
1167 /* no parser available: just output the raw packets */
1168 st->need_parsing = AVSTREAM_PARSE_NONE;
1169 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1170 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1171 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1172 st->parser->flags |= PARSER_FLAG_ONCE;
1176 if (!st->need_parsing || !st->parser) {
1177 /* no parsing needed: we just output the packet as is */
1179 compute_pkt_fields(s, st, NULL, pkt);
1180 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1181 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1182 ff_reduce_index(s, st->index);
1183 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1186 } else if (st->discard < AVDISCARD_ALL) {
1187 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1191 av_free_packet(&cur_pkt);
1195 if (!got_packet && s->parse_queue)
1196 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1198 if(s->debug & FF_FDEBUG_TS)
1199 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1210 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1212 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1216 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1217 &s->packet_buffer_end,
1219 read_frame_internal(s, pkt);
1223 AVPacketList *pktl = s->packet_buffer;
1226 AVPacket *next_pkt = &pktl->pkt;
1228 if (next_pkt->dts != AV_NOPTS_VALUE) {
1229 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1230 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1231 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1232 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1233 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1234 next_pkt->pts = pktl->pkt.dts;
1238 pktl = s->packet_buffer;
1241 /* read packet from packet buffer, if there is data */
1242 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1243 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1244 return read_from_packet_buffer(&s->packet_buffer,
1245 &s->packet_buffer_end, pkt);
1248 ret = read_frame_internal(s, pkt);
1250 if (pktl && ret != AVERROR(EAGAIN)) {
1257 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1258 &s->packet_buffer_end)) < 0)
1259 return AVERROR(ENOMEM);
1263 /* XXX: suppress the packet queue */
1264 static void flush_packet_queue(AVFormatContext *s)
1266 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1267 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1268 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1270 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1273 /*******************************************************/
1276 int av_find_default_stream_index(AVFormatContext *s)
1278 int first_audio_index = -1;
1282 if (s->nb_streams <= 0)
1284 for(i = 0; i < s->nb_streams; i++) {
1286 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1287 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1290 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1291 first_audio_index = i;
1293 return first_audio_index >= 0 ? first_audio_index : 0;
1297 * Flush the frame reader.
1299 void ff_read_frame_flush(AVFormatContext *s)
1304 flush_packet_queue(s);
1306 /* for each stream, reset read state */
1307 for(i = 0; i < s->nb_streams; i++) {
1311 av_parser_close(st->parser);
1314 st->last_IP_pts = AV_NOPTS_VALUE;
1315 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1316 st->reference_dts = AV_NOPTS_VALUE;
1318 st->probe_packets = MAX_PROBE_PACKETS;
1320 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1321 st->pts_buffer[j]= AV_NOPTS_VALUE;
1325 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1329 for(i = 0; i < s->nb_streams; i++) {
1330 AVStream *st = s->streams[i];
1332 st->cur_dts = av_rescale(timestamp,
1333 st->time_base.den * (int64_t)ref_st->time_base.num,
1334 st->time_base.num * (int64_t)ref_st->time_base.den);
1338 void ff_reduce_index(AVFormatContext *s, int stream_index)
1340 AVStream *st= s->streams[stream_index];
1341 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1343 if((unsigned)st->nb_index_entries >= max_entries){
1345 for(i=0; 2*i<st->nb_index_entries; i++)
1346 st->index_entries[i]= st->index_entries[2*i];
1347 st->nb_index_entries= i;
1351 int ff_add_index_entry(AVIndexEntry **index_entries,
1352 int *nb_index_entries,
1353 unsigned int *index_entries_allocated_size,
1354 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1356 AVIndexEntry *entries, *ie;
1359 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1362 entries = av_fast_realloc(*index_entries,
1363 index_entries_allocated_size,
1364 (*nb_index_entries + 1) *
1365 sizeof(AVIndexEntry));
1369 *index_entries= entries;
1371 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1374 index= (*nb_index_entries)++;
1375 ie= &entries[index];
1376 assert(index==0 || ie[-1].timestamp < timestamp);
1378 ie= &entries[index];
1379 if(ie->timestamp != timestamp){
1380 if(ie->timestamp <= timestamp)
1382 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1383 (*nb_index_entries)++;
1384 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1385 distance= ie->min_distance;
1389 ie->timestamp = timestamp;
1390 ie->min_distance= distance;
1397 int av_add_index_entry(AVStream *st,
1398 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1400 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1401 &st->index_entries_allocated_size, pos,
1402 timestamp, size, distance, flags);
1405 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1406 int64_t wanted_timestamp, int flags)
1414 //optimize appending index entries at the end
1415 if(b && entries[b-1].timestamp < wanted_timestamp)
1420 timestamp = entries[m].timestamp;
1421 if(timestamp >= wanted_timestamp)
1423 if(timestamp <= wanted_timestamp)
1426 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1428 if(!(flags & AVSEEK_FLAG_ANY)){
1429 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1430 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1439 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1442 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1443 wanted_timestamp, flags);
1446 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1448 AVInputFormat *avif= s->iformat;
1449 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1450 int64_t ts_min, ts_max, ts;
1455 if (stream_index < 0)
1458 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1461 ts_min= AV_NOPTS_VALUE;
1462 pos_limit= -1; //gcc falsely says it may be uninitialized
1464 st= s->streams[stream_index];
1465 if(st->index_entries){
1468 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()
1469 index= FFMAX(index, 0);
1470 e= &st->index_entries[index];
1472 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1474 ts_min= e->timestamp;
1475 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1481 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1482 assert(index < st->nb_index_entries);
1484 e= &st->index_entries[index];
1485 assert(e->timestamp >= target_ts);
1487 ts_max= e->timestamp;
1488 pos_limit= pos_max - e->min_distance;
1489 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1490 pos_max,pos_limit, ts_max);
1494 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1499 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1502 ff_update_cur_dts(s, st, ts);
1507 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1508 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1509 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1510 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1513 int64_t start_pos, filesize;
1516 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1518 if(ts_min == AV_NOPTS_VALUE){
1519 pos_min = s->data_offset;
1520 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1521 if (ts_min == AV_NOPTS_VALUE)
1525 if(ts_max == AV_NOPTS_VALUE){
1527 filesize = avio_size(s->pb);
1528 pos_max = filesize - 1;
1531 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1533 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1534 if (ts_max == AV_NOPTS_VALUE)
1538 int64_t tmp_pos= pos_max + 1;
1539 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1540 if(tmp_ts == AV_NOPTS_VALUE)
1544 if(tmp_pos >= filesize)
1550 if(ts_min > ts_max){
1552 }else if(ts_min == ts_max){
1557 while (pos_min < pos_limit) {
1558 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1559 pos_min, pos_max, ts_min, ts_max);
1560 assert(pos_limit <= pos_max);
1563 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1564 // interpolate position (better than dichotomy)
1565 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1566 + pos_min - approximate_keyframe_distance;
1567 }else if(no_change==1){
1568 // bisection, if interpolation failed to change min or max pos last time
1569 pos = (pos_min + pos_limit)>>1;
1571 /* linear search if bisection failed, can only happen if there
1572 are very few or no keyframes between min/max */
1577 else if(pos > pos_limit)
1581 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1586 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1587 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1588 pos_limit, start_pos, no_change);
1589 if(ts == AV_NOPTS_VALUE){
1590 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1593 assert(ts != AV_NOPTS_VALUE);
1594 if (target_ts <= ts) {
1595 pos_limit = start_pos - 1;
1599 if (target_ts >= ts) {
1605 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1606 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1608 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1610 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1611 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1612 pos, ts_min, target_ts, ts_max);
1617 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1618 int64_t pos_min, pos_max;
1620 pos_min = s->data_offset;
1621 pos_max = avio_size(s->pb) - 1;
1623 if (pos < pos_min) pos= pos_min;
1624 else if(pos > pos_max) pos= pos_max;
1626 avio_seek(s->pb, pos, SEEK_SET);
1631 static int seek_frame_generic(AVFormatContext *s,
1632 int stream_index, int64_t timestamp, int flags)
1639 st = s->streams[stream_index];
1641 index = av_index_search_timestamp(st, timestamp, flags);
1643 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1646 if(index < 0 || index==st->nb_index_entries-1){
1649 if(st->nb_index_entries){
1650 assert(st->index_entries);
1651 ie= &st->index_entries[st->nb_index_entries-1];
1652 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1654 ff_update_cur_dts(s, st, ie->timestamp);
1656 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1662 read_status = av_read_frame(s, &pkt);
1663 } while (read_status == AVERROR(EAGAIN));
1664 if (read_status < 0)
1666 av_free_packet(&pkt);
1667 if(stream_index == pkt.stream_index){
1668 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1672 index = av_index_search_timestamp(st, timestamp, flags);
1677 ff_read_frame_flush(s);
1678 if (s->iformat->read_seek){
1679 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1682 ie = &st->index_entries[index];
1683 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1685 ff_update_cur_dts(s, st, ie->timestamp);
1690 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1691 int64_t timestamp, int flags)
1696 if (flags & AVSEEK_FLAG_BYTE) {
1697 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1699 ff_read_frame_flush(s);
1700 return seek_frame_byte(s, stream_index, timestamp, flags);
1703 if(stream_index < 0){
1704 stream_index= av_find_default_stream_index(s);
1705 if(stream_index < 0)
1708 st= s->streams[stream_index];
1709 /* timestamp for default must be expressed in AV_TIME_BASE units */
1710 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1713 /* first, we try the format specific seek */
1714 if (s->iformat->read_seek) {
1715 ff_read_frame_flush(s);
1716 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1723 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1724 ff_read_frame_flush(s);
1725 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1726 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1727 ff_read_frame_flush(s);
1728 return seek_frame_generic(s, stream_index, timestamp, flags);
1734 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1736 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1739 ret = queue_attached_pictures(s);
1744 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1746 if(min_ts > ts || max_ts < ts)
1749 if (s->iformat->read_seek2) {
1751 ff_read_frame_flush(s);
1752 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1755 ret = queue_attached_pictures(s);
1759 if(s->iformat->read_timestamp){
1760 //try to seek via read_timestamp()
1763 //Fallback to old API if new is not implemented but old is
1764 //Note the old has somewat different sematics
1765 if(s->iformat->read_seek || 1)
1766 return av_seek_frame(s, stream_index, ts, flags | ((uint64_t)ts - min_ts > (uint64_t)max_ts - ts ? AVSEEK_FLAG_BACKWARD : 0));
1768 // try some generic seek like seek_frame_generic() but with new ts semantics
1771 /*******************************************************/
1774 * Return TRUE if the stream has accurate duration in any stream.
1776 * @return TRUE if the stream has accurate duration for at least one component.
1778 static int has_duration(AVFormatContext *ic)
1783 for(i = 0;i < ic->nb_streams; i++) {
1784 st = ic->streams[i];
1785 if (st->duration != AV_NOPTS_VALUE)
1788 if (ic->duration != AV_NOPTS_VALUE)
1794 * Estimate the stream timings from the one of each components.
1796 * Also computes the global bitrate if possible.
1798 static void update_stream_timings(AVFormatContext *ic)
1800 int64_t start_time, start_time1, end_time, end_time1;
1801 int64_t duration, duration1, filesize;
1805 start_time = INT64_MAX;
1806 end_time = INT64_MIN;
1807 duration = INT64_MIN;
1808 for(i = 0;i < ic->nb_streams; i++) {
1809 st = ic->streams[i];
1810 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1811 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1812 start_time = FFMIN(start_time, start_time1);
1813 if (st->duration != AV_NOPTS_VALUE) {
1814 end_time1 = start_time1
1815 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1816 end_time = FFMAX(end_time, end_time1);
1819 if (st->duration != AV_NOPTS_VALUE) {
1820 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1821 duration = FFMAX(duration, duration1);
1824 if (start_time != INT64_MAX) {
1825 ic->start_time = start_time;
1826 if (end_time != INT64_MIN)
1827 duration = FFMAX(duration, end_time - start_time);
1829 if (duration != INT64_MIN) {
1830 ic->duration = duration;
1831 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1832 /* compute the bitrate */
1833 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1834 (double)ic->duration;
1839 static void fill_all_stream_timings(AVFormatContext *ic)
1844 update_stream_timings(ic);
1845 for(i = 0;i < ic->nb_streams; i++) {
1846 st = ic->streams[i];
1847 if (st->start_time == AV_NOPTS_VALUE) {
1848 if(ic->start_time != AV_NOPTS_VALUE)
1849 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1850 if(ic->duration != AV_NOPTS_VALUE)
1851 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1856 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1858 int64_t filesize, duration;
1862 /* if bit_rate is already set, we believe it */
1863 if (ic->bit_rate <= 0) {
1865 for(i=0;i<ic->nb_streams;i++) {
1866 st = ic->streams[i];
1867 if (st->codec->bit_rate > 0)
1868 bit_rate += st->codec->bit_rate;
1870 ic->bit_rate = bit_rate;
1873 /* if duration is already set, we believe it */
1874 if (ic->duration == AV_NOPTS_VALUE &&
1875 ic->bit_rate != 0) {
1876 filesize = ic->pb ? avio_size(ic->pb) : 0;
1878 for(i = 0; i < ic->nb_streams; i++) {
1879 st = ic->streams[i];
1880 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1881 if (st->duration == AV_NOPTS_VALUE)
1882 st->duration = duration;
1888 #define DURATION_MAX_READ_SIZE 250000
1889 #define DURATION_MAX_RETRY 3
1891 /* only usable for MPEG-PS streams */
1892 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1894 AVPacket pkt1, *pkt = &pkt1;
1896 int read_size, i, ret;
1898 int64_t filesize, offset, duration;
1901 /* flush packet queue */
1902 flush_packet_queue(ic);
1904 for (i=0; i<ic->nb_streams; i++) {
1905 st = ic->streams[i];
1906 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1907 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1910 av_parser_close(st->parser);
1915 /* estimate the end time (duration) */
1916 /* XXX: may need to support wrapping */
1917 filesize = ic->pb ? avio_size(ic->pb) : 0;
1918 end_time = AV_NOPTS_VALUE;
1920 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1924 avio_seek(ic->pb, offset, SEEK_SET);
1927 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1931 ret = ff_read_packet(ic, pkt);
1932 } while(ret == AVERROR(EAGAIN));
1935 read_size += pkt->size;
1936 st = ic->streams[pkt->stream_index];
1937 if (pkt->pts != AV_NOPTS_VALUE &&
1938 (st->start_time != AV_NOPTS_VALUE ||
1939 st->first_dts != AV_NOPTS_VALUE)) {
1940 duration = end_time = pkt->pts;
1941 if (st->start_time != AV_NOPTS_VALUE)
1942 duration -= st->start_time;
1944 duration -= st->first_dts;
1946 duration += 1LL<<st->pts_wrap_bits;
1948 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1949 st->duration = duration;
1952 av_free_packet(pkt);
1954 }while( end_time==AV_NOPTS_VALUE
1955 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1956 && ++retry <= DURATION_MAX_RETRY);
1958 fill_all_stream_timings(ic);
1960 avio_seek(ic->pb, old_offset, SEEK_SET);
1961 for (i=0; i<ic->nb_streams; i++) {
1963 st->cur_dts= st->first_dts;
1964 st->last_IP_pts = AV_NOPTS_VALUE;
1965 st->reference_dts = AV_NOPTS_VALUE;
1969 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1973 /* get the file size, if possible */
1974 if (ic->iformat->flags & AVFMT_NOFILE) {
1977 file_size = avio_size(ic->pb);
1978 file_size = FFMAX(0, file_size);
1981 if ((!strcmp(ic->iformat->name, "mpeg") ||
1982 !strcmp(ic->iformat->name, "mpegts")) &&
1983 file_size && ic->pb->seekable) {
1984 /* get accurate estimate from the PTSes */
1985 estimate_timings_from_pts(ic, old_offset);
1986 } else if (has_duration(ic)) {
1987 /* at least one component has timings - we use them for all
1989 fill_all_stream_timings(ic);
1991 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1992 /* less precise: use bitrate info */
1993 estimate_timings_from_bit_rate(ic);
1995 update_stream_timings(ic);
1999 AVStream av_unused *st;
2000 for(i = 0;i < ic->nb_streams; i++) {
2001 st = ic->streams[i];
2002 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2003 (double) st->start_time / AV_TIME_BASE,
2004 (double) st->duration / AV_TIME_BASE);
2006 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2007 (double) ic->start_time / AV_TIME_BASE,
2008 (double) ic->duration / AV_TIME_BASE,
2009 ic->bit_rate / 1000);
2013 static int has_codec_parameters(AVStream *st)
2015 AVCodecContext *avctx = st->codec;
2017 switch (avctx->codec_type) {
2018 case AVMEDIA_TYPE_AUDIO:
2019 val = avctx->sample_rate && avctx->channels;
2020 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2023 case AVMEDIA_TYPE_VIDEO:
2025 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2032 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2035 static int has_decode_delay_been_guessed(AVStream *st)
2037 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2038 st->info->nb_decoded_frames >= 6;
2041 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2042 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2044 const AVCodec *codec;
2045 int got_picture = 1, ret = 0;
2046 AVFrame *frame = avcodec_alloc_frame();
2047 AVPacket pkt = *avpkt;
2050 return AVERROR(ENOMEM);
2052 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2053 AVDictionary *thread_opt = NULL;
2055 codec = st->codec->codec ? st->codec->codec :
2056 avcodec_find_decoder(st->codec->codec_id);
2059 st->info->found_decoder = -1;
2064 /* force thread count to 1 since the h264 decoder will not extract SPS
2065 * and PPS to extradata during multi-threaded decoding */
2066 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2067 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2069 av_dict_free(&thread_opt);
2071 st->info->found_decoder = -1;
2074 st->info->found_decoder = 1;
2075 } else if (!st->info->found_decoder)
2076 st->info->found_decoder = 1;
2078 if (st->info->found_decoder < 0) {
2083 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2085 (!has_codec_parameters(st) ||
2086 !has_decode_delay_been_guessed(st) ||
2087 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2089 avcodec_get_frame_defaults(frame);
2090 switch(st->codec->codec_type) {
2091 case AVMEDIA_TYPE_VIDEO:
2092 ret = avcodec_decode_video2(st->codec, frame,
2093 &got_picture, &pkt);
2095 case AVMEDIA_TYPE_AUDIO:
2096 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2103 st->info->nb_decoded_frames++;
2111 avcodec_free_frame(&frame);
2115 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2117 while (tags->id != AV_CODEC_ID_NONE) {
2125 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2128 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2129 if(tag == tags[i].tag)
2132 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2133 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2136 return AV_CODEC_ID_NONE;
2139 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags)
2143 case 32: return be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
2144 case 64: return be ? AV_CODEC_ID_PCM_F64BE : AV_CODEC_ID_PCM_F64LE;
2145 default: return AV_CODEC_ID_NONE;
2149 if (sflags & (1 << (bps - 1))) {
2151 case 1: return AV_CODEC_ID_PCM_S8;
2152 case 2: return be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
2153 case 3: return be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2154 case 4: return be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2155 default: return AV_CODEC_ID_NONE;
2159 case 1: return AV_CODEC_ID_PCM_U8;
2160 case 2: return be ? AV_CODEC_ID_PCM_U16BE : AV_CODEC_ID_PCM_U16LE;
2161 case 3: return be ? AV_CODEC_ID_PCM_U24BE : AV_CODEC_ID_PCM_U24LE;
2162 case 4: return be ? AV_CODEC_ID_PCM_U32BE : AV_CODEC_ID_PCM_U32LE;
2163 default: return AV_CODEC_ID_NONE;
2169 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2172 for(i=0; tags && tags[i]; i++){
2173 int tag= ff_codec_get_tag(tags[i], id);
2179 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2182 for(i=0; tags && tags[i]; i++){
2183 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2184 if(id!=AV_CODEC_ID_NONE) return id;
2186 return AV_CODEC_ID_NONE;
2189 static void compute_chapters_end(AVFormatContext *s)
2192 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2194 for (i = 0; i < s->nb_chapters; i++)
2195 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2196 AVChapter *ch = s->chapters[i];
2197 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2200 for (j = 0; j < s->nb_chapters; j++) {
2201 AVChapter *ch1 = s->chapters[j];
2202 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2203 if (j != i && next_start > ch->start && next_start < end)
2206 ch->end = (end == INT64_MAX) ? ch->start : end;
2210 static int get_std_framerate(int i){
2211 if(i<60*12) return i*1001;
2212 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2216 * Is the time base unreliable.
2217 * This is a heuristic to balance between quick acceptance of the values in
2218 * the headers vs. some extra checks.
2219 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2220 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2221 * And there are "variable" fps files this needs to detect as well.
2223 static int tb_unreliable(AVCodecContext *c){
2224 if( c->time_base.den >= 101L*c->time_base.num
2225 || c->time_base.den < 5L*c->time_base.num
2226 /* || c->codec_tag == AV_RL32("DIVX")
2227 || c->codec_tag == AV_RL32("XVID")*/
2228 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2229 || c->codec_id == AV_CODEC_ID_H264
2235 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2237 int i, count, ret, read_size, j;
2239 AVPacket pkt1, *pkt;
2240 int64_t old_offset = avio_tell(ic->pb);
2241 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2243 for(i=0;i<ic->nb_streams;i++) {
2244 const AVCodec *codec;
2245 AVDictionary *thread_opt = NULL;
2246 st = ic->streams[i];
2248 //only for the split stuff
2249 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2250 st->parser = av_parser_init(st->codec->codec_id);
2251 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2252 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2255 codec = st->codec->codec ? st->codec->codec :
2256 avcodec_find_decoder(st->codec->codec_id);
2258 /* force thread count to 1 since the h264 decoder will not extract SPS
2259 * and PPS to extradata during multi-threaded decoding */
2260 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2262 /* Ensure that subtitle_header is properly set. */
2263 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2264 && codec && !st->codec->codec)
2265 avcodec_open2(st->codec, codec, options ? &options[i]
2268 //try to just open decoders, in case this is enough to get parameters
2269 if (!has_codec_parameters(st)) {
2270 if (codec && !st->codec->codec)
2271 avcodec_open2(st->codec, codec, options ? &options[i]
2275 av_dict_free(&thread_opt);
2278 for (i=0; i<ic->nb_streams; i++) {
2279 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2280 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2286 if (ff_check_interrupt(&ic->interrupt_callback)){
2288 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2292 /* check if one codec still needs to be handled */
2293 for(i=0;i<ic->nb_streams;i++) {
2294 int fps_analyze_framecount = 20;
2296 st = ic->streams[i];
2297 if (!has_codec_parameters(st))
2299 /* if the timebase is coarse (like the usual millisecond precision
2300 of mkv), we need to analyze more frames to reliably arrive at
2302 if (av_q2d(st->time_base) > 0.0005)
2303 fps_analyze_framecount *= 2;
2304 if (ic->fps_probe_size >= 0)
2305 fps_analyze_framecount = ic->fps_probe_size;
2306 /* variable fps and no guess at the real fps */
2307 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2308 && st->codec_info_nb_frames < fps_analyze_framecount
2309 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2311 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2313 if (st->first_dts == AV_NOPTS_VALUE &&
2314 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2315 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2318 if (i == ic->nb_streams) {
2319 /* NOTE: if the format has no header, then we need to read
2320 some packets to get most of the streams, so we cannot
2322 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2323 /* if we found the info for all the codecs, we can stop */
2325 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2329 /* we did not get all the codec info, but we read too much data */
2330 if (read_size >= ic->probesize) {
2332 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2336 /* NOTE: a new stream can be added there if no header in file
2337 (AVFMTCTX_NOHEADER) */
2338 ret = read_frame_internal(ic, &pkt1);
2339 if (ret == AVERROR(EAGAIN))
2344 AVPacket empty_pkt = { 0 };
2346 av_init_packet(&empty_pkt);
2348 ret = -1; /* we could not have all the codec parameters before EOF */
2349 for(i=0;i<ic->nb_streams;i++) {
2350 st = ic->streams[i];
2352 /* flush the decoders */
2353 if (st->info->found_decoder == 1) {
2355 err = try_decode_frame(st, &empty_pkt,
2356 (options && i < orig_nb_streams) ?
2357 &options[i] : NULL);
2358 } while (err > 0 && !has_codec_parameters(st));
2362 av_log(ic, AV_LOG_WARNING,
2363 "decoding for stream %d failed\n", st->index);
2364 } else if (!has_codec_parameters(st)) {
2366 avcodec_string(buf, sizeof(buf), st->codec, 0);
2367 av_log(ic, AV_LOG_WARNING,
2368 "Could not find codec parameters (%s)\n", buf);
2376 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2379 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2380 &ic->packet_buffer_end);
2381 if ((ret = av_dup_packet(pkt)) < 0)
2382 goto find_stream_info_err;
2385 read_size += pkt->size;
2387 st = ic->streams[pkt->stream_index];
2388 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2389 /* check for non-increasing dts */
2390 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2391 st->info->fps_last_dts >= pkt->dts) {
2392 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2393 "packet %d with DTS %"PRId64", packet %d with DTS "
2394 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2395 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2396 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2398 /* check for a discontinuity in dts - if the difference in dts
2399 * is more than 1000 times the average packet duration in the sequence,
2400 * we treat it as a discontinuity */
2401 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2402 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2403 (pkt->dts - st->info->fps_last_dts) / 1000 >
2404 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2405 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2406 "packet %d with DTS %"PRId64", packet %d with DTS "
2407 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2408 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2409 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2412 /* update stored dts values */
2413 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2414 st->info->fps_first_dts = pkt->dts;
2415 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2417 st->info->fps_last_dts = pkt->dts;
2418 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2420 /* check max_analyze_duration */
2421 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2422 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2423 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2427 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2428 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2429 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2430 st->codec->extradata_size= i;
2431 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2432 if (!st->codec->extradata)
2433 return AVERROR(ENOMEM);
2434 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2435 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2439 /* if still no information, we try to open the codec and to
2440 decompress the frame. We try to avoid that in most cases as
2441 it takes longer and uses more memory. For MPEG-4, we need to
2442 decompress for QuickTime.
2444 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2445 least one frame of codec data, this makes sure the codec initializes
2446 the channel configuration and does not only trust the values from the container.
2448 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2450 st->codec_info_nb_frames++;
2454 // close codecs which were opened in try_decode_frame()
2455 for(i=0;i<ic->nb_streams;i++) {
2456 st = ic->streams[i];
2457 avcodec_close(st->codec);
2459 for(i=0;i<ic->nb_streams;i++) {
2460 st = ic->streams[i];
2461 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2462 /* estimate average framerate if not set by demuxer */
2463 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2464 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2465 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2467 double best_error = 0.01;
2469 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2470 delta_packets*(int64_t)st->time_base.den,
2471 delta_dts*(int64_t)st->time_base.num, 60000);
2473 /* round guessed framerate to a "standard" framerate if it's
2474 * within 1% of the original estimate*/
2475 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2476 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2477 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2479 if (error < best_error) {
2481 best_fps = std_fps.num;
2485 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2486 best_fps, 12*1001, INT_MAX);
2489 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2490 if(!st->codec->bits_per_coded_sample)
2491 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2492 // set stream disposition based on audio service type
2493 switch (st->codec->audio_service_type) {
2494 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2495 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2496 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2497 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2498 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2499 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2500 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2501 st->disposition = AV_DISPOSITION_COMMENT; break;
2502 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2503 st->disposition = AV_DISPOSITION_KARAOKE; break;
2508 estimate_timings(ic, old_offset);
2510 compute_chapters_end(ic);
2512 find_stream_info_err:
2513 for (i=0; i < ic->nb_streams; i++) {
2514 if (ic->streams[i]->codec)
2515 ic->streams[i]->codec->thread_count = 0;
2516 av_freep(&ic->streams[i]->info);
2521 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2525 for (i = 0; i < ic->nb_programs; i++)
2526 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2527 if (ic->programs[i]->stream_index[j] == s)
2528 return ic->programs[i];
2532 int av_find_best_stream(AVFormatContext *ic,
2533 enum AVMediaType type,
2534 int wanted_stream_nb,
2536 AVCodec **decoder_ret,
2539 int i, nb_streams = ic->nb_streams;
2540 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2541 unsigned *program = NULL;
2542 AVCodec *decoder = NULL, *best_decoder = NULL;
2544 if (related_stream >= 0 && wanted_stream_nb < 0) {
2545 AVProgram *p = find_program_from_stream(ic, related_stream);
2547 program = p->stream_index;
2548 nb_streams = p->nb_stream_indexes;
2551 for (i = 0; i < nb_streams; i++) {
2552 int real_stream_index = program ? program[i] : i;
2553 AVStream *st = ic->streams[real_stream_index];
2554 AVCodecContext *avctx = st->codec;
2555 if (avctx->codec_type != type)
2557 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2559 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2562 decoder = avcodec_find_decoder(st->codec->codec_id);
2565 ret = AVERROR_DECODER_NOT_FOUND;
2569 if (best_count >= st->codec_info_nb_frames)
2571 best_count = st->codec_info_nb_frames;
2572 ret = real_stream_index;
2573 best_decoder = decoder;
2574 if (program && i == nb_streams - 1 && ret < 0) {
2576 nb_streams = ic->nb_streams;
2577 i = 0; /* no related stream found, try again with everything */
2581 *decoder_ret = best_decoder;
2585 /*******************************************************/
2587 int av_read_play(AVFormatContext *s)
2589 if (s->iformat->read_play)
2590 return s->iformat->read_play(s);
2592 return avio_pause(s->pb, 0);
2593 return AVERROR(ENOSYS);
2596 int av_read_pause(AVFormatContext *s)
2598 if (s->iformat->read_pause)
2599 return s->iformat->read_pause(s);
2601 return avio_pause(s->pb, 1);
2602 return AVERROR(ENOSYS);
2605 void avformat_free_context(AVFormatContext *s)
2611 if (s->iformat && s->iformat->priv_class && s->priv_data)
2612 av_opt_free(s->priv_data);
2614 for(i=0;i<s->nb_streams;i++) {
2615 /* free all data in a stream component */
2618 av_parser_close(st->parser);
2620 if (st->attached_pic.data)
2621 av_free_packet(&st->attached_pic);
2622 av_dict_free(&st->metadata);
2623 av_free(st->index_entries);
2624 av_free(st->codec->extradata);
2625 av_free(st->codec->subtitle_header);
2627 av_free(st->priv_data);
2631 for(i=s->nb_programs-1; i>=0; i--) {
2632 av_dict_free(&s->programs[i]->metadata);
2633 av_freep(&s->programs[i]->stream_index);
2634 av_freep(&s->programs[i]);
2636 av_freep(&s->programs);
2637 av_freep(&s->priv_data);
2638 while(s->nb_chapters--) {
2639 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2640 av_free(s->chapters[s->nb_chapters]);
2642 av_freep(&s->chapters);
2643 av_dict_free(&s->metadata);
2644 av_freep(&s->streams);
2648 void avformat_close_input(AVFormatContext **ps)
2650 AVFormatContext *s = *ps;
2651 AVIOContext *pb = s->pb;
2653 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2654 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2657 flush_packet_queue(s);
2660 if (s->iformat->read_close)
2661 s->iformat->read_close(s);
2664 avformat_free_context(s);
2671 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2677 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2679 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2682 s->streams = streams;
2684 st = av_mallocz(sizeof(AVStream));
2687 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2692 st->codec = avcodec_alloc_context3(c);
2694 /* no default bitrate if decoding */
2695 st->codec->bit_rate = 0;
2697 st->index = s->nb_streams;
2698 st->start_time = AV_NOPTS_VALUE;
2699 st->duration = AV_NOPTS_VALUE;
2700 /* we set the current DTS to 0 so that formats without any timestamps
2701 but durations get some timestamps, formats with some unknown
2702 timestamps have their first few packets buffered and the
2703 timestamps corrected before they are returned to the user */
2705 st->first_dts = AV_NOPTS_VALUE;
2706 st->probe_packets = MAX_PROBE_PACKETS;
2708 /* default pts setting is MPEG-like */
2709 avpriv_set_pts_info(st, 33, 1, 90000);
2710 st->last_IP_pts = AV_NOPTS_VALUE;
2711 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2712 st->pts_buffer[i]= AV_NOPTS_VALUE;
2713 st->reference_dts = AV_NOPTS_VALUE;
2715 st->sample_aspect_ratio = (AVRational){0,1};
2717 st->info->fps_first_dts = AV_NOPTS_VALUE;
2718 st->info->fps_last_dts = AV_NOPTS_VALUE;
2720 s->streams[s->nb_streams++] = st;
2724 AVProgram *av_new_program(AVFormatContext *ac, int id)
2726 AVProgram *program=NULL;
2729 av_dlog(ac, "new_program: id=0x%04x\n", id);
2731 for(i=0; i<ac->nb_programs; i++)
2732 if(ac->programs[i]->id == id)
2733 program = ac->programs[i];
2736 program = av_mallocz(sizeof(AVProgram));
2739 dynarray_add(&ac->programs, &ac->nb_programs, program);
2740 program->discard = AVDISCARD_NONE;
2747 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2749 AVChapter *chapter = NULL;
2752 for(i=0; i<s->nb_chapters; i++)
2753 if(s->chapters[i]->id == id)
2754 chapter = s->chapters[i];
2757 chapter= av_mallocz(sizeof(AVChapter));
2760 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2762 av_dict_set(&chapter->metadata, "title", title, 0);
2764 chapter->time_base= time_base;
2765 chapter->start = start;
2771 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2774 AVProgram *program=NULL;
2777 if (idx >= ac->nb_streams) {
2778 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2782 for(i=0; i<ac->nb_programs; i++){
2783 if(ac->programs[i]->id != progid)
2785 program = ac->programs[i];
2786 for(j=0; j<program->nb_stream_indexes; j++)
2787 if(program->stream_index[j] == idx)
2790 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2793 program->stream_index = tmp;
2794 program->stream_index[program->nb_stream_indexes++] = idx;
2799 static void print_fps(double d, const char *postfix){
2800 uint64_t v= lrintf(d*100);
2801 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2802 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2803 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2806 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2808 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2809 AVDictionaryEntry *tag=NULL;
2811 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2812 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2813 if(strcmp("language", tag->key))
2814 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2819 /* "user interface" functions */
2820 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2823 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2824 AVStream *st = ic->streams[i];
2825 int g = av_gcd(st->time_base.num, st->time_base.den);
2826 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2827 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2828 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2829 /* the pid is an important information, so we display it */
2830 /* XXX: add a generic system */
2831 if (flags & AVFMT_SHOW_IDS)
2832 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2834 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2835 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2836 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2837 if (st->sample_aspect_ratio.num && // default
2838 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2839 AVRational display_aspect_ratio;
2840 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2841 st->codec->width*st->sample_aspect_ratio.num,
2842 st->codec->height*st->sample_aspect_ratio.den,
2844 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2845 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2846 display_aspect_ratio.num, display_aspect_ratio.den);
2848 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2849 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2850 print_fps(av_q2d(st->avg_frame_rate), "fps");
2851 if(st->time_base.den && st->time_base.num)
2852 print_fps(1/av_q2d(st->time_base), "tbn");
2853 if(st->codec->time_base.den && st->codec->time_base.num)
2854 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2856 if (st->disposition & AV_DISPOSITION_DEFAULT)
2857 av_log(NULL, AV_LOG_INFO, " (default)");
2858 if (st->disposition & AV_DISPOSITION_DUB)
2859 av_log(NULL, AV_LOG_INFO, " (dub)");
2860 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2861 av_log(NULL, AV_LOG_INFO, " (original)");
2862 if (st->disposition & AV_DISPOSITION_COMMENT)
2863 av_log(NULL, AV_LOG_INFO, " (comment)");
2864 if (st->disposition & AV_DISPOSITION_LYRICS)
2865 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2866 if (st->disposition & AV_DISPOSITION_KARAOKE)
2867 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2868 if (st->disposition & AV_DISPOSITION_FORCED)
2869 av_log(NULL, AV_LOG_INFO, " (forced)");
2870 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2871 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2872 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2873 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2874 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2875 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2876 av_log(NULL, AV_LOG_INFO, "\n");
2877 dump_metadata(NULL, st->metadata, " ");
2880 void av_dump_format(AVFormatContext *ic,
2886 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2887 if (ic->nb_streams && !printed)
2890 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2891 is_output ? "Output" : "Input",
2893 is_output ? ic->oformat->name : ic->iformat->name,
2894 is_output ? "to" : "from", url);
2895 dump_metadata(NULL, ic->metadata, " ");
2897 av_log(NULL, AV_LOG_INFO, " Duration: ");
2898 if (ic->duration != AV_NOPTS_VALUE) {
2899 int hours, mins, secs, us;
2900 secs = ic->duration / AV_TIME_BASE;
2901 us = ic->duration % AV_TIME_BASE;
2906 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2907 (100 * us) / AV_TIME_BASE);
2909 av_log(NULL, AV_LOG_INFO, "N/A");
2911 if (ic->start_time != AV_NOPTS_VALUE) {
2913 av_log(NULL, AV_LOG_INFO, ", start: ");
2914 secs = ic->start_time / AV_TIME_BASE;
2915 us = abs(ic->start_time % AV_TIME_BASE);
2916 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2917 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2919 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2921 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2923 av_log(NULL, AV_LOG_INFO, "N/A");
2925 av_log(NULL, AV_LOG_INFO, "\n");
2927 for (i = 0; i < ic->nb_chapters; i++) {
2928 AVChapter *ch = ic->chapters[i];
2929 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2930 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2931 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2933 dump_metadata(NULL, ch->metadata, " ");
2935 if(ic->nb_programs) {
2936 int j, k, total = 0;
2937 for(j=0; j<ic->nb_programs; j++) {
2938 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2940 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2941 name ? name->value : "");
2942 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2943 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2944 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2945 printed[ic->programs[j]->stream_index[k]] = 1;
2947 total += ic->programs[j]->nb_stream_indexes;
2949 if (total < ic->nb_streams)
2950 av_log(NULL, AV_LOG_INFO, " No Program\n");
2952 for(i=0;i<ic->nb_streams;i++)
2954 dump_stream_format(ic, i, index, is_output);
2959 uint64_t ff_ntp_time(void)
2961 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
2964 int av_get_frame_filename(char *buf, int buf_size,
2965 const char *path, int number)
2968 char *q, buf1[20], c;
2969 int nd, len, percentd_found;
2981 while (av_isdigit(*p)) {
2982 nd = nd * 10 + *p++ - '0';
2985 } while (av_isdigit(c));
2994 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2996 if ((q - buf + len) > buf_size - 1)
2998 memcpy(q, buf1, len);
3006 if ((q - buf) < buf_size - 1)
3010 if (!percentd_found)
3019 static void hex_dump_internal(void *avcl, FILE *f, int level,
3020 const uint8_t *buf, int size)
3023 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3025 for(i=0;i<size;i+=16) {
3032 PRINT(" %02x", buf[i+j]);
3037 for(j=0;j<len;j++) {
3039 if (c < ' ' || c > '~')
3048 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3050 hex_dump_internal(NULL, f, 0, buf, size);
3053 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3055 hex_dump_internal(avcl, NULL, level, buf, size);
3058 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3060 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3061 PRINT("stream #%d:\n", pkt->stream_index);
3062 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3063 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3064 /* DTS is _always_ valid after av_read_frame() */
3066 if (pkt->dts == AV_NOPTS_VALUE)
3069 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3070 /* PTS may not be known if B-frames are present. */
3072 if (pkt->pts == AV_NOPTS_VALUE)
3075 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3077 PRINT(" size=%d\n", pkt->size);
3080 av_hex_dump(f, pkt->data, pkt->size);
3083 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3085 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3088 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3091 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3094 void av_url_split(char *proto, int proto_size,
3095 char *authorization, int authorization_size,
3096 char *hostname, int hostname_size,
3098 char *path, int path_size,
3101 const char *p, *ls, *at, *col, *brk;
3103 if (port_ptr) *port_ptr = -1;
3104 if (proto_size > 0) proto[0] = 0;
3105 if (authorization_size > 0) authorization[0] = 0;
3106 if (hostname_size > 0) hostname[0] = 0;
3107 if (path_size > 0) path[0] = 0;
3109 /* parse protocol */
3110 if ((p = strchr(url, ':'))) {
3111 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3116 /* no protocol means plain filename */
3117 av_strlcpy(path, url, path_size);
3121 /* separate path from hostname */
3122 ls = strchr(p, '/');
3124 ls = strchr(p, '?');
3126 av_strlcpy(path, ls, path_size);
3128 ls = &p[strlen(p)]; // XXX
3130 /* the rest is hostname, use that to parse auth/port */
3132 /* authorization (user[:pass]@hostname) */
3133 if ((at = strchr(p, '@')) && at < ls) {
3134 av_strlcpy(authorization, p,
3135 FFMIN(authorization_size, at + 1 - p));
3136 p = at + 1; /* skip '@' */
3139 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3141 av_strlcpy(hostname, p + 1,
3142 FFMIN(hostname_size, brk - p));
3143 if (brk[1] == ':' && port_ptr)
3144 *port_ptr = atoi(brk + 2);
3145 } else if ((col = strchr(p, ':')) && col < ls) {
3146 av_strlcpy(hostname, p,
3147 FFMIN(col + 1 - p, hostname_size));
3148 if (port_ptr) *port_ptr = atoi(col + 1);
3150 av_strlcpy(hostname, p,
3151 FFMIN(ls + 1 - p, hostname_size));
3155 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3158 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3161 'C', 'D', 'E', 'F' };
3162 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3165 'c', 'd', 'e', 'f' };
3166 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3168 for(i = 0; i < s; i++) {
3169 buff[i * 2] = hex_table[src[i] >> 4];
3170 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3176 int ff_hex_to_data(uint8_t *data, const char *p)
3183 p += strspn(p, SPACE_CHARS);
3186 c = av_toupper((unsigned char) *p++);
3187 if (c >= '0' && c <= '9')
3189 else if (c >= 'A' && c <= 'F')
3204 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3205 unsigned int pts_num, unsigned int pts_den)
3208 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3209 if(new_tb.num != pts_num)
3210 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3212 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3214 if(new_tb.num <= 0 || new_tb.den <= 0) {
3215 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3218 s->time_base = new_tb;
3219 s->pts_wrap_bits = pts_wrap_bits;
3222 int ff_url_join(char *str, int size, const char *proto,
3223 const char *authorization, const char *hostname,
3224 int port, const char *fmt, ...)
3227 struct addrinfo hints = { 0 }, *ai;
3232 av_strlcatf(str, size, "%s://", proto);
3233 if (authorization && authorization[0])
3234 av_strlcatf(str, size, "%s@", authorization);
3235 #if CONFIG_NETWORK && defined(AF_INET6)
3236 /* Determine if hostname is a numerical IPv6 address,
3237 * properly escape it within [] in that case. */
3238 hints.ai_flags = AI_NUMERICHOST;
3239 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3240 if (ai->ai_family == AF_INET6) {
3241 av_strlcat(str, "[", size);
3242 av_strlcat(str, hostname, size);
3243 av_strlcat(str, "]", size);
3245 av_strlcat(str, hostname, size);
3250 /* Not an IPv6 address, just output the plain string. */
3251 av_strlcat(str, hostname, size);
3254 av_strlcatf(str, size, ":%d", port);
3257 int len = strlen(str);
3260 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3266 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3267 AVFormatContext *src)
3272 local_pkt.stream_index = dst_stream;
3273 if (pkt->pts != AV_NOPTS_VALUE)
3274 local_pkt.pts = av_rescale_q(pkt->pts,
3275 src->streams[pkt->stream_index]->time_base,
3276 dst->streams[dst_stream]->time_base);
3277 if (pkt->dts != AV_NOPTS_VALUE)
3278 local_pkt.dts = av_rescale_q(pkt->dts,
3279 src->streams[pkt->stream_index]->time_base,
3280 dst->streams[dst_stream]->time_base);
3281 return av_write_frame(dst, &local_pkt);
3284 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3287 const char *ptr = str;
3289 /* Parse key=value pairs. */
3292 char *dest = NULL, *dest_end;
3293 int key_len, dest_len = 0;
3295 /* Skip whitespace and potential commas. */
3296 while (*ptr && (av_isspace(*ptr) || *ptr == ','))
3303 if (!(ptr = strchr(key, '=')))
3306 key_len = ptr - key;
3308 callback_get_buf(context, key, key_len, &dest, &dest_len);
3309 dest_end = dest + dest_len - 1;
3313 while (*ptr && *ptr != '\"') {
3317 if (dest && dest < dest_end)
3321 if (dest && dest < dest_end)
3329 for (; *ptr && !(av_isspace(*ptr) || *ptr == ','); ptr++)
3330 if (dest && dest < dest_end)
3338 int ff_find_stream_index(AVFormatContext *s, int id)
3341 for (i = 0; i < s->nb_streams; i++) {
3342 if (s->streams[i]->id == id)
3348 void ff_make_absolute_url(char *buf, int size, const char *base,
3351 char *sep, *path_query;
3352 /* Absolute path, relative to the current server */
3353 if (base && strstr(base, "://") && rel[0] == '/') {
3355 av_strlcpy(buf, base, size);
3356 sep = strstr(buf, "://");
3358 /* Take scheme from base url */
3359 if (rel[1] == '/') {
3362 /* Take scheme and host from base url */
3364 sep = strchr(sep, '/');
3369 av_strlcat(buf, rel, size);
3372 /* If rel actually is an absolute url, just copy it */
3373 if (!base || strstr(rel, "://") || rel[0] == '/') {
3374 av_strlcpy(buf, rel, size);
3378 av_strlcpy(buf, base, size);
3380 /* Strip off any query string from base */
3381 path_query = strchr(buf, '?');
3382 if (path_query != NULL)
3385 /* Is relative path just a new query part? */
3386 if (rel[0] == '?') {
3387 av_strlcat(buf, rel, size);
3391 /* Remove the file name from the base url */
3392 sep = strrchr(buf, '/');
3397 while (av_strstart(rel, "../", NULL) && sep) {
3398 /* Remove the path delimiter at the end */
3400 sep = strrchr(buf, '/');
3401 /* If the next directory name to pop off is "..", break here */
3402 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3403 /* Readd the slash we just removed */
3404 av_strlcat(buf, "/", size);
3407 /* Cut off the directory name */
3414 av_strlcat(buf, rel, size);
3417 int64_t ff_iso8601_to_unix_time(const char *datestr)
3420 struct tm time1 = {0}, time2 = {0};
3422 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3423 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3425 return av_timegm(&time2);
3427 return av_timegm(&time1);
3429 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3430 "the date string.\n");
3435 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3438 if (ofmt->query_codec)
3439 return ofmt->query_codec(codec_id, std_compliance);
3440 else if (ofmt->codec_tag)
3441 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3442 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3443 codec_id == ofmt->subtitle_codec)
3446 return AVERROR_PATCHWELCOME;
3449 int avformat_network_init(void)
3453 ff_network_inited_globally = 1;
3454 if ((ret = ff_network_init()) < 0)
3461 int avformat_network_deinit(void)
3470 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3471 uint64_t channel_layout, int32_t sample_rate,
3472 int32_t width, int32_t height)
3478 return AVERROR(EINVAL);
3481 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3483 if (channel_layout) {
3485 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3489 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3491 if (width || height) {
3493 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3495 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3497 return AVERROR(ENOMEM);
3498 bytestream_put_le32(&data, flags);
3500 bytestream_put_le32(&data, channels);
3502 bytestream_put_le64(&data, channel_layout);
3504 bytestream_put_le32(&data, sample_rate);
3505 if (width || height) {
3506 bytestream_put_le32(&data, width);
3507 bytestream_put_le32(&data, height);
3512 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3514 return ff_codec_bmp_tags;
3516 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3518 return ff_codec_wav_tags;
3521 static int match_host_pattern(const char *pattern, const char *hostname)
3524 if (!strcmp(pattern, "*"))
3526 // Skip a possible *. at the start of the pattern
3527 if (pattern[0] == '*')
3529 if (pattern[0] == '.')
3531 len_p = strlen(pattern);
3532 len_h = strlen(hostname);
3535 // Simply check if the end of hostname is equal to 'pattern'
3536 if (!strcmp(pattern, &hostname[len_h - len_p])) {
3538 return 1; // Exact match
3539 if (hostname[len_h - len_p - 1] == '.')
3540 return 1; // The matched substring is a domain and not just a substring of a domain
3545 int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
3553 buf = av_strdup(no_proxy);
3558 char *sep, *next = NULL;
3559 start += strspn(start, " ,");
3560 sep = start + strcspn(start, " ,");
3565 if (match_host_pattern(start, hostname)) {