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 *pnum = (*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.destruct = pkt->destruct;
1075 pkt->destruct = NULL;
1077 if ((ret = av_dup_packet(&out_pkt)) < 0)
1080 if (!add_to_pktbuf(&s->parse_queue, &out_pkt, &s->parse_queue_end)) {
1081 av_free_packet(&out_pkt);
1082 ret = AVERROR(ENOMEM);
1088 /* end of the stream => close and free the parser */
1089 if (pkt == &flush_pkt) {
1090 av_parser_close(st->parser);
1095 av_free_packet(pkt);
1099 static int read_from_packet_buffer(AVPacketList **pkt_buffer,
1100 AVPacketList **pkt_buffer_end,
1104 av_assert0(*pkt_buffer);
1107 *pkt_buffer = pktl->next;
1109 *pkt_buffer_end = NULL;
1114 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1116 int ret = 0, i, got_packet = 0;
1118 av_init_packet(pkt);
1120 while (!got_packet && !s->parse_queue) {
1124 /* read next packet */
1125 ret = ff_read_packet(s, &cur_pkt);
1127 if (ret == AVERROR(EAGAIN))
1129 /* flush the parsers */
1130 for(i = 0; i < s->nb_streams; i++) {
1132 if (st->parser && st->need_parsing)
1133 parse_packet(s, NULL, st->index);
1135 /* all remaining packets are now in parse_queue =>
1136 * really terminate parsing */
1140 st = s->streams[cur_pkt.stream_index];
1142 if (cur_pkt.pts != AV_NOPTS_VALUE &&
1143 cur_pkt.dts != AV_NOPTS_VALUE &&
1144 cur_pkt.pts < cur_pkt.dts) {
1145 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1146 cur_pkt.stream_index,
1151 if (s->debug & FF_FDEBUG_TS)
1152 av_log(s, AV_LOG_DEBUG, "ff_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1153 cur_pkt.stream_index,
1160 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1161 st->parser = av_parser_init(st->codec->codec_id);
1163 /* no parser available: just output the raw packets */
1164 st->need_parsing = AVSTREAM_PARSE_NONE;
1165 } else if(st->need_parsing == AVSTREAM_PARSE_HEADERS) {
1166 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1167 } else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE) {
1168 st->parser->flags |= PARSER_FLAG_ONCE;
1172 if (!st->need_parsing || !st->parser) {
1173 /* no parsing needed: we just output the packet as is */
1175 compute_pkt_fields(s, st, NULL, pkt);
1176 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1177 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1178 ff_reduce_index(s, st->index);
1179 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1182 } else if (st->discard < AVDISCARD_ALL) {
1183 if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)
1187 av_free_packet(&cur_pkt);
1191 if (!got_packet && s->parse_queue)
1192 ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);
1194 if(s->debug & FF_FDEBUG_TS)
1195 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1206 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1208 const int genpts = s->flags & AVFMT_FLAG_GENPTS;
1212 return s->packet_buffer ? read_from_packet_buffer(&s->packet_buffer,
1213 &s->packet_buffer_end,
1215 read_frame_internal(s, pkt);
1219 AVPacketList *pktl = s->packet_buffer;
1222 AVPacket *next_pkt = &pktl->pkt;
1224 if (next_pkt->dts != AV_NOPTS_VALUE) {
1225 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1226 while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {
1227 if (pktl->pkt.stream_index == next_pkt->stream_index &&
1228 (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&
1229 av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1230 next_pkt->pts = pktl->pkt.dts;
1234 pktl = s->packet_buffer;
1237 /* read packet from packet buffer, if there is data */
1238 if (!(next_pkt->pts == AV_NOPTS_VALUE &&
1239 next_pkt->dts != AV_NOPTS_VALUE && !eof))
1240 return read_from_packet_buffer(&s->packet_buffer,
1241 &s->packet_buffer_end, pkt);
1244 ret = read_frame_internal(s, pkt);
1246 if (pktl && ret != AVERROR(EAGAIN)) {
1253 if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1254 &s->packet_buffer_end)) < 0)
1255 return AVERROR(ENOMEM);
1259 /* XXX: suppress the packet queue */
1260 static void flush_packet_queue(AVFormatContext *s)
1262 free_packet_buffer(&s->parse_queue, &s->parse_queue_end);
1263 free_packet_buffer(&s->packet_buffer, &s->packet_buffer_end);
1264 free_packet_buffer(&s->raw_packet_buffer, &s->raw_packet_buffer_end);
1266 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1269 /*******************************************************/
1272 int av_find_default_stream_index(AVFormatContext *s)
1274 int first_audio_index = -1;
1278 if (s->nb_streams <= 0)
1280 for(i = 0; i < s->nb_streams; i++) {
1282 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1283 !(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
1286 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1287 first_audio_index = i;
1289 return first_audio_index >= 0 ? first_audio_index : 0;
1293 * Flush the frame reader.
1295 void ff_read_frame_flush(AVFormatContext *s)
1300 flush_packet_queue(s);
1302 /* for each stream, reset read state */
1303 for(i = 0; i < s->nb_streams; i++) {
1307 av_parser_close(st->parser);
1310 st->last_IP_pts = AV_NOPTS_VALUE;
1311 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1312 st->reference_dts = AV_NOPTS_VALUE;
1314 st->probe_packets = MAX_PROBE_PACKETS;
1316 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1317 st->pts_buffer[j]= AV_NOPTS_VALUE;
1321 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1325 for(i = 0; i < s->nb_streams; i++) {
1326 AVStream *st = s->streams[i];
1328 st->cur_dts = av_rescale(timestamp,
1329 st->time_base.den * (int64_t)ref_st->time_base.num,
1330 st->time_base.num * (int64_t)ref_st->time_base.den);
1334 void ff_reduce_index(AVFormatContext *s, int stream_index)
1336 AVStream *st= s->streams[stream_index];
1337 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1339 if((unsigned)st->nb_index_entries >= max_entries){
1341 for(i=0; 2*i<st->nb_index_entries; i++)
1342 st->index_entries[i]= st->index_entries[2*i];
1343 st->nb_index_entries= i;
1347 int ff_add_index_entry(AVIndexEntry **index_entries,
1348 int *nb_index_entries,
1349 unsigned int *index_entries_allocated_size,
1350 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1352 AVIndexEntry *entries, *ie;
1355 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1358 entries = av_fast_realloc(*index_entries,
1359 index_entries_allocated_size,
1360 (*nb_index_entries + 1) *
1361 sizeof(AVIndexEntry));
1365 *index_entries= entries;
1367 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1370 index= (*nb_index_entries)++;
1371 ie= &entries[index];
1372 assert(index==0 || ie[-1].timestamp < timestamp);
1374 ie= &entries[index];
1375 if(ie->timestamp != timestamp){
1376 if(ie->timestamp <= timestamp)
1378 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1379 (*nb_index_entries)++;
1380 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1381 distance= ie->min_distance;
1385 ie->timestamp = timestamp;
1386 ie->min_distance= distance;
1393 int av_add_index_entry(AVStream *st,
1394 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1396 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1397 &st->index_entries_allocated_size, pos,
1398 timestamp, size, distance, flags);
1401 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1402 int64_t wanted_timestamp, int flags)
1410 //optimize appending index entries at the end
1411 if(b && entries[b-1].timestamp < wanted_timestamp)
1416 timestamp = entries[m].timestamp;
1417 if(timestamp >= wanted_timestamp)
1419 if(timestamp <= wanted_timestamp)
1422 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1424 if(!(flags & AVSEEK_FLAG_ANY)){
1425 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1426 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1435 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1438 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1439 wanted_timestamp, flags);
1442 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1444 AVInputFormat *avif= s->iformat;
1445 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1446 int64_t ts_min, ts_max, ts;
1451 if (stream_index < 0)
1454 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1457 ts_min= AV_NOPTS_VALUE;
1458 pos_limit= -1; //gcc falsely says it may be uninitialized
1460 st= s->streams[stream_index];
1461 if(st->index_entries){
1464 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()
1465 index= FFMAX(index, 0);
1466 e= &st->index_entries[index];
1468 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1470 ts_min= e->timestamp;
1471 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1477 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1478 assert(index < st->nb_index_entries);
1480 e= &st->index_entries[index];
1481 assert(e->timestamp >= target_ts);
1483 ts_max= e->timestamp;
1484 pos_limit= pos_max - e->min_distance;
1485 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1486 pos_max,pos_limit, ts_max);
1490 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1495 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1498 ff_update_cur_dts(s, st, ts);
1503 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1504 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1505 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1506 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1509 int64_t start_pos, filesize;
1512 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1514 if(ts_min == AV_NOPTS_VALUE){
1515 pos_min = s->data_offset;
1516 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1517 if (ts_min == AV_NOPTS_VALUE)
1521 if(ts_max == AV_NOPTS_VALUE){
1523 filesize = avio_size(s->pb);
1524 pos_max = filesize - 1;
1527 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1529 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1530 if (ts_max == AV_NOPTS_VALUE)
1534 int64_t tmp_pos= pos_max + 1;
1535 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1536 if(tmp_ts == AV_NOPTS_VALUE)
1540 if(tmp_pos >= filesize)
1546 if(ts_min > ts_max){
1548 }else if(ts_min == ts_max){
1553 while (pos_min < pos_limit) {
1554 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1555 pos_min, pos_max, ts_min, ts_max);
1556 assert(pos_limit <= pos_max);
1559 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1560 // interpolate position (better than dichotomy)
1561 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1562 + pos_min - approximate_keyframe_distance;
1563 }else if(no_change==1){
1564 // bisection, if interpolation failed to change min or max pos last time
1565 pos = (pos_min + pos_limit)>>1;
1567 /* linear search if bisection failed, can only happen if there
1568 are very few or no keyframes between min/max */
1573 else if(pos > pos_limit)
1577 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1582 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1583 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1584 pos_limit, start_pos, no_change);
1585 if(ts == AV_NOPTS_VALUE){
1586 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1589 assert(ts != AV_NOPTS_VALUE);
1590 if (target_ts <= ts) {
1591 pos_limit = start_pos - 1;
1595 if (target_ts >= ts) {
1601 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1602 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1604 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1606 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1607 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1608 pos, ts_min, target_ts, ts_max);
1613 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1614 int64_t pos_min, pos_max;
1616 pos_min = s->data_offset;
1617 pos_max = avio_size(s->pb) - 1;
1619 if (pos < pos_min) pos= pos_min;
1620 else if(pos > pos_max) pos= pos_max;
1622 avio_seek(s->pb, pos, SEEK_SET);
1627 static int seek_frame_generic(AVFormatContext *s,
1628 int stream_index, int64_t timestamp, int flags)
1635 st = s->streams[stream_index];
1637 index = av_index_search_timestamp(st, timestamp, flags);
1639 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1642 if(index < 0 || index==st->nb_index_entries-1){
1645 if(st->nb_index_entries){
1646 assert(st->index_entries);
1647 ie= &st->index_entries[st->nb_index_entries-1];
1648 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1650 ff_update_cur_dts(s, st, ie->timestamp);
1652 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1658 read_status = av_read_frame(s, &pkt);
1659 } while (read_status == AVERROR(EAGAIN));
1660 if (read_status < 0)
1662 av_free_packet(&pkt);
1663 if(stream_index == pkt.stream_index){
1664 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1668 index = av_index_search_timestamp(st, timestamp, flags);
1673 ff_read_frame_flush(s);
1674 if (s->iformat->read_seek){
1675 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1678 ie = &st->index_entries[index];
1679 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1681 ff_update_cur_dts(s, st, ie->timestamp);
1686 static int seek_frame_internal(AVFormatContext *s, int stream_index,
1687 int64_t timestamp, int flags)
1692 if (flags & AVSEEK_FLAG_BYTE) {
1693 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1695 ff_read_frame_flush(s);
1696 return seek_frame_byte(s, stream_index, timestamp, flags);
1699 if(stream_index < 0){
1700 stream_index= av_find_default_stream_index(s);
1701 if(stream_index < 0)
1704 st= s->streams[stream_index];
1705 /* timestamp for default must be expressed in AV_TIME_BASE units */
1706 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1709 /* first, we try the format specific seek */
1710 if (s->iformat->read_seek) {
1711 ff_read_frame_flush(s);
1712 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1719 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1720 ff_read_frame_flush(s);
1721 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1722 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1723 ff_read_frame_flush(s);
1724 return seek_frame_generic(s, stream_index, timestamp, flags);
1730 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1732 int ret = seek_frame_internal(s, stream_index, timestamp, flags);
1735 queue_attached_pictures(s);
1740 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1742 if(min_ts > ts || max_ts < ts)
1745 if (s->iformat->read_seek2) {
1747 ff_read_frame_flush(s);
1748 ret = s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1751 queue_attached_pictures(s);
1755 if(s->iformat->read_timestamp){
1756 //try to seek via read_timestamp()
1759 //Fallback to old API if new is not implemented but old is
1760 //Note the old has somewat different sematics
1761 if(s->iformat->read_seek || 1)
1762 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1764 // try some generic seek like seek_frame_generic() but with new ts semantics
1767 /*******************************************************/
1770 * Return TRUE if the stream has accurate duration in any stream.
1772 * @return TRUE if the stream has accurate duration for at least one component.
1774 static int has_duration(AVFormatContext *ic)
1779 for(i = 0;i < ic->nb_streams; i++) {
1780 st = ic->streams[i];
1781 if (st->duration != AV_NOPTS_VALUE)
1784 if (ic->duration != AV_NOPTS_VALUE)
1790 * Estimate the stream timings from the one of each components.
1792 * Also computes the global bitrate if possible.
1794 static void update_stream_timings(AVFormatContext *ic)
1796 int64_t start_time, start_time1, end_time, end_time1;
1797 int64_t duration, duration1, filesize;
1801 start_time = INT64_MAX;
1802 end_time = INT64_MIN;
1803 duration = INT64_MIN;
1804 for(i = 0;i < ic->nb_streams; i++) {
1805 st = ic->streams[i];
1806 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1807 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1808 start_time = FFMIN(start_time, start_time1);
1809 if (st->duration != AV_NOPTS_VALUE) {
1810 end_time1 = start_time1
1811 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1812 end_time = FFMAX(end_time, end_time1);
1815 if (st->duration != AV_NOPTS_VALUE) {
1816 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1817 duration = FFMAX(duration, duration1);
1820 if (start_time != INT64_MAX) {
1821 ic->start_time = start_time;
1822 if (end_time != INT64_MIN)
1823 duration = FFMAX(duration, end_time - start_time);
1825 if (duration != INT64_MIN) {
1826 ic->duration = duration;
1827 if (ic->pb && (filesize = avio_size(ic->pb)) > 0) {
1828 /* compute the bitrate */
1829 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
1830 (double)ic->duration;
1835 static void fill_all_stream_timings(AVFormatContext *ic)
1840 update_stream_timings(ic);
1841 for(i = 0;i < ic->nb_streams; i++) {
1842 st = ic->streams[i];
1843 if (st->start_time == AV_NOPTS_VALUE) {
1844 if(ic->start_time != AV_NOPTS_VALUE)
1845 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1846 if(ic->duration != AV_NOPTS_VALUE)
1847 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1852 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
1854 int64_t filesize, duration;
1858 /* if bit_rate is already set, we believe it */
1859 if (ic->bit_rate <= 0) {
1861 for(i=0;i<ic->nb_streams;i++) {
1862 st = ic->streams[i];
1863 if (st->codec->bit_rate > 0)
1864 bit_rate += st->codec->bit_rate;
1866 ic->bit_rate = bit_rate;
1869 /* if duration is already set, we believe it */
1870 if (ic->duration == AV_NOPTS_VALUE &&
1871 ic->bit_rate != 0) {
1872 filesize = ic->pb ? avio_size(ic->pb) : 0;
1874 for(i = 0; i < ic->nb_streams; i++) {
1875 st = ic->streams[i];
1876 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1877 if (st->duration == AV_NOPTS_VALUE)
1878 st->duration = duration;
1884 #define DURATION_MAX_READ_SIZE 250000
1885 #define DURATION_MAX_RETRY 3
1887 /* only usable for MPEG-PS streams */
1888 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1890 AVPacket pkt1, *pkt = &pkt1;
1892 int read_size, i, ret;
1894 int64_t filesize, offset, duration;
1897 /* flush packet queue */
1898 flush_packet_queue(ic);
1900 for (i=0; i<ic->nb_streams; i++) {
1901 st = ic->streams[i];
1902 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1903 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
1906 av_parser_close(st->parser);
1911 /* estimate the end time (duration) */
1912 /* XXX: may need to support wrapping */
1913 filesize = ic->pb ? avio_size(ic->pb) : 0;
1914 end_time = AV_NOPTS_VALUE;
1916 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1920 avio_seek(ic->pb, offset, SEEK_SET);
1923 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1927 ret = ff_read_packet(ic, pkt);
1928 } while(ret == AVERROR(EAGAIN));
1931 read_size += pkt->size;
1932 st = ic->streams[pkt->stream_index];
1933 if (pkt->pts != AV_NOPTS_VALUE &&
1934 (st->start_time != AV_NOPTS_VALUE ||
1935 st->first_dts != AV_NOPTS_VALUE)) {
1936 duration = end_time = pkt->pts;
1937 if (st->start_time != AV_NOPTS_VALUE)
1938 duration -= st->start_time;
1940 duration -= st->first_dts;
1942 duration += 1LL<<st->pts_wrap_bits;
1944 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
1945 st->duration = duration;
1948 av_free_packet(pkt);
1950 }while( end_time==AV_NOPTS_VALUE
1951 && filesize > (DURATION_MAX_READ_SIZE<<retry)
1952 && ++retry <= DURATION_MAX_RETRY);
1954 fill_all_stream_timings(ic);
1956 avio_seek(ic->pb, old_offset, SEEK_SET);
1957 for (i=0; i<ic->nb_streams; i++) {
1959 st->cur_dts= st->first_dts;
1960 st->last_IP_pts = AV_NOPTS_VALUE;
1961 st->reference_dts = AV_NOPTS_VALUE;
1965 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
1969 /* get the file size, if possible */
1970 if (ic->iformat->flags & AVFMT_NOFILE) {
1973 file_size = avio_size(ic->pb);
1974 file_size = FFMAX(0, file_size);
1977 if ((!strcmp(ic->iformat->name, "mpeg") ||
1978 !strcmp(ic->iformat->name, "mpegts")) &&
1979 file_size && ic->pb->seekable) {
1980 /* get accurate estimate from the PTSes */
1981 estimate_timings_from_pts(ic, old_offset);
1982 } else if (has_duration(ic)) {
1983 /* at least one component has timings - we use them for all
1985 fill_all_stream_timings(ic);
1987 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
1988 /* less precise: use bitrate info */
1989 estimate_timings_from_bit_rate(ic);
1991 update_stream_timings(ic);
1995 AVStream av_unused *st;
1996 for(i = 0;i < ic->nb_streams; i++) {
1997 st = ic->streams[i];
1998 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
1999 (double) st->start_time / AV_TIME_BASE,
2000 (double) st->duration / AV_TIME_BASE);
2002 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2003 (double) ic->start_time / AV_TIME_BASE,
2004 (double) ic->duration / AV_TIME_BASE,
2005 ic->bit_rate / 1000);
2009 static int has_codec_parameters(AVStream *st)
2011 AVCodecContext *avctx = st->codec;
2013 switch (avctx->codec_type) {
2014 case AVMEDIA_TYPE_AUDIO:
2015 val = avctx->sample_rate && avctx->channels;
2016 if (st->info->found_decoder >= 0 && avctx->sample_fmt == AV_SAMPLE_FMT_NONE)
2019 case AVMEDIA_TYPE_VIDEO:
2021 if (st->info->found_decoder >= 0 && avctx->pix_fmt == AV_PIX_FMT_NONE)
2028 return avctx->codec_id != AV_CODEC_ID_NONE && val != 0;
2031 static int has_decode_delay_been_guessed(AVStream *st)
2033 return st->codec->codec_id != AV_CODEC_ID_H264 ||
2034 st->info->nb_decoded_frames >= 6;
2037 /* returns 1 or 0 if or if not decoded data was returned, or a negative error */
2038 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2040 const AVCodec *codec;
2041 int got_picture = 1, ret = 0;
2042 AVFrame *frame = avcodec_alloc_frame();
2043 AVPacket pkt = *avpkt;
2046 return AVERROR(ENOMEM);
2048 if (!avcodec_is_open(st->codec) && !st->info->found_decoder) {
2049 AVDictionary *thread_opt = NULL;
2051 codec = st->codec->codec ? st->codec->codec :
2052 avcodec_find_decoder(st->codec->codec_id);
2055 st->info->found_decoder = -1;
2060 /* force thread count to 1 since the h264 decoder will not extract SPS
2061 * and PPS to extradata during multi-threaded decoding */
2062 av_dict_set(options ? options : &thread_opt, "threads", "1", 0);
2063 ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);
2065 av_dict_free(&thread_opt);
2067 st->info->found_decoder = -1;
2070 st->info->found_decoder = 1;
2071 } else if (!st->info->found_decoder)
2072 st->info->found_decoder = 1;
2074 if (st->info->found_decoder < 0) {
2079 while ((pkt.size > 0 || (!pkt.data && got_picture)) &&
2081 (!has_codec_parameters(st) ||
2082 !has_decode_delay_been_guessed(st) ||
2083 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2085 avcodec_get_frame_defaults(frame);
2086 switch(st->codec->codec_type) {
2087 case AVMEDIA_TYPE_VIDEO:
2088 ret = avcodec_decode_video2(st->codec, frame,
2089 &got_picture, &pkt);
2091 case AVMEDIA_TYPE_AUDIO:
2092 ret = avcodec_decode_audio4(st->codec, frame, &got_picture, &pkt);
2099 st->info->nb_decoded_frames++;
2107 avcodec_free_frame(&frame);
2111 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id)
2113 while (tags->id != AV_CODEC_ID_NONE) {
2121 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2124 for(i=0; tags[i].id != AV_CODEC_ID_NONE;i++) {
2125 if(tag == tags[i].tag)
2128 for(i=0; tags[i].id != AV_CODEC_ID_NONE; i++) {
2129 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2132 return AV_CODEC_ID_NONE;
2135 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum AVCodecID id)
2138 for(i=0; tags && tags[i]; i++){
2139 int tag= ff_codec_get_tag(tags[i], id);
2145 enum AVCodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2148 for(i=0; tags && tags[i]; i++){
2149 enum AVCodecID id= ff_codec_get_id(tags[i], tag);
2150 if(id!=AV_CODEC_ID_NONE) return id;
2152 return AV_CODEC_ID_NONE;
2155 static void compute_chapters_end(AVFormatContext *s)
2158 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2160 for (i = 0; i < s->nb_chapters; i++)
2161 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2162 AVChapter *ch = s->chapters[i];
2163 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2166 for (j = 0; j < s->nb_chapters; j++) {
2167 AVChapter *ch1 = s->chapters[j];
2168 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2169 if (j != i && next_start > ch->start && next_start < end)
2172 ch->end = (end == INT64_MAX) ? ch->start : end;
2176 static int get_std_framerate(int i){
2177 if(i<60*12) return i*1001;
2178 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2182 * Is the time base unreliable.
2183 * This is a heuristic to balance between quick acceptance of the values in
2184 * the headers vs. some extra checks.
2185 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2186 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2187 * And there are "variable" fps files this needs to detect as well.
2189 static int tb_unreliable(AVCodecContext *c){
2190 if( c->time_base.den >= 101L*c->time_base.num
2191 || c->time_base.den < 5L*c->time_base.num
2192 /* || c->codec_tag == AV_RL32("DIVX")
2193 || c->codec_tag == AV_RL32("XVID")*/
2194 || c->codec_id == AV_CODEC_ID_MPEG2VIDEO
2195 || c->codec_id == AV_CODEC_ID_H264
2201 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2203 int i, count, ret, read_size, j;
2205 AVPacket pkt1, *pkt;
2206 int64_t old_offset = avio_tell(ic->pb);
2207 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2209 for(i=0;i<ic->nb_streams;i++) {
2210 const AVCodec *codec;
2211 AVDictionary *thread_opt = NULL;
2212 st = ic->streams[i];
2214 //only for the split stuff
2215 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2216 st->parser = av_parser_init(st->codec->codec_id);
2217 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2218 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2221 codec = st->codec->codec ? st->codec->codec :
2222 avcodec_find_decoder(st->codec->codec_id);
2224 /* force thread count to 1 since the h264 decoder will not extract SPS
2225 * and PPS to extradata during multi-threaded decoding */
2226 av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);
2228 /* Ensure that subtitle_header is properly set. */
2229 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2230 && codec && !st->codec->codec)
2231 avcodec_open2(st->codec, codec, options ? &options[i]
2234 //try to just open decoders, in case this is enough to get parameters
2235 if (!has_codec_parameters(st)) {
2236 if (codec && !st->codec->codec)
2237 avcodec_open2(st->codec, codec, options ? &options[i]
2241 av_dict_free(&thread_opt);
2244 for (i=0; i<ic->nb_streams; i++) {
2245 #if FF_API_R_FRAME_RATE
2246 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2248 ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;
2249 ic->streams[i]->info->fps_last_dts = AV_NOPTS_VALUE;
2255 if (ff_check_interrupt(&ic->interrupt_callback)){
2257 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2261 /* check if one codec still needs to be handled */
2262 for(i=0;i<ic->nb_streams;i++) {
2263 int fps_analyze_framecount = 20;
2265 st = ic->streams[i];
2266 if (!has_codec_parameters(st))
2268 /* if the timebase is coarse (like the usual millisecond precision
2269 of mkv), we need to analyze more frames to reliably arrive at
2271 if (av_q2d(st->time_base) > 0.0005)
2272 fps_analyze_framecount *= 2;
2273 if (ic->fps_probe_size >= 0)
2274 fps_analyze_framecount = ic->fps_probe_size;
2275 /* variable fps and no guess at the real fps */
2276 if( tb_unreliable(st->codec) && !st->avg_frame_rate.num
2277 && st->codec_info_nb_frames < fps_analyze_framecount
2278 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2280 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2282 if (st->first_dts == AV_NOPTS_VALUE &&
2283 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2284 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2287 if (i == ic->nb_streams) {
2288 /* NOTE: if the format has no header, then we need to read
2289 some packets to get most of the streams, so we cannot
2291 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2292 /* if we found the info for all the codecs, we can stop */
2294 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2298 /* we did not get all the codec info, but we read too much data */
2299 if (read_size >= ic->probesize) {
2301 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2305 /* NOTE: a new stream can be added there if no header in file
2306 (AVFMTCTX_NOHEADER) */
2307 ret = read_frame_internal(ic, &pkt1);
2308 if (ret == AVERROR(EAGAIN))
2313 AVPacket empty_pkt = { 0 };
2315 av_init_packet(&empty_pkt);
2317 ret = -1; /* we could not have all the codec parameters before EOF */
2318 for(i=0;i<ic->nb_streams;i++) {
2319 st = ic->streams[i];
2321 /* flush the decoders */
2322 if (st->info->found_decoder == 1) {
2324 err = try_decode_frame(st, &empty_pkt,
2325 (options && i < orig_nb_streams) ?
2326 &options[i] : NULL);
2327 } while (err > 0 && !has_codec_parameters(st));
2331 av_log(ic, AV_LOG_WARNING,
2332 "decoding for stream %d failed\n", st->index);
2333 } else if (!has_codec_parameters(st)) {
2335 avcodec_string(buf, sizeof(buf), st->codec, 0);
2336 av_log(ic, AV_LOG_WARNING,
2337 "Could not find codec parameters (%s)\n", buf);
2345 if (ic->flags & AVFMT_FLAG_NOBUFFER) {
2348 pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,
2349 &ic->packet_buffer_end);
2350 if ((ret = av_dup_packet(pkt)) < 0)
2351 goto find_stream_info_err;
2354 read_size += pkt->size;
2356 st = ic->streams[pkt->stream_index];
2357 if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {
2358 /* check for non-increasing dts */
2359 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2360 st->info->fps_last_dts >= pkt->dts) {
2361 av_log(ic, AV_LOG_WARNING, "Non-increasing DTS in stream %d: "
2362 "packet %d with DTS %"PRId64", packet %d with DTS "
2363 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2364 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2365 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2367 /* check for a discontinuity in dts - if the difference in dts
2368 * is more than 1000 times the average packet duration in the sequence,
2369 * we treat it as a discontinuity */
2370 if (st->info->fps_last_dts != AV_NOPTS_VALUE &&
2371 st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&
2372 (pkt->dts - st->info->fps_last_dts) / 1000 >
2373 (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {
2374 av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "
2375 "packet %d with DTS %"PRId64", packet %d with DTS "
2376 "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,
2377 st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);
2378 st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;
2381 /* update stored dts values */
2382 if (st->info->fps_first_dts == AV_NOPTS_VALUE) {
2383 st->info->fps_first_dts = pkt->dts;
2384 st->info->fps_first_dts_idx = st->codec_info_nb_frames;
2386 st->info->fps_last_dts = pkt->dts;
2387 st->info->fps_last_dts_idx = st->codec_info_nb_frames;
2389 /* check max_analyze_duration */
2390 if (av_rescale_q(pkt->dts - st->info->fps_first_dts, st->time_base,
2391 AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2392 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2396 #if FF_API_R_FRAME_RATE
2398 int64_t last = st->info->last_dts;
2400 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
2401 int64_t duration= pkt->dts - last;
2402 double dur= duration * av_q2d(st->time_base);
2404 if (st->info->duration_count < 2)
2405 memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2406 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2407 int framerate= get_std_framerate(i);
2408 int ticks= lrintf(dur*framerate/(1001*12));
2409 double error = dur - (double)ticks*1001*12 / framerate;
2410 st->info->duration_error[i] += error*error;
2412 st->info->duration_count++;
2413 // ignore the first 4 values, they might have some random jitter
2414 if (st->info->duration_count > 3)
2415 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2417 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2418 st->info->last_dts = pkt->dts;
2421 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2422 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2423 if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {
2424 st->codec->extradata_size= i;
2425 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2426 if (!st->codec->extradata)
2427 return AVERROR(ENOMEM);
2428 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2429 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2433 /* if still no information, we try to open the codec and to
2434 decompress the frame. We try to avoid that in most cases as
2435 it takes longer and uses more memory. For MPEG-4, we need to
2436 decompress for QuickTime.
2438 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2439 least one frame of codec data, this makes sure the codec initializes
2440 the channel configuration and does not only trust the values from the container.
2442 try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);
2444 st->codec_info_nb_frames++;
2448 // close codecs which were opened in try_decode_frame()
2449 for(i=0;i<ic->nb_streams;i++) {
2450 st = ic->streams[i];
2451 avcodec_close(st->codec);
2453 for(i=0;i<ic->nb_streams;i++) {
2454 st = ic->streams[i];
2455 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2456 /* estimate average framerate if not set by demuxer */
2457 if (!st->avg_frame_rate.num && st->info->fps_last_dts != st->info->fps_first_dts) {
2458 int64_t delta_dts = st->info->fps_last_dts - st->info->fps_first_dts;
2459 int delta_packets = st->info->fps_last_dts_idx - st->info->fps_first_dts_idx;
2461 double best_error = 0.01;
2463 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2464 delta_packets*(int64_t)st->time_base.den,
2465 delta_dts*(int64_t)st->time_base.num, 60000);
2467 /* round guessed framerate to a "standard" framerate if it's
2468 * within 1% of the original estimate*/
2469 for (j = 1; j < MAX_STD_TIMEBASES; j++) {
2470 AVRational std_fps = { get_std_framerate(j), 12*1001 };
2471 double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);
2473 if (error < best_error) {
2475 best_fps = std_fps.num;
2479 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2480 best_fps, 12*1001, INT_MAX);
2483 #if FF_API_R_FRAME_RATE
2484 // the check for tb_unreliable() is not completely correct, since this is not about handling
2485 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2486 // ipmovie.c produces.
2487 if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > 1 && !st->r_frame_rate.num)
2488 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);
2489 if (st->info->duration_count && !st->r_frame_rate.num
2490 && tb_unreliable(st->codec)) {
2492 double best_error= 2*av_q2d(st->time_base);
2493 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2495 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2496 double error = st->info->duration_error[j] * get_std_framerate(j);
2497 if(error < best_error){
2499 num = get_std_framerate(j);
2502 // do not increase frame rate by more than 1 % in order to match a standard rate.
2503 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2504 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2507 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2508 if(!st->codec->bits_per_coded_sample)
2509 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2510 // set stream disposition based on audio service type
2511 switch (st->codec->audio_service_type) {
2512 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2513 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2514 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2515 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2516 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2517 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2518 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2519 st->disposition = AV_DISPOSITION_COMMENT; break;
2520 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2521 st->disposition = AV_DISPOSITION_KARAOKE; break;
2526 estimate_timings(ic, old_offset);
2528 compute_chapters_end(ic);
2530 find_stream_info_err:
2531 for (i=0; i < ic->nb_streams; i++) {
2532 if (ic->streams[i]->codec)
2533 ic->streams[i]->codec->thread_count = 0;
2534 av_freep(&ic->streams[i]->info);
2539 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2543 for (i = 0; i < ic->nb_programs; i++)
2544 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2545 if (ic->programs[i]->stream_index[j] == s)
2546 return ic->programs[i];
2550 int av_find_best_stream(AVFormatContext *ic,
2551 enum AVMediaType type,
2552 int wanted_stream_nb,
2554 AVCodec **decoder_ret,
2557 int i, nb_streams = ic->nb_streams;
2558 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2559 unsigned *program = NULL;
2560 AVCodec *decoder = NULL, *best_decoder = NULL;
2562 if (related_stream >= 0 && wanted_stream_nb < 0) {
2563 AVProgram *p = find_program_from_stream(ic, related_stream);
2565 program = p->stream_index;
2566 nb_streams = p->nb_stream_indexes;
2569 for (i = 0; i < nb_streams; i++) {
2570 int real_stream_index = program ? program[i] : i;
2571 AVStream *st = ic->streams[real_stream_index];
2572 AVCodecContext *avctx = st->codec;
2573 if (avctx->codec_type != type)
2575 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2577 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2580 decoder = avcodec_find_decoder(st->codec->codec_id);
2583 ret = AVERROR_DECODER_NOT_FOUND;
2587 if (best_count >= st->codec_info_nb_frames)
2589 best_count = st->codec_info_nb_frames;
2590 ret = real_stream_index;
2591 best_decoder = decoder;
2592 if (program && i == nb_streams - 1 && ret < 0) {
2594 nb_streams = ic->nb_streams;
2595 i = 0; /* no related stream found, try again with everything */
2599 *decoder_ret = best_decoder;
2603 /*******************************************************/
2605 int av_read_play(AVFormatContext *s)
2607 if (s->iformat->read_play)
2608 return s->iformat->read_play(s);
2610 return avio_pause(s->pb, 0);
2611 return AVERROR(ENOSYS);
2614 int av_read_pause(AVFormatContext *s)
2616 if (s->iformat->read_pause)
2617 return s->iformat->read_pause(s);
2619 return avio_pause(s->pb, 1);
2620 return AVERROR(ENOSYS);
2623 void avformat_free_context(AVFormatContext *s)
2629 if (s->iformat && s->iformat->priv_class && s->priv_data)
2630 av_opt_free(s->priv_data);
2632 for(i=0;i<s->nb_streams;i++) {
2633 /* free all data in a stream component */
2636 av_parser_close(st->parser);
2638 if (st->attached_pic.data)
2639 av_free_packet(&st->attached_pic);
2640 av_dict_free(&st->metadata);
2641 av_free(st->index_entries);
2642 av_free(st->codec->extradata);
2643 av_free(st->codec->subtitle_header);
2645 av_free(st->priv_data);
2649 for(i=s->nb_programs-1; i>=0; i--) {
2650 av_dict_free(&s->programs[i]->metadata);
2651 av_freep(&s->programs[i]->stream_index);
2652 av_freep(&s->programs[i]);
2654 av_freep(&s->programs);
2655 av_freep(&s->priv_data);
2656 while(s->nb_chapters--) {
2657 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2658 av_free(s->chapters[s->nb_chapters]);
2660 av_freep(&s->chapters);
2661 av_dict_free(&s->metadata);
2662 av_freep(&s->streams);
2666 #if FF_API_CLOSE_INPUT_FILE
2667 void av_close_input_file(AVFormatContext *s)
2669 avformat_close_input(&s);
2673 void avformat_close_input(AVFormatContext **ps)
2675 AVFormatContext *s = *ps;
2676 AVIOContext *pb = s->pb;
2678 if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
2679 (s->flags & AVFMT_FLAG_CUSTOM_IO))
2682 flush_packet_queue(s);
2685 if (s->iformat->read_close)
2686 s->iformat->read_close(s);
2689 avformat_free_context(s);
2696 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2702 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2704 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2707 s->streams = streams;
2709 st = av_mallocz(sizeof(AVStream));
2712 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2717 st->codec = avcodec_alloc_context3(c);
2719 /* no default bitrate if decoding */
2720 st->codec->bit_rate = 0;
2722 st->index = s->nb_streams;
2723 st->start_time = AV_NOPTS_VALUE;
2724 st->duration = AV_NOPTS_VALUE;
2725 /* we set the current DTS to 0 so that formats without any timestamps
2726 but durations get some timestamps, formats with some unknown
2727 timestamps have their first few packets buffered and the
2728 timestamps corrected before they are returned to the user */
2730 st->first_dts = AV_NOPTS_VALUE;
2731 st->probe_packets = MAX_PROBE_PACKETS;
2733 /* default pts setting is MPEG-like */
2734 avpriv_set_pts_info(st, 33, 1, 90000);
2735 st->last_IP_pts = AV_NOPTS_VALUE;
2736 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2737 st->pts_buffer[i]= AV_NOPTS_VALUE;
2738 st->reference_dts = AV_NOPTS_VALUE;
2740 st->sample_aspect_ratio = (AVRational){0,1};
2742 #if FF_API_R_FRAME_RATE
2743 st->info->last_dts = AV_NOPTS_VALUE;
2745 st->info->fps_first_dts = AV_NOPTS_VALUE;
2746 st->info->fps_last_dts = AV_NOPTS_VALUE;
2748 s->streams[s->nb_streams++] = st;
2752 AVProgram *av_new_program(AVFormatContext *ac, int id)
2754 AVProgram *program=NULL;
2757 av_dlog(ac, "new_program: id=0x%04x\n", id);
2759 for(i=0; i<ac->nb_programs; i++)
2760 if(ac->programs[i]->id == id)
2761 program = ac->programs[i];
2764 program = av_mallocz(sizeof(AVProgram));
2767 dynarray_add(&ac->programs, &ac->nb_programs, program);
2768 program->discard = AVDISCARD_NONE;
2775 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2777 AVChapter *chapter = NULL;
2780 for(i=0; i<s->nb_chapters; i++)
2781 if(s->chapters[i]->id == id)
2782 chapter = s->chapters[i];
2785 chapter= av_mallocz(sizeof(AVChapter));
2788 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2790 av_dict_set(&chapter->metadata, "title", title, 0);
2792 chapter->time_base= time_base;
2793 chapter->start = start;
2799 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2802 AVProgram *program=NULL;
2805 if (idx >= ac->nb_streams) {
2806 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
2810 for(i=0; i<ac->nb_programs; i++){
2811 if(ac->programs[i]->id != progid)
2813 program = ac->programs[i];
2814 for(j=0; j<program->nb_stream_indexes; j++)
2815 if(program->stream_index[j] == idx)
2818 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2821 program->stream_index = tmp;
2822 program->stream_index[program->nb_stream_indexes++] = idx;
2827 static void print_fps(double d, const char *postfix){
2828 uint64_t v= lrintf(d*100);
2829 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
2830 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
2831 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
2834 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
2836 if(m && !(av_dict_count(m) == 1 && av_dict_get(m, "language", NULL, 0))){
2837 AVDictionaryEntry *tag=NULL;
2839 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
2840 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
2841 if(strcmp("language", tag->key))
2842 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
2847 /* "user interface" functions */
2848 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2851 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2852 AVStream *st = ic->streams[i];
2853 int g = av_gcd(st->time_base.num, st->time_base.den);
2854 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
2855 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2856 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2857 /* the pid is an important information, so we display it */
2858 /* XXX: add a generic system */
2859 if (flags & AVFMT_SHOW_IDS)
2860 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2862 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
2863 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
2864 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2865 if (st->sample_aspect_ratio.num && // default
2866 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
2867 AVRational display_aspect_ratio;
2868 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
2869 st->codec->width*st->sample_aspect_ratio.num,
2870 st->codec->height*st->sample_aspect_ratio.den,
2872 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
2873 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
2874 display_aspect_ratio.num, display_aspect_ratio.den);
2876 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
2877 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
2878 print_fps(av_q2d(st->avg_frame_rate), "fps");
2879 #if FF_API_R_FRAME_RATE
2880 if(st->r_frame_rate.den && st->r_frame_rate.num)
2881 print_fps(av_q2d(st->r_frame_rate), "tbr");
2883 if(st->time_base.den && st->time_base.num)
2884 print_fps(1/av_q2d(st->time_base), "tbn");
2885 if(st->codec->time_base.den && st->codec->time_base.num)
2886 print_fps(1/av_q2d(st->codec->time_base), "tbc");
2888 if (st->disposition & AV_DISPOSITION_DEFAULT)
2889 av_log(NULL, AV_LOG_INFO, " (default)");
2890 if (st->disposition & AV_DISPOSITION_DUB)
2891 av_log(NULL, AV_LOG_INFO, " (dub)");
2892 if (st->disposition & AV_DISPOSITION_ORIGINAL)
2893 av_log(NULL, AV_LOG_INFO, " (original)");
2894 if (st->disposition & AV_DISPOSITION_COMMENT)
2895 av_log(NULL, AV_LOG_INFO, " (comment)");
2896 if (st->disposition & AV_DISPOSITION_LYRICS)
2897 av_log(NULL, AV_LOG_INFO, " (lyrics)");
2898 if (st->disposition & AV_DISPOSITION_KARAOKE)
2899 av_log(NULL, AV_LOG_INFO, " (karaoke)");
2900 if (st->disposition & AV_DISPOSITION_FORCED)
2901 av_log(NULL, AV_LOG_INFO, " (forced)");
2902 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
2903 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
2904 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
2905 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
2906 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
2907 av_log(NULL, AV_LOG_INFO, " (clean effects)");
2908 av_log(NULL, AV_LOG_INFO, "\n");
2909 dump_metadata(NULL, st->metadata, " ");
2912 void av_dump_format(AVFormatContext *ic,
2918 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
2919 if (ic->nb_streams && !printed)
2922 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2923 is_output ? "Output" : "Input",
2925 is_output ? ic->oformat->name : ic->iformat->name,
2926 is_output ? "to" : "from", url);
2927 dump_metadata(NULL, ic->metadata, " ");
2929 av_log(NULL, AV_LOG_INFO, " Duration: ");
2930 if (ic->duration != AV_NOPTS_VALUE) {
2931 int hours, mins, secs, us;
2932 secs = ic->duration / AV_TIME_BASE;
2933 us = ic->duration % AV_TIME_BASE;
2938 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2939 (100 * us) / AV_TIME_BASE);
2941 av_log(NULL, AV_LOG_INFO, "N/A");
2943 if (ic->start_time != AV_NOPTS_VALUE) {
2945 av_log(NULL, AV_LOG_INFO, ", start: ");
2946 secs = ic->start_time / AV_TIME_BASE;
2947 us = abs(ic->start_time % AV_TIME_BASE);
2948 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2949 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2951 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2953 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2955 av_log(NULL, AV_LOG_INFO, "N/A");
2957 av_log(NULL, AV_LOG_INFO, "\n");
2959 for (i = 0; i < ic->nb_chapters; i++) {
2960 AVChapter *ch = ic->chapters[i];
2961 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
2962 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
2963 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
2965 dump_metadata(NULL, ch->metadata, " ");
2967 if(ic->nb_programs) {
2968 int j, k, total = 0;
2969 for(j=0; j<ic->nb_programs; j++) {
2970 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
2972 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2973 name ? name->value : "");
2974 dump_metadata(NULL, ic->programs[j]->metadata, " ");
2975 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
2976 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2977 printed[ic->programs[j]->stream_index[k]] = 1;
2979 total += ic->programs[j]->nb_stream_indexes;
2981 if (total < ic->nb_streams)
2982 av_log(NULL, AV_LOG_INFO, " No Program\n");
2984 for(i=0;i<ic->nb_streams;i++)
2986 dump_stream_format(ic, i, index, is_output);
2991 #if FF_API_AV_GETTIME && CONFIG_SHARED && HAVE_SYMVER
2992 FF_SYMVER(int64_t, av_gettime, (void), "LIBAVFORMAT_54")
2994 return av_gettime();
2998 uint64_t ff_ntp_time(void)
3000 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3003 int av_get_frame_filename(char *buf, int buf_size,
3004 const char *path, int number)
3007 char *q, buf1[20], c;
3008 int nd, len, percentd_found;
3020 while (isdigit(*p)) {
3021 nd = nd * 10 + *p++ - '0';
3024 } while (isdigit(c));
3033 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3035 if ((q - buf + len) > buf_size - 1)
3037 memcpy(q, buf1, len);
3045 if ((q - buf) < buf_size - 1)
3049 if (!percentd_found)
3058 static void hex_dump_internal(void *avcl, FILE *f, int level,
3059 const uint8_t *buf, int size)
3063 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3065 for(i=0;i<size;i+=16) {
3072 PRINT(" %02x", buf[i+j]);
3077 for(j=0;j<len;j++) {
3079 if (c < ' ' || c > '~')
3088 void av_hex_dump(FILE *f, const uint8_t *buf, int size)
3090 hex_dump_internal(NULL, f, 0, buf, size);
3093 void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size)
3095 hex_dump_internal(avcl, NULL, level, buf, size);
3098 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3101 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3102 PRINT("stream #%d:\n", pkt->stream_index);
3103 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3104 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3105 /* DTS is _always_ valid after av_read_frame() */
3107 if (pkt->dts == AV_NOPTS_VALUE)
3110 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3111 /* PTS may not be known if B-frames are present. */
3113 if (pkt->pts == AV_NOPTS_VALUE)
3116 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3118 PRINT(" size=%d\n", pkt->size);
3121 av_hex_dump(f, pkt->data, pkt->size);
3124 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3126 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3129 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3132 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3135 void av_url_split(char *proto, int proto_size,
3136 char *authorization, int authorization_size,
3137 char *hostname, int hostname_size,
3139 char *path, int path_size,
3142 const char *p, *ls, *at, *col, *brk;
3144 if (port_ptr) *port_ptr = -1;
3145 if (proto_size > 0) proto[0] = 0;
3146 if (authorization_size > 0) authorization[0] = 0;
3147 if (hostname_size > 0) hostname[0] = 0;
3148 if (path_size > 0) path[0] = 0;
3150 /* parse protocol */
3151 if ((p = strchr(url, ':'))) {
3152 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3157 /* no protocol means plain filename */
3158 av_strlcpy(path, url, path_size);
3162 /* separate path from hostname */
3163 ls = strchr(p, '/');
3165 ls = strchr(p, '?');
3167 av_strlcpy(path, ls, path_size);
3169 ls = &p[strlen(p)]; // XXX
3171 /* the rest is hostname, use that to parse auth/port */
3173 /* authorization (user[:pass]@hostname) */
3174 if ((at = strchr(p, '@')) && at < ls) {
3175 av_strlcpy(authorization, p,
3176 FFMIN(authorization_size, at + 1 - p));
3177 p = at + 1; /* skip '@' */
3180 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3182 av_strlcpy(hostname, p + 1,
3183 FFMIN(hostname_size, brk - p));
3184 if (brk[1] == ':' && port_ptr)
3185 *port_ptr = atoi(brk + 2);
3186 } else if ((col = strchr(p, ':')) && col < ls) {
3187 av_strlcpy(hostname, p,
3188 FFMIN(col + 1 - p, hostname_size));
3189 if (port_ptr) *port_ptr = atoi(col + 1);
3191 av_strlcpy(hostname, p,
3192 FFMIN(ls + 1 - p, hostname_size));
3196 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3199 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3202 'C', 'D', 'E', 'F' };
3203 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3206 'c', 'd', 'e', 'f' };
3207 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3209 for(i = 0; i < s; i++) {
3210 buff[i * 2] = hex_table[src[i] >> 4];
3211 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3217 int ff_hex_to_data(uint8_t *data, const char *p)
3224 p += strspn(p, SPACE_CHARS);
3227 c = toupper((unsigned char) *p++);
3228 if (c >= '0' && c <= '9')
3230 else if (c >= 'A' && c <= 'F')
3245 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
3246 unsigned int pts_num, unsigned int pts_den)
3249 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3250 if(new_tb.num != pts_num)
3251 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3253 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3255 if(new_tb.num <= 0 || new_tb.den <= 0) {
3256 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3259 s->time_base = new_tb;
3260 s->pts_wrap_bits = pts_wrap_bits;
3263 int ff_url_join(char *str, int size, const char *proto,
3264 const char *authorization, const char *hostname,
3265 int port, const char *fmt, ...)
3268 struct addrinfo hints = { 0 }, *ai;
3273 av_strlcatf(str, size, "%s://", proto);
3274 if (authorization && authorization[0])
3275 av_strlcatf(str, size, "%s@", authorization);
3276 #if CONFIG_NETWORK && defined(AF_INET6)
3277 /* Determine if hostname is a numerical IPv6 address,
3278 * properly escape it within [] in that case. */
3279 hints.ai_flags = AI_NUMERICHOST;
3280 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3281 if (ai->ai_family == AF_INET6) {
3282 av_strlcat(str, "[", size);
3283 av_strlcat(str, hostname, size);
3284 av_strlcat(str, "]", size);
3286 av_strlcat(str, hostname, size);
3291 /* Not an IPv6 address, just output the plain string. */
3292 av_strlcat(str, hostname, size);
3295 av_strlcatf(str, size, ":%d", port);
3298 int len = strlen(str);
3301 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3307 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3308 AVFormatContext *src)
3313 local_pkt.stream_index = dst_stream;
3314 if (pkt->pts != AV_NOPTS_VALUE)
3315 local_pkt.pts = av_rescale_q(pkt->pts,
3316 src->streams[pkt->stream_index]->time_base,
3317 dst->streams[dst_stream]->time_base);
3318 if (pkt->dts != AV_NOPTS_VALUE)
3319 local_pkt.dts = av_rescale_q(pkt->dts,
3320 src->streams[pkt->stream_index]->time_base,
3321 dst->streams[dst_stream]->time_base);
3322 return av_write_frame(dst, &local_pkt);
3325 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3328 const char *ptr = str;
3330 /* Parse key=value pairs. */
3333 char *dest = NULL, *dest_end;
3334 int key_len, dest_len = 0;
3336 /* Skip whitespace and potential commas. */
3337 while (*ptr && (isspace(*ptr) || *ptr == ','))
3344 if (!(ptr = strchr(key, '=')))
3347 key_len = ptr - key;
3349 callback_get_buf(context, key, key_len, &dest, &dest_len);
3350 dest_end = dest + dest_len - 1;
3354 while (*ptr && *ptr != '\"') {
3358 if (dest && dest < dest_end)
3362 if (dest && dest < dest_end)
3370 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3371 if (dest && dest < dest_end)
3379 int ff_find_stream_index(AVFormatContext *s, int id)
3382 for (i = 0; i < s->nb_streams; i++) {
3383 if (s->streams[i]->id == id)
3389 void ff_make_absolute_url(char *buf, int size, const char *base,
3392 char *sep, *path_query;
3393 /* Absolute path, relative to the current server */
3394 if (base && strstr(base, "://") && rel[0] == '/') {
3396 av_strlcpy(buf, base, size);
3397 sep = strstr(buf, "://");
3399 /* Take scheme from base url */
3400 if (rel[1] == '/') {
3403 /* Take scheme and host from base url */
3405 sep = strchr(sep, '/');
3410 av_strlcat(buf, rel, size);
3413 /* If rel actually is an absolute url, just copy it */
3414 if (!base || strstr(rel, "://") || rel[0] == '/') {
3415 av_strlcpy(buf, rel, size);
3419 av_strlcpy(buf, base, size);
3421 /* Strip off any query string from base */
3422 path_query = strchr(buf, '?');
3423 if (path_query != NULL)
3426 /* Is relative path just a new query part? */
3427 if (rel[0] == '?') {
3428 av_strlcat(buf, rel, size);
3432 /* Remove the file name from the base url */
3433 sep = strrchr(buf, '/');
3438 while (av_strstart(rel, "../", NULL) && sep) {
3439 /* Remove the path delimiter at the end */
3441 sep = strrchr(buf, '/');
3442 /* If the next directory name to pop off is "..", break here */
3443 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3444 /* Readd the slash we just removed */
3445 av_strlcat(buf, "/", size);
3448 /* Cut off the directory name */
3455 av_strlcat(buf, rel, size);
3458 int64_t ff_iso8601_to_unix_time(const char *datestr)
3461 struct tm time1 = {0}, time2 = {0};
3463 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
3464 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
3466 return av_timegm(&time2);
3468 return av_timegm(&time1);
3470 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
3471 "the date string.\n");
3476 int avformat_query_codec(AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
3479 if (ofmt->query_codec)
3480 return ofmt->query_codec(codec_id, std_compliance);
3481 else if (ofmt->codec_tag)
3482 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
3483 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
3484 codec_id == ofmt->subtitle_codec)
3487 return AVERROR_PATCHWELCOME;
3490 int avformat_network_init(void)
3494 ff_network_inited_globally = 1;
3495 if ((ret = ff_network_init()) < 0)
3502 int avformat_network_deinit(void)
3511 int ff_add_param_change(AVPacket *pkt, int32_t channels,
3512 uint64_t channel_layout, int32_t sample_rate,
3513 int32_t width, int32_t height)
3519 return AVERROR(EINVAL);
3522 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT;
3524 if (channel_layout) {
3526 flags |= AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT;
3530 flags |= AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE;
3532 if (width || height) {
3534 flags |= AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS;
3536 data = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, size);
3538 return AVERROR(ENOMEM);
3539 bytestream_put_le32(&data, flags);
3541 bytestream_put_le32(&data, channels);
3543 bytestream_put_le64(&data, channel_layout);
3545 bytestream_put_le32(&data, sample_rate);
3546 if (width || height) {
3547 bytestream_put_le32(&data, width);
3548 bytestream_put_le32(&data, height);
3553 const struct AVCodecTag *avformat_get_riff_video_tags(void)
3555 return ff_codec_bmp_tags;
3557 const struct AVCodecTag *avformat_get_riff_audio_tags(void)
3559 return ff_codec_wav_tags;