2 * various utility functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "avio_internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/raw.h"
29 #include "libavutil/opt.h"
32 #include "libavutil/avstring.h"
34 #include "audiointerleave.h"
49 * various utility functions for use within FFmpeg
52 unsigned avformat_version(void)
54 return LIBAVFORMAT_VERSION_INT;
57 const char *avformat_configuration(void)
59 return FFMPEG_CONFIGURATION;
62 const char *avformat_license(void)
64 #define LICENSE_PREFIX "libavformat license: "
65 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
68 /* fraction handling */
71 * f = val + (num / den) + 0.5.
73 * 'num' is normalized so that it is such as 0 <= num < den.
75 * @param f fractional number
76 * @param val integer value
77 * @param num must be >= 0
78 * @param den must be >= 1
80 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
93 * Fractional addition to f: f = f + (incr / f->den).
95 * @param f fractional number
96 * @param incr increment, can be positive or negative
98 static void av_frac_add(AVFrac *f, int64_t incr)
111 } else if (num >= den) {
118 /** head of registered input format linked list */
119 #if !FF_API_FIRST_FORMAT
122 AVInputFormat *first_iformat = NULL;
123 /** head of registered output format linked list */
124 #if !FF_API_FIRST_FORMAT
127 AVOutputFormat *first_oformat = NULL;
129 AVInputFormat *av_iformat_next(AVInputFormat *f)
131 if(f) return f->next;
132 else return first_iformat;
135 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
137 if(f) return f->next;
138 else return first_oformat;
141 void av_register_input_format(AVInputFormat *format)
145 while (*p != NULL) p = &(*p)->next;
150 void av_register_output_format(AVOutputFormat *format)
154 while (*p != NULL) p = &(*p)->next;
159 int av_match_ext(const char *filename, const char *extensions)
167 ext = strrchr(filename, '.');
173 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
176 if (!strcasecmp(ext1, ext))
186 static int match_format(const char *name, const char *names)
194 namelen = strlen(name);
195 while ((p = strchr(names, ','))) {
196 len = FFMAX(p - names, namelen);
197 if (!strncasecmp(name, names, len))
201 return !strcasecmp(name, names);
204 #if FF_API_GUESS_FORMAT
205 AVOutputFormat *guess_format(const char *short_name, const char *filename,
206 const char *mime_type)
208 return av_guess_format(short_name, filename, mime_type);
212 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
213 const char *mime_type)
215 AVOutputFormat *fmt = NULL, *fmt_found;
216 int score_max, score;
218 /* specific test for image sequences */
219 #if CONFIG_IMAGE2_MUXER
220 if (!short_name && filename &&
221 av_filename_number_test(filename) &&
222 ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
223 return av_guess_format("image2", NULL, NULL);
226 /* Find the proper file type. */
229 while ((fmt = av_oformat_next(fmt))) {
231 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
233 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
235 if (filename && fmt->extensions &&
236 av_match_ext(filename, fmt->extensions)) {
239 if (score > score_max) {
247 #if FF_API_GUESS_FORMAT
248 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
249 const char *mime_type)
251 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
254 AVOutputFormat *stream_fmt;
255 char stream_format_name[64];
257 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
258 stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
268 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
269 const char *filename, const char *mime_type, enum AVMediaType type){
270 if(type == AVMEDIA_TYPE_VIDEO){
271 enum CodecID codec_id= CODEC_ID_NONE;
273 #if CONFIG_IMAGE2_MUXER
274 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
275 codec_id= ff_guess_image2_codec(filename);
278 if(codec_id == CODEC_ID_NONE)
279 codec_id= fmt->video_codec;
281 }else if(type == AVMEDIA_TYPE_AUDIO)
282 return fmt->audio_codec;
283 else if (type == AVMEDIA_TYPE_SUBTITLE)
284 return fmt->subtitle_codec;
286 return CODEC_ID_NONE;
289 AVInputFormat *av_find_input_format(const char *short_name)
291 AVInputFormat *fmt = NULL;
292 while ((fmt = av_iformat_next(fmt))) {
293 if (match_format(short_name, fmt->name))
299 #if FF_API_SYMVER && CONFIG_SHARED && HAVE_SYMVER
300 FF_SYMVER(void, av_destruct_packet_nofree, (AVPacket *pkt), "LIBAVFORMAT_52")
302 av_destruct_packet_nofree(pkt);
305 FF_SYMVER(void, av_destruct_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
307 av_destruct_packet(pkt);
310 FF_SYMVER(int, av_new_packet, (AVPacket *pkt, int size), "LIBAVFORMAT_52")
312 return av_new_packet(pkt, size);
315 FF_SYMVER(int, av_dup_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
317 return av_dup_packet(pkt);
320 FF_SYMVER(void, av_free_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
325 FF_SYMVER(void, av_init_packet, (AVPacket *pkt), "LIBAVFORMAT_52")
327 av_log(NULL, AV_LOG_WARNING, "Diverting av_*_packet function calls to libavcodec. Recompile to improve performance\n");
332 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
334 int ret= av_new_packet(pkt, size);
339 pkt->pos= avio_tell(s);
341 ret= avio_read(s, pkt->data, size);
345 av_shrink_packet(pkt, ret);
350 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
355 return av_get_packet(s, pkt, size);
356 old_size = pkt->size;
357 ret = av_grow_packet(pkt, size);
360 ret = avio_read(s, pkt->data + old_size, size);
361 av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
366 int av_filename_number_test(const char *filename)
369 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
372 AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
374 AVProbeData lpd = *pd;
375 AVInputFormat *fmt1 = NULL, *fmt;
376 int score, score_max=0;
378 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
379 int id3len = ff_id3v2_tag_len(lpd.buf);
380 if (lpd.buf_size > id3len + 16) {
382 lpd.buf_size -= id3len;
387 while ((fmt1 = av_iformat_next(fmt1))) {
388 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
391 if (fmt1->read_probe) {
392 score = fmt1->read_probe(&lpd);
393 if(!score && fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
395 } else if (fmt1->extensions) {
396 if (av_match_ext(lpd.filename, fmt1->extensions)) {
400 if (score > score_max) {
403 }else if (score == score_max)
406 *score_ret= score_max;
410 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
413 AVInputFormat *fmt= av_probe_input_format3(pd, is_opened, &score_ret);
414 if(score_ret > *score_max){
415 *score_max= score_ret;
421 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
423 return av_probe_input_format2(pd, is_opened, &score);
426 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
428 static const struct {
429 const char *name; enum CodecID id; enum AVMediaType type;
431 { "aac" , CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
432 { "ac3" , CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
433 { "dts" , CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
434 { "eac3" , CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
435 { "h264" , CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
436 { "m4v" , CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
437 { "mp3" , CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
438 { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
442 AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
446 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
447 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
448 for (i = 0; fmt_id_type[i].name; i++) {
449 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
450 st->codec->codec_id = fmt_id_type[i].id;
451 st->codec->codec_type = fmt_id_type[i].type;
459 /************************************************************/
460 /* input media file */
463 * Open a media file from an IO stream. 'fmt' must be specified.
465 int av_open_input_stream(AVFormatContext **ic_ptr,
466 AVIOContext *pb, const char *filename,
467 AVInputFormat *fmt, AVFormatParameters *ap)
471 AVFormatParameters default_ap;
475 memset(ap, 0, sizeof(default_ap));
478 if(!ap->prealloced_context)
479 ic = avformat_alloc_context();
483 err = AVERROR(ENOMEM);
488 ic->duration = AV_NOPTS_VALUE;
489 ic->start_time = AV_NOPTS_VALUE;
490 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
492 /* allocate private data */
493 if (fmt->priv_data_size > 0) {
494 ic->priv_data = av_mallocz(fmt->priv_data_size);
495 if (!ic->priv_data) {
496 err = AVERROR(ENOMEM);
500 ic->priv_data = NULL;
503 // e.g. AVFMT_NOFILE formats will not have a AVIOContext
505 ff_id3v2_read(ic, ID3v2_DEFAULT_MAGIC);
507 if (ic->iformat->read_header) {
508 err = ic->iformat->read_header(ic, ap);
513 if (pb && !ic->data_offset)
514 ic->data_offset = avio_tell(ic->pb);
516 #if FF_API_OLD_METADATA
517 ff_metadata_demux_compat(ic);
520 ic->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
527 av_freep(&ic->priv_data);
528 for(i=0;i<ic->nb_streams;i++) {
529 AVStream *st = ic->streams[i];
531 av_free(st->priv_data);
532 av_free(st->codec->extradata);
544 /** size of probe buffer, for guessing file type from file contents */
545 #define PROBE_BUF_MIN 2048
546 #define PROBE_BUF_MAX (1<<20)
548 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
549 const char *filename, void *logctx,
550 unsigned int offset, unsigned int max_probe_size)
552 AVProbeData pd = { filename ? filename : "", NULL, -offset };
553 unsigned char *buf = NULL;
554 int ret = 0, probe_size;
556 if (!max_probe_size) {
557 max_probe_size = PROBE_BUF_MAX;
558 } else if (max_probe_size > PROBE_BUF_MAX) {
559 max_probe_size = PROBE_BUF_MAX;
560 } else if (max_probe_size < PROBE_BUF_MIN) {
561 return AVERROR(EINVAL);
564 if (offset >= max_probe_size) {
565 return AVERROR(EINVAL);
568 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt && ret >= 0;
569 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
570 int ret, score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
571 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
573 if (probe_size < offset) {
577 /* read probe data */
578 buf = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
579 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
580 /* fail if error was not end of file, otherwise, lower score */
581 if (ret != AVERROR_EOF) {
586 ret = 0; /* error was end of file, nothing read */
589 pd.buf = &buf[offset];
591 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
593 /* guess file format */
594 *fmt = av_probe_input_format2(&pd, 1, &score);
596 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
597 av_log(logctx, AV_LOG_WARNING, "Format detected only with low score of %d, misdetection possible!\n", score);
599 av_log(logctx, AV_LOG_DEBUG, "Probed with size=%d and score=%d\n", probe_size, score);
605 return AVERROR_INVALIDDATA;
608 /* rewind. reuse probe buffer to avoid seeking */
609 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
615 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
618 AVFormatParameters *ap)
621 AVProbeData probe_data, *pd = &probe_data;
622 AVIOContext *pb = NULL;
623 void *logctx= ap && ap->prealloced_context ? *ic_ptr : NULL;
627 pd->filename = filename;
632 /* guess format if no file can be opened */
633 fmt = av_probe_input_format(pd, 0);
636 /* Do not open file if the format does not need it. XXX: specific
637 hack needed to handle RTSP/TCP */
638 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
639 /* if no file needed do not try to open one */
640 if ((err=avio_open(&pb, filename, AVIO_RDONLY)) < 0) {
644 ffio_set_buf_size(pb, buf_size);
646 if (!fmt && (err = av_probe_input_buffer(pb, &fmt, filename, logctx, 0, logctx ? (*ic_ptr)->probesize : 0)) < 0) {
651 /* if still no format found, error */
653 err = AVERROR_INVALIDDATA;
657 /* check filename in case an image number is expected */
658 if (fmt->flags & AVFMT_NEEDNUMBER) {
659 if (!av_filename_number_test(filename)) {
660 err = AVERROR_NUMEXPECTED;
664 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
672 if (ap && ap->prealloced_context)
679 /*******************************************************/
681 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
682 AVPacketList **plast_pktl){
683 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
688 (*plast_pktl)->next = pktl;
690 *packet_buffer = pktl;
692 /* add the packet in the buffered packet list */
698 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
704 AVPacketList *pktl = s->raw_packet_buffer;
708 if(s->streams[pkt->stream_index]->request_probe <= 0){
709 s->raw_packet_buffer = pktl->next;
710 s->raw_packet_buffer_remaining_size += pkt->size;
717 ret= s->iformat->read_packet(s, pkt);
719 if (!pktl || ret == AVERROR(EAGAIN))
721 for (i = 0; i < s->nb_streams; i++)
722 if(s->streams[i]->request_probe > 0)
723 s->streams[i]->request_probe = -1;
726 st= s->streams[pkt->stream_index];
728 switch(st->codec->codec_type){
729 case AVMEDIA_TYPE_VIDEO:
730 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
732 case AVMEDIA_TYPE_AUDIO:
733 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
735 case AVMEDIA_TYPE_SUBTITLE:
736 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
740 if(!pktl && st->request_probe <= 0)
743 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
744 s->raw_packet_buffer_remaining_size -= pkt->size;
746 if(st->request_probe>0){
747 AVProbeData *pd = &st->probe_data;
749 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
752 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
753 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
754 pd->buf_size += pkt->size;
755 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
757 end= s->raw_packet_buffer_remaining_size <= 0
758 || st->probe_packets<=0;
760 if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
761 int score= set_codec_from_probe_data(s, st, pd);
762 if( (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
766 st->request_probe= -1;
767 if(st->codec->codec_id != CODEC_ID_NONE){
768 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
770 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
777 /**********************************************************/
780 * Get the number of samples of an audio frame. Return -1 on error.
782 static int get_audio_frame_size(AVCodecContext *enc, int size)
786 if(enc->codec_id == CODEC_ID_VORBIS)
789 if (enc->frame_size <= 1) {
790 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
792 if (bits_per_sample) {
793 if (enc->channels == 0)
795 frame_size = (size << 3) / (bits_per_sample * enc->channels);
797 /* used for example by ADPCM codecs */
798 if (enc->bit_rate == 0)
800 frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
803 frame_size = enc->frame_size;
810 * Return the frame duration in seconds. Return 0 if not available.
812 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
813 AVCodecParserContext *pc, AVPacket *pkt)
819 switch(st->codec->codec_type) {
820 case AVMEDIA_TYPE_VIDEO:
821 if(st->time_base.num*1000LL > st->time_base.den){
822 *pnum = st->time_base.num;
823 *pden = st->time_base.den;
824 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
825 *pnum = st->codec->time_base.num;
826 *pden = st->codec->time_base.den;
827 if (pc && pc->repeat_pict) {
828 *pnum = (*pnum) * (1 + pc->repeat_pict);
830 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
831 //Thus if we have no parser in such case leave duration undefined.
832 if(st->codec->ticks_per_frame>1 && !pc){
837 case AVMEDIA_TYPE_AUDIO:
838 frame_size = get_audio_frame_size(st->codec, pkt->size);
839 if (frame_size <= 0 || st->codec->sample_rate <= 0)
842 *pden = st->codec->sample_rate;
849 static int is_intra_only(AVCodecContext *enc){
850 if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
852 }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
853 switch(enc->codec_id){
855 case CODEC_ID_MJPEGB:
857 case CODEC_ID_RAWVIDEO:
858 case CODEC_ID_DVVIDEO:
859 case CODEC_ID_HUFFYUV:
860 case CODEC_ID_FFVHUFF:
865 case CODEC_ID_JPEG2000:
873 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
874 int64_t dts, int64_t pts)
876 AVStream *st= s->streams[stream_index];
877 AVPacketList *pktl= s->packet_buffer;
879 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
882 st->first_dts= dts - st->cur_dts;
885 for(; pktl; pktl= pktl->next){
886 if(pktl->pkt.stream_index != stream_index)
888 //FIXME think more about this check
889 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
890 pktl->pkt.pts += st->first_dts;
892 if(pktl->pkt.dts != AV_NOPTS_VALUE)
893 pktl->pkt.dts += st->first_dts;
895 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
896 st->start_time= pktl->pkt.pts;
898 if (st->start_time == AV_NOPTS_VALUE)
899 st->start_time = pts;
902 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
904 AVPacketList *pktl= s->packet_buffer;
907 if(st->first_dts != AV_NOPTS_VALUE){
908 cur_dts= st->first_dts;
909 for(; pktl; pktl= pktl->next){
910 if(pktl->pkt.stream_index == pkt->stream_index){
911 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
913 cur_dts -= pkt->duration;
916 pktl= s->packet_buffer;
917 st->first_dts = cur_dts;
918 }else if(st->cur_dts)
921 for(; pktl; pktl= pktl->next){
922 if(pktl->pkt.stream_index != pkt->stream_index)
924 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
925 && !pktl->pkt.duration){
926 pktl->pkt.dts= cur_dts;
927 if(!st->codec->has_b_frames)
928 pktl->pkt.pts= cur_dts;
929 cur_dts += pkt->duration;
930 pktl->pkt.duration= pkt->duration;
934 if(st->first_dts == AV_NOPTS_VALUE)
935 st->cur_dts= cur_dts;
938 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
939 AVCodecParserContext *pc, AVPacket *pkt)
941 int num, den, presentation_delayed, delay, i;
944 if (s->flags & AVFMT_FLAG_NOFILLIN)
947 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
948 pkt->dts= AV_NOPTS_VALUE;
950 if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)
951 //FIXME Set low_delay = 0 when has_b_frames = 1
952 st->codec->has_b_frames = 1;
954 /* do we have a video B-frame ? */
955 delay= st->codec->has_b_frames;
956 presentation_delayed = 0;
958 // ignore delay caused by frame threading so that the mpeg2-without-dts
959 // warning will not trigger
960 if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
961 delay -= st->codec->thread_count-1;
963 /* XXX: need has_b_frame, but cannot get it if the codec is
966 pc && pc->pict_type != FF_B_TYPE)
967 presentation_delayed = 1;
969 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
970 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
971 pkt->dts -= 1LL<<st->pts_wrap_bits;
974 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
975 // we take the conservative approach and discard both
976 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
977 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
978 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination\n");
979 pkt->dts= pkt->pts= AV_NOPTS_VALUE;
982 if (pkt->duration == 0) {
983 compute_frame_duration(&num, &den, st, pc, pkt);
985 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
987 if(pkt->duration != 0 && s->packet_buffer)
988 update_initial_durations(s, st, pkt);
992 /* correct timestamps with byte offset if demuxers only have timestamps
993 on packet boundaries */
994 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
995 /* this will estimate bitrate based on this frame's duration and size */
996 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
997 if(pkt->pts != AV_NOPTS_VALUE)
999 if(pkt->dts != AV_NOPTS_VALUE)
1003 if (pc && pc->dts_sync_point >= 0) {
1004 // we have synchronization info from the parser
1005 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
1007 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
1008 if (pkt->dts != AV_NOPTS_VALUE) {
1009 // got DTS from the stream, update reference timestamp
1010 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
1011 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1012 } else if (st->reference_dts != AV_NOPTS_VALUE) {
1013 // compute DTS based on reference timestamp
1014 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
1015 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1017 if (pc->dts_sync_point > 0)
1018 st->reference_dts = pkt->dts; // new reference
1022 /* This may be redundant, but it should not hurt. */
1023 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
1024 presentation_delayed = 1;
1026 // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
1027 /* interpolate PTS and DTS if they are not present */
1028 //We skip H264 currently because delay and has_b_frames are not reliably set
1029 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
1030 if (presentation_delayed) {
1031 /* DTS = decompression timestamp */
1032 /* PTS = presentation timestamp */
1033 if (pkt->dts == AV_NOPTS_VALUE)
1034 pkt->dts = st->last_IP_pts;
1035 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
1036 if (pkt->dts == AV_NOPTS_VALUE)
1037 pkt->dts = st->cur_dts;
1039 /* this is tricky: the dts must be incremented by the duration
1040 of the frame we are displaying, i.e. the last I- or P-frame */
1041 if (st->last_IP_duration == 0)
1042 st->last_IP_duration = pkt->duration;
1043 if(pkt->dts != AV_NOPTS_VALUE)
1044 st->cur_dts = pkt->dts + st->last_IP_duration;
1045 st->last_IP_duration = pkt->duration;
1046 st->last_IP_pts= pkt->pts;
1047 /* cannot compute PTS if not present (we can compute it only
1048 by knowing the future */
1049 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1050 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1051 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1052 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1053 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1054 pkt->pts += pkt->duration;
1055 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
1059 /* presentation is not delayed : PTS and DTS are the same */
1060 if(pkt->pts == AV_NOPTS_VALUE)
1061 pkt->pts = pkt->dts;
1062 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1063 if(pkt->pts == AV_NOPTS_VALUE)
1064 pkt->pts = st->cur_dts;
1065 pkt->dts = pkt->pts;
1066 if(pkt->pts != AV_NOPTS_VALUE)
1067 st->cur_dts = pkt->pts + pkt->duration;
1071 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1072 st->pts_buffer[0]= pkt->pts;
1073 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1074 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1075 if(pkt->dts == AV_NOPTS_VALUE)
1076 pkt->dts= st->pts_buffer[0];
1077 if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here
1078 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1080 if(pkt->dts > st->cur_dts)
1081 st->cur_dts = pkt->dts;
1084 // av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);
1087 if(is_intra_only(st->codec))
1088 pkt->flags |= AV_PKT_FLAG_KEY;
1091 /* keyframe computation */
1092 if (pc->key_frame == 1)
1093 pkt->flags |= AV_PKT_FLAG_KEY;
1094 else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)
1095 pkt->flags |= AV_PKT_FLAG_KEY;
1098 pkt->convergence_duration = pc->convergence_duration;
1102 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1107 av_init_packet(pkt);
1110 /* select current input stream component */
1113 if (!st->need_parsing || !st->parser) {
1114 /* no parsing needed: we just output the packet as is */
1115 /* raw data support */
1116 *pkt = st->cur_pkt; st->cur_pkt.data= NULL;
1117 compute_pkt_fields(s, st, NULL, pkt);
1119 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1120 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1121 ff_reduce_index(s, st->index);
1122 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1125 } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1126 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1127 st->cur_ptr, st->cur_len,
1128 st->cur_pkt.pts, st->cur_pkt.dts,
1130 st->cur_pkt.pts = AV_NOPTS_VALUE;
1131 st->cur_pkt.dts = AV_NOPTS_VALUE;
1132 /* increment read pointer */
1136 /* return packet if any */
1140 pkt->stream_index = st->index;
1141 pkt->pts = st->parser->pts;
1142 pkt->dts = st->parser->dts;
1143 pkt->pos = st->parser->pos;
1144 if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1146 pkt->destruct= st->cur_pkt.destruct;
1147 st->cur_pkt.destruct= NULL;
1148 st->cur_pkt.data = NULL;
1149 assert(st->cur_len == 0);
1151 pkt->destruct = NULL;
1153 compute_pkt_fields(s, st, st->parser, pkt);
1155 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1156 ff_reduce_index(s, st->index);
1157 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1158 0, 0, AVINDEX_KEYFRAME);
1165 av_free_packet(&st->cur_pkt);
1170 /* read next packet */
1171 ret = av_read_packet(s, &cur_pkt);
1173 if (ret == AVERROR(EAGAIN))
1175 /* return the last frames, if any */
1176 for(i = 0; i < s->nb_streams; i++) {
1178 if (st->parser && st->need_parsing) {
1179 av_parser_parse2(st->parser, st->codec,
1180 &pkt->data, &pkt->size,
1182 AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1188 /* no more packets: really terminate parsing */
1191 st = s->streams[cur_pkt.stream_index];
1192 st->cur_pkt= cur_pkt;
1194 if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1195 st->cur_pkt.dts != AV_NOPTS_VALUE &&
1196 st->cur_pkt.pts < st->cur_pkt.dts){
1197 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1198 st->cur_pkt.stream_index,
1202 // av_free_packet(&st->cur_pkt);
1206 if(s->debug & FF_FDEBUG_TS)
1207 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1208 st->cur_pkt.stream_index,
1212 st->cur_pkt.duration,
1216 st->cur_ptr = st->cur_pkt.data;
1217 st->cur_len = st->cur_pkt.size;
1218 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1219 st->parser = av_parser_init(st->codec->codec_id);
1221 /* no parser available: just output the raw packets */
1222 st->need_parsing = AVSTREAM_PARSE_NONE;
1223 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1224 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1225 }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1226 st->parser->flags |= PARSER_FLAG_ONCE;
1231 if(s->debug & FF_FDEBUG_TS)
1232 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1243 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1247 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1250 pktl = s->packet_buffer;
1252 AVPacket *next_pkt= &pktl->pkt;
1254 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1255 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1256 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1257 if( pktl->pkt.stream_index == next_pkt->stream_index
1258 && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1259 && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1260 next_pkt->pts= pktl->pkt.dts;
1264 pktl = s->packet_buffer;
1267 if( next_pkt->pts != AV_NOPTS_VALUE
1268 || next_pkt->dts == AV_NOPTS_VALUE
1270 /* read packet from packet buffer, if there is data */
1272 s->packet_buffer = pktl->next;
1278 int ret= av_read_frame_internal(s, pkt);
1280 if(pktl && ret != AVERROR(EAGAIN)){
1287 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1288 &s->packet_buffer_end)) < 0)
1289 return AVERROR(ENOMEM);
1291 assert(!s->packet_buffer);
1292 return av_read_frame_internal(s, pkt);
1297 /* XXX: suppress the packet queue */
1298 static void flush_packet_queue(AVFormatContext *s)
1303 pktl = s->packet_buffer;
1306 s->packet_buffer = pktl->next;
1307 av_free_packet(&pktl->pkt);
1310 while(s->raw_packet_buffer){
1311 pktl = s->raw_packet_buffer;
1312 s->raw_packet_buffer = pktl->next;
1313 av_free_packet(&pktl->pkt);
1316 s->packet_buffer_end=
1317 s->raw_packet_buffer_end= NULL;
1318 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1321 /*******************************************************/
1324 int av_find_default_stream_index(AVFormatContext *s)
1326 int first_audio_index = -1;
1330 if (s->nb_streams <= 0)
1332 for(i = 0; i < s->nb_streams; i++) {
1334 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1337 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1338 first_audio_index = i;
1340 return first_audio_index >= 0 ? first_audio_index : 0;
1344 * Flush the frame reader.
1346 void ff_read_frame_flush(AVFormatContext *s)
1351 flush_packet_queue(s);
1355 /* for each stream, reset read state */
1356 for(i = 0; i < s->nb_streams; i++) {
1360 av_parser_close(st->parser);
1362 av_free_packet(&st->cur_pkt);
1364 st->last_IP_pts = AV_NOPTS_VALUE;
1365 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1366 st->reference_dts = AV_NOPTS_VALUE;
1371 st->probe_packets = MAX_PROBE_PACKETS;
1373 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1374 st->pts_buffer[j]= AV_NOPTS_VALUE;
1378 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1381 for(i = 0; i < s->nb_streams; i++) {
1382 AVStream *st = s->streams[i];
1384 st->cur_dts = av_rescale(timestamp,
1385 st->time_base.den * (int64_t)ref_st->time_base.num,
1386 st->time_base.num * (int64_t)ref_st->time_base.den);
1390 void ff_reduce_index(AVFormatContext *s, int stream_index)
1392 AVStream *st= s->streams[stream_index];
1393 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1395 if((unsigned)st->nb_index_entries >= max_entries){
1397 for(i=0; 2*i<st->nb_index_entries; i++)
1398 st->index_entries[i]= st->index_entries[2*i];
1399 st->nb_index_entries= i;
1403 int ff_add_index_entry(AVIndexEntry **index_entries,
1404 int *nb_index_entries,
1405 unsigned int *index_entries_allocated_size,
1406 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1408 AVIndexEntry *entries, *ie;
1411 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1414 entries = av_fast_realloc(*index_entries,
1415 index_entries_allocated_size,
1416 (*nb_index_entries + 1) *
1417 sizeof(AVIndexEntry));
1421 *index_entries= entries;
1423 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1426 index= (*nb_index_entries)++;
1427 ie= &entries[index];
1428 assert(index==0 || ie[-1].timestamp < timestamp);
1430 ie= &entries[index];
1431 if(ie->timestamp != timestamp){
1432 if(ie->timestamp <= timestamp)
1434 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1435 (*nb_index_entries)++;
1436 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1437 distance= ie->min_distance;
1441 ie->timestamp = timestamp;
1442 ie->min_distance= distance;
1449 int av_add_index_entry(AVStream *st,
1450 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1452 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1453 &st->index_entries_allocated_size, pos,
1454 timestamp, size, distance, flags);
1457 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1458 int64_t wanted_timestamp, int flags)
1466 //optimize appending index entries at the end
1467 if(b && entries[b-1].timestamp < wanted_timestamp)
1472 timestamp = entries[m].timestamp;
1473 if(timestamp >= wanted_timestamp)
1475 if(timestamp <= wanted_timestamp)
1478 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1480 if(!(flags & AVSEEK_FLAG_ANY)){
1481 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1482 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1491 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1494 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1495 wanted_timestamp, flags);
1500 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1501 AVInputFormat *avif= s->iformat;
1502 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1503 int64_t ts_min, ts_max, ts;
1508 if (stream_index < 0)
1512 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1516 ts_min= AV_NOPTS_VALUE;
1517 pos_limit= -1; //gcc falsely says it may be uninitialized
1519 st= s->streams[stream_index];
1520 if(st->index_entries){
1523 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()
1524 index= FFMAX(index, 0);
1525 e= &st->index_entries[index];
1527 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1529 ts_min= e->timestamp;
1531 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1538 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1539 assert(index < st->nb_index_entries);
1541 e= &st->index_entries[index];
1542 assert(e->timestamp >= target_ts);
1544 ts_max= e->timestamp;
1545 pos_limit= pos_max - e->min_distance;
1547 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1548 pos_max,pos_limit, ts_max);
1553 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1558 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1561 av_update_cur_dts(s, st, ts);
1566 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1568 int64_t start_pos, filesize;
1572 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1575 if(ts_min == AV_NOPTS_VALUE){
1576 pos_min = s->data_offset;
1577 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1578 if (ts_min == AV_NOPTS_VALUE)
1582 if(ts_max == AV_NOPTS_VALUE){
1584 filesize = avio_size(s->pb);
1585 pos_max = filesize - 1;
1588 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1590 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1591 if (ts_max == AV_NOPTS_VALUE)
1595 int64_t tmp_pos= pos_max + 1;
1596 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1597 if(tmp_ts == AV_NOPTS_VALUE)
1601 if(tmp_pos >= filesize)
1607 if(ts_min > ts_max){
1609 }else if(ts_min == ts_max){
1614 while (pos_min < pos_limit) {
1616 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1620 assert(pos_limit <= pos_max);
1623 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1624 // interpolate position (better than dichotomy)
1625 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1626 + pos_min - approximate_keyframe_distance;
1627 }else if(no_change==1){
1628 // bisection, if interpolation failed to change min or max pos last time
1629 pos = (pos_min + pos_limit)>>1;
1631 /* linear search if bisection failed, can only happen if there
1632 are very few or no keyframes between min/max */
1637 else if(pos > pos_limit)
1641 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1647 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1648 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit,
1649 start_pos, no_change);
1651 if(ts == AV_NOPTS_VALUE){
1652 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1655 assert(ts != AV_NOPTS_VALUE);
1656 if (target_ts <= ts) {
1657 pos_limit = start_pos - 1;
1661 if (target_ts >= ts) {
1667 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1668 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1671 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1673 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1674 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1675 pos, ts_min, target_ts, ts_max);
1681 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1682 int64_t pos_min, pos_max;
1686 if (stream_index < 0)
1689 st= s->streams[stream_index];
1692 pos_min = s->data_offset;
1693 pos_max = avio_size(s->pb) - 1;
1695 if (pos < pos_min) pos= pos_min;
1696 else if(pos > pos_max) pos= pos_max;
1698 avio_seek(s->pb, pos, SEEK_SET);
1701 av_update_cur_dts(s, st, ts);
1706 static int av_seek_frame_generic(AVFormatContext *s,
1707 int stream_index, int64_t timestamp, int flags)
1714 st = s->streams[stream_index];
1716 index = av_index_search_timestamp(st, timestamp, flags);
1718 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1721 if(index < 0 || index==st->nb_index_entries-1){
1725 if(st->nb_index_entries){
1726 assert(st->index_entries);
1727 ie= &st->index_entries[st->nb_index_entries-1];
1728 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1730 av_update_cur_dts(s, st, ie->timestamp);
1732 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1738 ret = av_read_frame(s, &pkt);
1739 }while(ret == AVERROR(EAGAIN));
1742 av_free_packet(&pkt);
1743 if(stream_index == pkt.stream_index){
1744 if((pkt.flags & AV_PKT_FLAG_KEY) && pkt.dts > timestamp)
1748 index = av_index_search_timestamp(st, timestamp, flags);
1753 ff_read_frame_flush(s);
1754 if (s->iformat->read_seek){
1755 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1758 ie = &st->index_entries[index];
1759 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1761 av_update_cur_dts(s, st, ie->timestamp);
1766 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1771 ff_read_frame_flush(s);
1773 if(flags & AVSEEK_FLAG_BYTE)
1774 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1776 if(stream_index < 0){
1777 stream_index= av_find_default_stream_index(s);
1778 if(stream_index < 0)
1781 st= s->streams[stream_index];
1782 /* timestamp for default must be expressed in AV_TIME_BASE units */
1783 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1786 /* first, we try the format specific seek */
1787 if (s->iformat->read_seek)
1788 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1795 if(s->iformat->read_timestamp)
1796 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1798 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1801 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1803 if(min_ts > ts || max_ts < ts)
1806 ff_read_frame_flush(s);
1808 if (s->iformat->read_seek2)
1809 return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1811 if(s->iformat->read_timestamp){
1812 //try to seek via read_timestamp()
1815 //Fallback to old API if new is not implemented but old is
1816 //Note the old has somewat different sematics
1817 if(s->iformat->read_seek || 1)
1818 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1820 // try some generic seek like av_seek_frame_generic() but with new ts semantics
1823 /*******************************************************/
1826 * Return TRUE if the stream has accurate duration in any stream.
1828 * @return TRUE if the stream has accurate duration for at least one component.
1830 static int av_has_duration(AVFormatContext *ic)
1835 for(i = 0;i < ic->nb_streams; i++) {
1836 st = ic->streams[i];
1837 if (st->duration != AV_NOPTS_VALUE)
1844 * Estimate the stream timings from the one of each components.
1846 * Also computes the global bitrate if possible.
1848 static void av_update_stream_timings(AVFormatContext *ic)
1850 int64_t start_time, start_time1, end_time, end_time1;
1851 int64_t duration, duration1;
1855 start_time = INT64_MAX;
1856 end_time = INT64_MIN;
1857 duration = INT64_MIN;
1858 for(i = 0;i < ic->nb_streams; i++) {
1859 st = ic->streams[i];
1860 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1861 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1862 if (start_time1 < start_time)
1863 start_time = start_time1;
1864 if (st->duration != AV_NOPTS_VALUE) {
1865 end_time1 = start_time1
1866 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1867 if (end_time1 > end_time)
1868 end_time = end_time1;
1871 if (st->duration != AV_NOPTS_VALUE) {
1872 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1873 if (duration1 > duration)
1874 duration = duration1;
1877 if (start_time != INT64_MAX) {
1878 ic->start_time = start_time;
1879 if (end_time != INT64_MIN) {
1880 if (end_time - start_time > duration)
1881 duration = end_time - start_time;
1884 if (duration != INT64_MIN) {
1885 ic->duration = duration;
1886 if (ic->file_size > 0) {
1887 /* compute the bitrate */
1888 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1889 (double)ic->duration;
1894 static void fill_all_stream_timings(AVFormatContext *ic)
1899 av_update_stream_timings(ic);
1900 for(i = 0;i < ic->nb_streams; i++) {
1901 st = ic->streams[i];
1902 if (st->start_time == AV_NOPTS_VALUE) {
1903 if(ic->start_time != AV_NOPTS_VALUE)
1904 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1905 if(ic->duration != AV_NOPTS_VALUE)
1906 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1911 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1913 int64_t filesize, duration;
1917 /* if bit_rate is already set, we believe it */
1918 if (ic->bit_rate <= 0) {
1920 for(i=0;i<ic->nb_streams;i++) {
1921 st = ic->streams[i];
1922 if (st->codec->bit_rate > 0)
1923 bit_rate += st->codec->bit_rate;
1925 ic->bit_rate = bit_rate;
1928 /* if duration is already set, we believe it */
1929 if (ic->duration == AV_NOPTS_VALUE &&
1930 ic->bit_rate != 0 &&
1931 ic->file_size != 0) {
1932 filesize = ic->file_size;
1934 for(i = 0; i < ic->nb_streams; i++) {
1935 st = ic->streams[i];
1936 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1937 if (st->duration == AV_NOPTS_VALUE)
1938 st->duration = duration;
1944 #define DURATION_MAX_READ_SIZE 250000
1945 #define DURATION_MAX_RETRY 3
1947 /* only usable for MPEG-PS streams */
1948 static void av_estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
1950 AVPacket pkt1, *pkt = &pkt1;
1952 int read_size, i, ret;
1954 int64_t filesize, offset, duration;
1959 /* flush packet queue */
1960 flush_packet_queue(ic);
1962 for (i=0; i<ic->nb_streams; i++) {
1963 st = ic->streams[i];
1964 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
1965 av_log(st->codec, AV_LOG_WARNING, "start time is not set in av_estimate_timings_from_pts\n");
1968 av_parser_close(st->parser);
1970 av_free_packet(&st->cur_pkt);
1974 /* estimate the end time (duration) */
1975 /* XXX: may need to support wrapping */
1976 filesize = ic->file_size;
1977 end_time = AV_NOPTS_VALUE;
1979 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
1983 avio_seek(ic->pb, offset, SEEK_SET);
1986 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
1990 ret = av_read_packet(ic, pkt);
1991 }while(ret == AVERROR(EAGAIN));
1994 read_size += pkt->size;
1995 st = ic->streams[pkt->stream_index];
1996 if (pkt->pts != AV_NOPTS_VALUE &&
1997 (st->start_time != AV_NOPTS_VALUE ||
1998 st->first_dts != AV_NOPTS_VALUE)) {
1999 duration = end_time = pkt->pts;
2000 if (st->start_time != AV_NOPTS_VALUE) duration -= st->start_time;
2001 else duration -= st->first_dts;
2003 duration += 1LL<<st->pts_wrap_bits;
2005 if (st->duration == AV_NOPTS_VALUE ||
2006 st->duration < duration)
2007 st->duration = duration;
2010 av_free_packet(pkt);
2012 }while( end_time==AV_NOPTS_VALUE
2013 && filesize > (DURATION_MAX_READ_SIZE<<retry)
2014 && ++retry <= DURATION_MAX_RETRY);
2016 fill_all_stream_timings(ic);
2018 avio_seek(ic->pb, old_offset, SEEK_SET);
2019 for (i=0; i<ic->nb_streams; i++) {
2021 st->cur_dts= st->first_dts;
2022 st->last_IP_pts = AV_NOPTS_VALUE;
2023 st->reference_dts = AV_NOPTS_VALUE;
2027 static void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
2031 /* get the file size, if possible */
2032 if (ic->iformat->flags & AVFMT_NOFILE) {
2035 file_size = avio_size(ic->pb);
2039 ic->file_size = file_size;
2041 if ((!strcmp(ic->iformat->name, "mpeg") ||
2042 !strcmp(ic->iformat->name, "mpegts")) &&
2043 file_size && ic->pb->seekable) {
2044 /* get accurate estimate from the PTSes */
2045 av_estimate_timings_from_pts(ic, old_offset);
2046 } else if (av_has_duration(ic)) {
2047 /* at least one component has timings - we use them for all
2049 fill_all_stream_timings(ic);
2051 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2052 /* less precise: use bitrate info */
2053 av_estimate_timings_from_bit_rate(ic);
2055 av_update_stream_timings(ic);
2061 for(i = 0;i < ic->nb_streams; i++) {
2062 st = ic->streams[i];
2063 printf("%d: start_time: %0.3f duration: %0.3f\n",
2064 i, (double)st->start_time / AV_TIME_BASE,
2065 (double)st->duration / AV_TIME_BASE);
2067 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2068 (double)ic->start_time / AV_TIME_BASE,
2069 (double)ic->duration / AV_TIME_BASE,
2070 ic->bit_rate / 1000);
2075 static int has_codec_parameters(AVCodecContext *enc)
2078 switch(enc->codec_type) {
2079 case AVMEDIA_TYPE_AUDIO:
2080 val = enc->sample_rate && enc->channels && enc->sample_fmt != AV_SAMPLE_FMT_NONE;
2081 if(!enc->frame_size &&
2082 (enc->codec_id == CODEC_ID_VORBIS ||
2083 enc->codec_id == CODEC_ID_AAC ||
2084 enc->codec_id == CODEC_ID_MP1 ||
2085 enc->codec_id == CODEC_ID_MP2 ||
2086 enc->codec_id == CODEC_ID_MP3 ||
2087 enc->codec_id == CODEC_ID_SPEEX))
2090 case AVMEDIA_TYPE_VIDEO:
2091 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
2097 return enc->codec_id != CODEC_ID_NONE && val != 0;
2100 static int has_decode_delay_been_guessed(AVStream *st)
2102 return st->codec->codec_id != CODEC_ID_H264 ||
2103 st->codec_info_nb_frames >= 6 + st->codec->has_b_frames;
2106 static int try_decode_frame(AVStream *st, AVPacket *avpkt)
2110 int got_picture, data_size, ret=0;
2113 if(!st->codec->codec){
2114 codec = avcodec_find_decoder(st->codec->codec_id);
2117 ret = avcodec_open(st->codec, codec);
2122 if(!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st)){
2123 switch(st->codec->codec_type) {
2124 case AVMEDIA_TYPE_VIDEO:
2125 avcodec_get_frame_defaults(&picture);
2126 ret = avcodec_decode_video2(st->codec, &picture,
2127 &got_picture, avpkt);
2129 case AVMEDIA_TYPE_AUDIO:
2130 data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
2131 samples = av_malloc(data_size);
2134 ret = avcodec_decode_audio3(st->codec, samples,
2146 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2148 while (tags->id != CODEC_ID_NONE) {
2156 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2159 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2160 if(tag == tags[i].tag)
2163 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2164 if (ff_toupper4(tag) == ff_toupper4(tags[i].tag))
2167 return CODEC_ID_NONE;
2170 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2173 for(i=0; tags && tags[i]; i++){
2174 int tag= ff_codec_get_tag(tags[i], id);
2180 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2183 for(i=0; tags && tags[i]; i++){
2184 enum CodecID id= ff_codec_get_id(tags[i], tag);
2185 if(id!=CODEC_ID_NONE) return id;
2187 return CODEC_ID_NONE;
2190 static void compute_chapters_end(AVFormatContext *s)
2193 int64_t max_time = s->duration + (s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time;
2195 for (i = 0; i < s->nb_chapters; i++)
2196 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2197 AVChapter *ch = s->chapters[i];
2198 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2201 for (j = 0; j < s->nb_chapters; j++) {
2202 AVChapter *ch1 = s->chapters[j];
2203 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2204 if (j != i && next_start > ch->start && next_start < end)
2207 ch->end = (end == INT64_MAX) ? ch->start : end;
2211 static int get_std_framerate(int i){
2212 if(i<60*12) return i*1001;
2213 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2217 * Is the time base unreliable.
2218 * This is a heuristic to balance between quick acceptance of the values in
2219 * the headers vs. some extra checks.
2220 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2221 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2222 * And there are "variable" fps files this needs to detect as well.
2224 static int tb_unreliable(AVCodecContext *c){
2225 if( c->time_base.den >= 101L*c->time_base.num
2226 || c->time_base.den < 5L*c->time_base.num
2227 /* || c->codec_tag == AV_RL32("DIVX")
2228 || c->codec_tag == AV_RL32("XVID")*/
2229 || c->codec_id == CODEC_ID_MPEG2VIDEO
2230 || c->codec_id == CODEC_ID_H264
2236 int av_find_stream_info(AVFormatContext *ic)
2238 int i, count, ret, read_size, j;
2240 AVPacket pkt1, *pkt;
2241 int64_t old_offset = avio_tell(ic->pb);
2243 for(i=0;i<ic->nb_streams;i++) {
2245 st = ic->streams[i];
2246 if (st->codec->codec_id == CODEC_ID_AAC) {
2247 st->codec->sample_rate = 0;
2248 st->codec->frame_size = 0;
2249 st->codec->channels = 0;
2251 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2252 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2253 /* if(!st->time_base.num)
2255 if(!st->codec->time_base.num)
2256 st->codec->time_base= st->time_base;
2258 //only for the split stuff
2259 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2260 st->parser = av_parser_init(st->codec->codec_id);
2261 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2262 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2265 assert(!st->codec->codec);
2266 codec = avcodec_find_decoder(st->codec->codec_id);
2268 /* Force decoding of at least one frame of codec data
2269 * this makes sure the codec initializes the channel configuration
2270 * and does not trust the values from the container.
2272 if (codec && codec->capabilities & CODEC_CAP_CHANNEL_CONF)
2273 st->codec->channels = 0;
2275 /* Ensure that subtitle_header is properly set. */
2276 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2277 && codec && !st->codec->codec)
2278 avcodec_open(st->codec, codec);
2280 //try to just open decoders, in case this is enough to get parameters
2281 if(!has_codec_parameters(st->codec)){
2282 if (codec && !st->codec->codec)
2283 avcodec_open(st->codec, codec);
2287 for (i=0; i<ic->nb_streams; i++) {
2288 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2294 if(url_interrupt_cb()){
2296 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2300 /* check if one codec still needs to be handled */
2301 for(i=0;i<ic->nb_streams;i++) {
2302 int fps_analyze_framecount = 20;
2304 st = ic->streams[i];
2305 if (!has_codec_parameters(st->codec))
2307 /* if the timebase is coarse (like the usual millisecond precision
2308 of mkv), we need to analyze more frames to reliably arrive at
2310 if (av_q2d(st->time_base) > 0.0005)
2311 fps_analyze_framecount *= 2;
2312 /* variable fps and no guess at the real fps */
2313 if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2314 && st->info->duration_count < fps_analyze_framecount
2315 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2317 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2319 if(st->first_dts == AV_NOPTS_VALUE)
2322 if (i == ic->nb_streams) {
2323 /* NOTE: if the format has no header, then we need to read
2324 some packets to get most of the streams, so we cannot
2326 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2327 /* if we found the info for all the codecs, we can stop */
2329 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2333 /* we did not get all the codec info, but we read too much data */
2334 if (read_size >= ic->probesize) {
2336 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2340 /* NOTE: a new stream can be added there if no header in file
2341 (AVFMTCTX_NOHEADER) */
2342 ret = av_read_frame_internal(ic, &pkt1);
2343 if (ret < 0 && ret != AVERROR(EAGAIN)) {
2345 ret = -1; /* we could not have all the codec parameters before EOF */
2346 for(i=0;i<ic->nb_streams;i++) {
2347 st = ic->streams[i];
2348 if (!has_codec_parameters(st->codec)){
2350 avcodec_string(buf, sizeof(buf), st->codec, 0);
2351 av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2359 if (ret == AVERROR(EAGAIN))
2362 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2363 if ((ret = av_dup_packet(pkt)) < 0)
2364 goto find_stream_info_err;
2366 read_size += pkt->size;
2368 st = ic->streams[pkt->stream_index];
2369 if (st->codec_info_nb_frames>1) {
2370 if (st->time_base.den > 0 && av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2371 av_log(ic, AV_LOG_WARNING, "max_analyze_duration reached\n");
2374 st->info->codec_info_duration += pkt->duration;
2377 int64_t last = st->info->last_dts;
2378 int64_t duration= pkt->dts - last;
2380 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2381 double dur= duration * av_q2d(st->time_base);
2383 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2384 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2385 if (st->info->duration_count < 2)
2386 memset(st->info->duration_error, 0, sizeof(st->info->duration_error));
2387 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error); i++) {
2388 int framerate= get_std_framerate(i);
2389 int ticks= lrintf(dur*framerate/(1001*12));
2390 double error= dur - ticks*1001*12/(double)framerate;
2391 st->info->duration_error[i] += error*error;
2393 st->info->duration_count++;
2394 // ignore the first 4 values, they might have some random jitter
2395 if (st->info->duration_count > 3)
2396 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2398 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2399 st->info->last_dts = pkt->dts;
2401 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2402 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2404 st->codec->extradata_size= i;
2405 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2406 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2407 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2411 /* if still no information, we try to open the codec and to
2412 decompress the frame. We try to avoid that in most cases as
2413 it takes longer and uses more memory. For MPEG-4, we need to
2414 decompress for QuickTime. */
2415 if (!has_codec_parameters(st->codec) || !has_decode_delay_been_guessed(st))
2416 try_decode_frame(st, pkt);
2418 st->codec_info_nb_frames++;
2422 // close codecs which were opened in try_decode_frame()
2423 for(i=0;i<ic->nb_streams;i++) {
2424 st = ic->streams[i];
2425 if(st->codec->codec)
2426 avcodec_close(st->codec);
2428 for(i=0;i<ic->nb_streams;i++) {
2429 st = ic->streams[i];
2430 if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2431 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2432 (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2433 st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2434 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2435 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
2436 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2437 if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
2438 st->codec->codec_tag= tag;
2441 // the check for tb_unreliable() is not completely correct, since this is not about handling
2442 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2443 // ipmovie.c produces.
2444 if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
2445 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);
2446 if (st->info->duration_count && !st->r_frame_rate.num
2447 && tb_unreliable(st->codec) /*&&
2448 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2449 st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2451 double best_error= 2*av_q2d(st->time_base);
2452 best_error = best_error*best_error*st->info->duration_count*1000*12*30;
2454 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error); j++) {
2455 double error = st->info->duration_error[j] * get_std_framerate(j);
2456 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2457 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2458 if(error < best_error){
2460 num = get_std_framerate(j);
2463 // do not increase frame rate by more than 1 % in order to match a standard rate.
2464 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2465 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2468 if (!st->r_frame_rate.num){
2469 if( st->codec->time_base.den * (int64_t)st->time_base.num
2470 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2471 st->r_frame_rate.num = st->codec->time_base.den;
2472 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2474 st->r_frame_rate.num = st->time_base.den;
2475 st->r_frame_rate.den = st->time_base.num;
2478 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2479 if(!st->codec->bits_per_coded_sample)
2480 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2481 // set stream disposition based on audio service type
2482 switch (st->codec->audio_service_type) {
2483 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2484 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2485 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2486 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2487 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2488 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2489 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2490 st->disposition = AV_DISPOSITION_COMMENT; break;
2491 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2492 st->disposition = AV_DISPOSITION_KARAOKE; break;
2497 av_estimate_timings(ic, old_offset);
2499 compute_chapters_end(ic);
2502 /* correct DTS for B-frame streams with no timestamps */
2503 for(i=0;i<ic->nb_streams;i++) {
2504 st = ic->streams[i];
2505 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2507 ppktl = &ic->packet_buffer;
2509 if(ppkt1->stream_index != i)
2511 if(ppkt1->pkt->dts < 0)
2513 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2515 ppkt1->pkt->dts -= delta;
2520 st->cur_dts -= delta;
2526 find_stream_info_err:
2527 for (i=0; i < ic->nb_streams; i++)
2528 av_freep(&ic->streams[i]->info);
2532 static AVProgram *find_program_from_stream(AVFormatContext *ic, int s)
2536 for (i = 0; i < ic->nb_programs; i++)
2537 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2538 if (ic->programs[i]->stream_index[j] == s)
2539 return ic->programs[i];
2543 int av_find_best_stream(AVFormatContext *ic,
2544 enum AVMediaType type,
2545 int wanted_stream_nb,
2547 AVCodec **decoder_ret,
2550 int i, nb_streams = ic->nb_streams;
2551 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2552 unsigned *program = NULL;
2553 AVCodec *decoder = NULL, *best_decoder = NULL;
2555 if (related_stream >= 0 && wanted_stream_nb < 0) {
2556 AVProgram *p = find_program_from_stream(ic, related_stream);
2558 program = p->stream_index;
2559 nb_streams = p->nb_stream_indexes;
2562 for (i = 0; i < nb_streams; i++) {
2563 int real_stream_index = program ? program[i] : i;
2564 AVStream *st = ic->streams[real_stream_index];
2565 AVCodecContext *avctx = st->codec;
2566 if (avctx->codec_type != type)
2568 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2570 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2573 decoder = avcodec_find_decoder(st->codec->codec_id);
2576 ret = AVERROR_DECODER_NOT_FOUND;
2580 if (best_count >= st->codec_info_nb_frames)
2582 best_count = st->codec_info_nb_frames;
2583 ret = real_stream_index;
2584 best_decoder = decoder;
2585 if (program && i == nb_streams - 1 && ret < 0) {
2587 nb_streams = ic->nb_streams;
2588 i = 0; /* no related stream found, try again with everything */
2592 *decoder_ret = best_decoder;
2596 /*******************************************************/
2598 int av_read_play(AVFormatContext *s)
2600 if (s->iformat->read_play)
2601 return s->iformat->read_play(s);
2603 return avio_pause(s->pb, 0);
2604 return AVERROR(ENOSYS);
2607 int av_read_pause(AVFormatContext *s)
2609 if (s->iformat->read_pause)
2610 return s->iformat->read_pause(s);
2612 return avio_pause(s->pb, 1);
2613 return AVERROR(ENOSYS);
2616 void av_close_input_stream(AVFormatContext *s)
2618 flush_packet_queue(s);
2619 if (s->iformat->read_close)
2620 s->iformat->read_close(s);
2621 avformat_free_context(s);
2624 void avformat_free_context(AVFormatContext *s)
2629 for(i=0;i<s->nb_streams;i++) {
2630 /* free all data in a stream component */
2633 av_parser_close(st->parser);
2634 av_free_packet(&st->cur_pkt);
2636 av_metadata_free(&st->metadata);
2637 av_free(st->index_entries);
2638 av_free(st->codec->extradata);
2639 av_free(st->codec->subtitle_header);
2641 #if FF_API_OLD_METADATA
2642 av_free(st->filename);
2644 av_free(st->priv_data);
2648 for(i=s->nb_programs-1; i>=0; i--) {
2649 #if FF_API_OLD_METADATA
2650 av_freep(&s->programs[i]->provider_name);
2651 av_freep(&s->programs[i]->name);
2653 av_metadata_free(&s->programs[i]->metadata);
2654 av_freep(&s->programs[i]->stream_index);
2655 av_freep(&s->programs[i]);
2657 av_freep(&s->programs);
2658 av_freep(&s->priv_data);
2659 while(s->nb_chapters--) {
2660 #if FF_API_OLD_METADATA
2661 av_free(s->chapters[s->nb_chapters]->title);
2663 av_metadata_free(&s->chapters[s->nb_chapters]->metadata);
2664 av_free(s->chapters[s->nb_chapters]);
2666 av_freep(&s->chapters);
2667 av_metadata_free(&s->metadata);
2672 void av_close_input_file(AVFormatContext *s)
2674 AVIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2675 av_close_input_stream(s);
2680 AVStream *av_new_stream(AVFormatContext *s, int id)
2685 #if FF_API_MAX_STREAMS
2686 if (s->nb_streams >= MAX_STREAMS){
2687 av_log(s, AV_LOG_ERROR, "Too many streams\n");
2693 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2695 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2698 s->streams = streams;
2701 st = av_mallocz(sizeof(AVStream));
2704 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2709 st->codec= avcodec_alloc_context();
2711 /* no default bitrate if decoding */
2712 st->codec->bit_rate = 0;
2714 st->index = s->nb_streams;
2716 st->start_time = AV_NOPTS_VALUE;
2717 st->duration = AV_NOPTS_VALUE;
2718 /* we set the current DTS to 0 so that formats without any timestamps
2719 but durations get some timestamps, formats with some unknown
2720 timestamps have their first few packets buffered and the
2721 timestamps corrected before they are returned to the user */
2723 st->first_dts = AV_NOPTS_VALUE;
2724 st->probe_packets = MAX_PROBE_PACKETS;
2726 /* default pts setting is MPEG-like */
2727 av_set_pts_info(st, 33, 1, 90000);
2728 st->last_IP_pts = AV_NOPTS_VALUE;
2729 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2730 st->pts_buffer[i]= AV_NOPTS_VALUE;
2731 st->reference_dts = AV_NOPTS_VALUE;
2733 st->sample_aspect_ratio = (AVRational){0,1};
2735 s->streams[s->nb_streams++] = st;
2739 AVProgram *av_new_program(AVFormatContext *ac, int id)
2741 AVProgram *program=NULL;
2745 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2748 for(i=0; i<ac->nb_programs; i++)
2749 if(ac->programs[i]->id == id)
2750 program = ac->programs[i];
2753 program = av_mallocz(sizeof(AVProgram));
2756 dynarray_add(&ac->programs, &ac->nb_programs, program);
2757 program->discard = AVDISCARD_NONE;
2764 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2766 AVChapter *chapter = NULL;
2769 for(i=0; i<s->nb_chapters; i++)
2770 if(s->chapters[i]->id == id)
2771 chapter = s->chapters[i];
2774 chapter= av_mallocz(sizeof(AVChapter));
2777 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2779 #if FF_API_OLD_METADATA
2780 av_free(chapter->title);
2782 av_metadata_set2(&chapter->metadata, "title", title, 0);
2784 chapter->time_base= time_base;
2785 chapter->start = start;
2791 /************************************************************/
2792 /* output media file */
2794 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2798 if (s->oformat->priv_data_size > 0) {
2799 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2801 return AVERROR(ENOMEM);
2802 if (s->oformat->priv_class) {
2803 *(const AVClass**)s->priv_data= s->oformat->priv_class;
2804 av_opt_set_defaults(s->priv_data);
2807 s->priv_data = NULL;
2809 if (s->oformat->set_parameters) {
2810 ret = s->oformat->set_parameters(s, ap);
2817 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
2819 const AVCodecTag *avctag;
2821 enum CodecID id = CODEC_ID_NONE;
2822 unsigned int tag = 0;
2825 * Check that tag + id is in the table
2826 * If neither is in the table -> OK
2827 * If tag is in the table with another id -> FAIL
2828 * If id is in the table with another tag -> FAIL unless strict < normal
2830 for (n = 0; s->oformat->codec_tag[n]; n++) {
2831 avctag = s->oformat->codec_tag[n];
2832 while (avctag->id != CODEC_ID_NONE) {
2833 if (ff_toupper4(avctag->tag) == ff_toupper4(st->codec->codec_tag)) {
2835 if (id == st->codec->codec_id)
2838 if (avctag->id == st->codec->codec_id)
2843 if (id != CODEC_ID_NONE)
2845 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
2850 int av_write_header(AVFormatContext *s)
2855 // some sanity checks
2856 if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
2857 av_log(s, AV_LOG_ERROR, "no streams\n");
2858 return AVERROR(EINVAL);
2861 for(i=0;i<s->nb_streams;i++) {
2864 switch (st->codec->codec_type) {
2865 case AVMEDIA_TYPE_AUDIO:
2866 if(st->codec->sample_rate<=0){
2867 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2868 return AVERROR(EINVAL);
2870 if(!st->codec->block_align)
2871 st->codec->block_align = st->codec->channels *
2872 av_get_bits_per_sample(st->codec->codec_id) >> 3;
2874 case AVMEDIA_TYPE_VIDEO:
2875 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2876 av_log(s, AV_LOG_ERROR, "time base not set\n");
2877 return AVERROR(EINVAL);
2879 if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
2880 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2881 return AVERROR(EINVAL);
2883 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){
2884 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
2885 return AVERROR(EINVAL);
2890 if(s->oformat->codec_tag){
2891 if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){
2892 //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
2893 st->codec->codec_tag= 0;
2895 if(st->codec->codec_tag){
2896 if (!validate_codec_tag(s, st)) {
2898 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
2899 av_log(s, AV_LOG_ERROR,
2900 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
2901 tagbuf, st->codec->codec_tag, st->codec->codec_id);
2902 return AVERROR_INVALIDDATA;
2905 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2908 if(s->oformat->flags & AVFMT_GLOBALHEADER &&
2909 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
2910 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
2913 if (!s->priv_data && s->oformat->priv_data_size > 0) {
2914 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2916 return AVERROR(ENOMEM);
2919 #if FF_API_OLD_METADATA
2920 ff_metadata_mux_compat(s);
2923 /* set muxer identification string */
2924 if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
2925 av_metadata_set2(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
2928 if(s->oformat->write_header){
2929 ret = s->oformat->write_header(s);
2934 /* init PTS generation */
2935 for(i=0;i<s->nb_streams;i++) {
2936 int64_t den = AV_NOPTS_VALUE;
2939 switch (st->codec->codec_type) {
2940 case AVMEDIA_TYPE_AUDIO:
2941 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2943 case AVMEDIA_TYPE_VIDEO:
2944 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2949 if (den != AV_NOPTS_VALUE) {
2951 return AVERROR_INVALIDDATA;
2952 av_frac_init(&st->pts, 0, 0, den);
2958 //FIXME merge with compute_pkt_fields
2959 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
2960 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2961 int num, den, frame_size, i;
2963 av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
2964 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2966 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2967 return AVERROR(EINVAL);*/
2969 /* duration field */
2970 if (pkt->duration == 0) {
2971 compute_frame_duration(&num, &den, st, NULL, pkt);
2973 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
2977 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2980 //XXX/FIXME this is a temporary hack until all encoders output pts
2981 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2983 // pkt->pts= st->cur_dts;
2984 pkt->pts= st->pts.val;
2987 //calculate dts from pts
2988 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
2989 st->pts_buffer[0]= pkt->pts;
2990 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2991 st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
2992 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2993 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2995 pkt->dts= st->pts_buffer[0];
2998 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2999 av_log(s, AV_LOG_ERROR,
3000 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
3001 st->index, st->cur_dts, pkt->dts);
3002 return AVERROR(EINVAL);
3004 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
3005 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
3006 return AVERROR(EINVAL);
3009 // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
3010 st->cur_dts= pkt->dts;
3011 st->pts.val= pkt->dts;
3014 switch (st->codec->codec_type) {
3015 case AVMEDIA_TYPE_AUDIO:
3016 frame_size = get_audio_frame_size(st->codec, pkt->size);
3018 /* HACK/FIXME, we skip the initial 0 size packets as they are most
3019 likely equal to the encoder delay, but it would be better if we
3020 had the real timestamps from the encoder */
3021 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
3022 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
3025 case AVMEDIA_TYPE_VIDEO:
3026 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
3034 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
3036 int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
3038 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3041 ret= s->oformat->write_packet(s, pkt);
3043 ret= url_ferror(s->pb);
3047 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
3048 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
3050 AVPacketList **next_point, *this_pktl;
3052 this_pktl = av_mallocz(sizeof(AVPacketList));
3053 this_pktl->pkt= *pkt;
3054 pkt->destruct= NULL; // do not free original but only the copy
3055 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
3057 if(s->streams[pkt->stream_index]->last_in_packet_buffer){
3058 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
3060 next_point = &s->packet_buffer;
3063 if(compare(s, &s->packet_buffer_end->pkt, pkt)){
3064 while(!compare(s, &(*next_point)->pkt, pkt)){
3065 next_point= &(*next_point)->next;
3069 next_point = &(s->packet_buffer_end->next);
3072 assert(!*next_point);
3074 s->packet_buffer_end= this_pktl;
3077 this_pktl->next= *next_point;
3079 s->streams[pkt->stream_index]->last_in_packet_buffer=
3080 *next_point= this_pktl;
3083 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3085 AVStream *st = s->streams[ pkt ->stream_index];
3086 AVStream *st2= s->streams[ next->stream_index];
3087 int64_t a= st2->time_base.num * (int64_t)st ->time_base.den;
3088 int64_t b= st ->time_base.num * (int64_t)st2->time_base.den;
3089 int64_t dts1 = av_rescale_rnd(pkt->dts, b, a, AV_ROUND_DOWN);
3090 if (dts1==next->dts && dts1==av_rescale_rnd(pkt->dts, b, a, AV_ROUND_UP))
3091 return pkt->stream_index < next->stream_index;
3092 return dts1 < next->dts;
3095 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
3101 ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
3104 for(i=0; i < s->nb_streams; i++)
3105 stream_count+= !!s->streams[i]->last_in_packet_buffer;
3107 if(stream_count && (s->nb_streams == stream_count || flush)){
3108 pktl= s->packet_buffer;
3111 s->packet_buffer= pktl->next;
3112 if(!s->packet_buffer)
3113 s->packet_buffer_end= NULL;
3115 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3116 s->streams[out->stream_index]->last_in_packet_buffer= NULL;
3120 av_init_packet(out);
3126 * Interleave an AVPacket correctly so it can be muxed.
3127 * @param out the interleaved packet will be output here
3128 * @param in the input packet
3129 * @param flush 1 if no further packets are available as input and all
3130 * remaining packets should be output
3131 * @return 1 if a packet was output, 0 if no packet could be output,
3132 * < 0 if an error occurred
3134 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
3135 if(s->oformat->interleave_packet)
3136 return s->oformat->interleave_packet(s, out, in, flush);
3138 return av_interleave_packet_per_dts(s, out, in, flush);
3141 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3142 AVStream *st= s->streams[ pkt->stream_index];
3145 //FIXME/XXX/HACK drop zero sized packets
3146 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3149 av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3150 pkt->size, pkt->dts, pkt->pts);
3151 if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3154 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3155 return AVERROR(EINVAL);
3159 int ret= av_interleave_packet(s, &opkt, pkt, 0);
3160 if(ret<=0) //FIXME cleanup needed for ret<0 ?
3163 ret= s->oformat->write_packet(s, &opkt);
3165 av_free_packet(&opkt);
3170 if(url_ferror(s->pb))
3171 return url_ferror(s->pb);
3175 int av_write_trailer(AVFormatContext *s)
3181 ret= av_interleave_packet(s, &pkt, NULL, 1);
3182 if(ret<0) //FIXME cleanup needed for ret<0 ?
3187 ret= s->oformat->write_packet(s, &pkt);
3189 av_free_packet(&pkt);
3193 if(url_ferror(s->pb))
3197 if(s->oformat->write_trailer)
3198 ret = s->oformat->write_trailer(s);
3201 ret=url_ferror(s->pb);
3202 for(i=0;i<s->nb_streams;i++) {
3203 av_freep(&s->streams[i]->priv_data);
3204 av_freep(&s->streams[i]->index_entries);
3206 av_freep(&s->priv_data);
3210 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3213 AVProgram *program=NULL;
3216 if (idx >= ac->nb_streams) {
3217 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3221 for(i=0; i<ac->nb_programs; i++){
3222 if(ac->programs[i]->id != progid)
3224 program = ac->programs[i];
3225 for(j=0; j<program->nb_stream_indexes; j++)
3226 if(program->stream_index[j] == idx)
3229 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3232 program->stream_index = tmp;
3233 program->stream_index[program->nb_stream_indexes++] = idx;
3238 static void print_fps(double d, const char *postfix){
3239 uint64_t v= lrintf(d*100);
3240 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3241 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3242 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3245 static void dump_metadata(void *ctx, AVMetadata *m, const char *indent)
3247 if(m && !(m->count == 1 && av_metadata_get(m, "language", NULL, 0))){
3248 AVMetadataTag *tag=NULL;
3250 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3251 while((tag=av_metadata_get(m, "", tag, AV_METADATA_IGNORE_SUFFIX))) {
3252 if(strcmp("language", tag->key))
3253 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tag->value);
3258 /* "user interface" functions */
3259 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3262 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3263 AVStream *st = ic->streams[i];
3264 int g = av_gcd(st->time_base.num, st->time_base.den);
3265 AVMetadataTag *lang = av_metadata_get(st->metadata, "language", NULL, 0);
3266 avcodec_string(buf, sizeof(buf), st->codec, is_output);
3267 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
3268 /* the pid is an important information, so we display it */
3269 /* XXX: add a generic system */
3270 if (flags & AVFMT_SHOW_IDS)
3271 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3273 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3274 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3275 av_log(NULL, AV_LOG_INFO, ": %s", buf);
3276 if (st->sample_aspect_ratio.num && // default
3277 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3278 AVRational display_aspect_ratio;
3279 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3280 st->codec->width*st->sample_aspect_ratio.num,
3281 st->codec->height*st->sample_aspect_ratio.den,
3283 av_log(NULL, AV_LOG_INFO, ", PAR %d:%d DAR %d:%d",
3284 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3285 display_aspect_ratio.num, display_aspect_ratio.den);
3287 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3288 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3289 print_fps(av_q2d(st->avg_frame_rate), "fps");
3290 if(st->r_frame_rate.den && st->r_frame_rate.num)
3291 print_fps(av_q2d(st->r_frame_rate), "tbr");
3292 if(st->time_base.den && st->time_base.num)
3293 print_fps(1/av_q2d(st->time_base), "tbn");
3294 if(st->codec->time_base.den && st->codec->time_base.num)
3295 print_fps(1/av_q2d(st->codec->time_base), "tbc");
3297 if (st->disposition & AV_DISPOSITION_DEFAULT)
3298 av_log(NULL, AV_LOG_INFO, " (default)");
3299 if (st->disposition & AV_DISPOSITION_DUB)
3300 av_log(NULL, AV_LOG_INFO, " (dub)");
3301 if (st->disposition & AV_DISPOSITION_ORIGINAL)
3302 av_log(NULL, AV_LOG_INFO, " (original)");
3303 if (st->disposition & AV_DISPOSITION_COMMENT)
3304 av_log(NULL, AV_LOG_INFO, " (comment)");
3305 if (st->disposition & AV_DISPOSITION_LYRICS)
3306 av_log(NULL, AV_LOG_INFO, " (lyrics)");
3307 if (st->disposition & AV_DISPOSITION_KARAOKE)
3308 av_log(NULL, AV_LOG_INFO, " (karaoke)");
3309 if (st->disposition & AV_DISPOSITION_FORCED)
3310 av_log(NULL, AV_LOG_INFO, " (forced)");
3311 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3312 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3313 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3314 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3315 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
3316 av_log(NULL, AV_LOG_INFO, " (clean effects)");
3317 av_log(NULL, AV_LOG_INFO, "\n");
3318 dump_metadata(NULL, st->metadata, " ");
3321 #if FF_API_DUMP_FORMAT
3322 void dump_format(AVFormatContext *ic,
3327 av_dump_format(ic, index, url, is_output);
3331 void av_dump_format(AVFormatContext *ic,
3337 uint8_t *printed = av_mallocz(ic->nb_streams);
3338 if (ic->nb_streams && !printed)
3341 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3342 is_output ? "Output" : "Input",
3344 is_output ? ic->oformat->name : ic->iformat->name,
3345 is_output ? "to" : "from", url);
3346 dump_metadata(NULL, ic->metadata, " ");
3348 av_log(NULL, AV_LOG_INFO, " Duration: ");
3349 if (ic->duration != AV_NOPTS_VALUE) {
3350 int hours, mins, secs, us;
3351 secs = ic->duration / AV_TIME_BASE;
3352 us = ic->duration % AV_TIME_BASE;
3357 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3358 (100 * us) / AV_TIME_BASE);
3360 av_log(NULL, AV_LOG_INFO, "N/A");
3362 if (ic->start_time != AV_NOPTS_VALUE) {
3364 av_log(NULL, AV_LOG_INFO, ", start: ");
3365 secs = ic->start_time / AV_TIME_BASE;
3366 us = abs(ic->start_time % AV_TIME_BASE);
3367 av_log(NULL, AV_LOG_INFO, "%d.%06d",
3368 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3370 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3372 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3374 av_log(NULL, AV_LOG_INFO, "N/A");
3376 av_log(NULL, AV_LOG_INFO, "\n");
3378 for (i = 0; i < ic->nb_chapters; i++) {
3379 AVChapter *ch = ic->chapters[i];
3380 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
3381 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3382 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
3384 dump_metadata(NULL, ch->metadata, " ");
3386 if(ic->nb_programs) {
3387 int j, k, total = 0;
3388 for(j=0; j<ic->nb_programs; j++) {
3389 AVMetadataTag *name = av_metadata_get(ic->programs[j]->metadata,
3391 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3392 name ? name->value : "");
3393 dump_metadata(NULL, ic->programs[j]->metadata, " ");
3394 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3395 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3396 printed[ic->programs[j]->stream_index[k]] = 1;
3398 total += ic->programs[j]->nb_stream_indexes;
3400 if (total < ic->nb_streams)
3401 av_log(NULL, AV_LOG_INFO, " No Program\n");
3403 for(i=0;i<ic->nb_streams;i++)
3405 dump_stream_format(ic, i, index, is_output);
3410 #if FF_API_PARSE_FRAME_PARAM
3411 #include "libavutil/parseutils.h"
3413 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
3415 return av_parse_video_size(width_ptr, height_ptr, str);
3418 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
3420 AVRational frame_rate;
3421 int ret = av_parse_video_rate(&frame_rate, arg);
3422 *frame_rate_num= frame_rate.num;
3423 *frame_rate_den= frame_rate.den;
3428 int64_t av_gettime(void)
3431 gettimeofday(&tv,NULL);
3432 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3435 uint64_t ff_ntp_time(void)
3437 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3440 #if FF_API_PARSE_DATE
3441 #include "libavutil/parseutils.h"
3443 int64_t parse_date(const char *timestr, int duration)
3446 av_parse_time(&timeval, timestr, duration);
3451 #if FF_API_FIND_INFO_TAG
3452 #include "libavutil/parseutils.h"
3454 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3456 return av_find_info_tag(arg, arg_size, tag1, info);
3460 int av_get_frame_filename(char *buf, int buf_size,
3461 const char *path, int number)
3464 char *q, buf1[20], c;
3465 int nd, len, percentd_found;
3477 while (isdigit(*p)) {
3478 nd = nd * 10 + *p++ - '0';
3481 } while (isdigit(c));
3490 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3492 if ((q - buf + len) > buf_size - 1)
3494 memcpy(q, buf1, len);
3502 if ((q - buf) < buf_size - 1)
3506 if (!percentd_found)
3515 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3519 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3521 for(i=0;i<size;i+=16) {
3528 PRINT(" %02x", buf[i+j]);
3533 for(j=0;j<len;j++) {
3535 if (c < ' ' || c > '~')
3544 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3546 hex_dump_internal(NULL, f, 0, buf, size);
3549 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3551 hex_dump_internal(avcl, NULL, level, buf, size);
3554 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3557 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3558 PRINT("stream #%d:\n", pkt->stream_index);
3559 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3560 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3561 /* DTS is _always_ valid after av_read_frame() */
3563 if (pkt->dts == AV_NOPTS_VALUE)
3566 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3567 /* PTS may not be known if B-frames are present. */
3569 if (pkt->pts == AV_NOPTS_VALUE)
3572 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3574 PRINT(" size=%d\n", pkt->size);
3577 av_hex_dump(f, pkt->data, pkt->size);
3581 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3583 AVRational tb = { 1, AV_TIME_BASE };
3584 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3588 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3590 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3594 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3596 AVRational tb = { 1, AV_TIME_BASE };
3597 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3601 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3604 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3607 #if FF_API_URL_SPLIT
3608 attribute_deprecated
3609 void ff_url_split(char *proto, int proto_size,
3610 char *authorization, int authorization_size,
3611 char *hostname, int hostname_size,
3613 char *path, int path_size,
3616 av_url_split(proto, proto_size,
3617 authorization, authorization_size,
3618 hostname, hostname_size,
3625 void av_url_split(char *proto, int proto_size,
3626 char *authorization, int authorization_size,
3627 char *hostname, int hostname_size,
3629 char *path, int path_size,
3632 const char *p, *ls, *at, *col, *brk;
3634 if (port_ptr) *port_ptr = -1;
3635 if (proto_size > 0) proto[0] = 0;
3636 if (authorization_size > 0) authorization[0] = 0;
3637 if (hostname_size > 0) hostname[0] = 0;
3638 if (path_size > 0) path[0] = 0;
3640 /* parse protocol */
3641 if ((p = strchr(url, ':'))) {
3642 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3647 /* no protocol means plain filename */
3648 av_strlcpy(path, url, path_size);
3652 /* separate path from hostname */
3653 ls = strchr(p, '/');
3655 ls = strchr(p, '?');
3657 av_strlcpy(path, ls, path_size);
3659 ls = &p[strlen(p)]; // XXX
3661 /* the rest is hostname, use that to parse auth/port */
3663 /* authorization (user[:pass]@hostname) */
3664 if ((at = strchr(p, '@')) && at < ls) {
3665 av_strlcpy(authorization, p,
3666 FFMIN(authorization_size, at + 1 - p));
3667 p = at + 1; /* skip '@' */
3670 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3672 av_strlcpy(hostname, p + 1,
3673 FFMIN(hostname_size, brk - p));
3674 if (brk[1] == ':' && port_ptr)
3675 *port_ptr = atoi(brk + 2);
3676 } else if ((col = strchr(p, ':')) && col < ls) {
3677 av_strlcpy(hostname, p,
3678 FFMIN(col + 1 - p, hostname_size));
3679 if (port_ptr) *port_ptr = atoi(col + 1);
3681 av_strlcpy(hostname, p,
3682 FFMIN(ls + 1 - p, hostname_size));
3686 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3689 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3692 'C', 'D', 'E', 'F' };
3693 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3696 'c', 'd', 'e', 'f' };
3697 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3699 for(i = 0; i < s; i++) {
3700 buff[i * 2] = hex_table[src[i] >> 4];
3701 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
3707 int ff_hex_to_data(uint8_t *data, const char *p)
3714 p += strspn(p, SPACE_CHARS);
3717 c = toupper((unsigned char) *p++);
3718 if (c >= '0' && c <= '9')
3720 else if (c >= 'A' && c <= 'F')
3735 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3736 unsigned int pts_num, unsigned int pts_den)
3739 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
3740 if(new_tb.num != pts_num)
3741 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
3743 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
3745 if(new_tb.num <= 0 || new_tb.den <= 0) {
3746 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
3749 s->time_base = new_tb;
3750 s->pts_wrap_bits = pts_wrap_bits;
3753 int ff_url_join(char *str, int size, const char *proto,
3754 const char *authorization, const char *hostname,
3755 int port, const char *fmt, ...)
3758 struct addrinfo hints, *ai;
3763 av_strlcatf(str, size, "%s://", proto);
3764 if (authorization && authorization[0])
3765 av_strlcatf(str, size, "%s@", authorization);
3766 #if CONFIG_NETWORK && defined(AF_INET6)
3767 /* Determine if hostname is a numerical IPv6 address,
3768 * properly escape it within [] in that case. */
3769 memset(&hints, 0, sizeof(hints));
3770 hints.ai_flags = AI_NUMERICHOST;
3771 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
3772 if (ai->ai_family == AF_INET6) {
3773 av_strlcat(str, "[", size);
3774 av_strlcat(str, hostname, size);
3775 av_strlcat(str, "]", size);
3777 av_strlcat(str, hostname, size);
3782 /* Not an IPv6 address, just output the plain string. */
3783 av_strlcat(str, hostname, size);
3786 av_strlcatf(str, size, ":%d", port);
3789 int len = strlen(str);
3792 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
3798 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
3799 AVFormatContext *src)
3804 local_pkt.stream_index = dst_stream;
3805 if (pkt->pts != AV_NOPTS_VALUE)
3806 local_pkt.pts = av_rescale_q(pkt->pts,
3807 src->streams[pkt->stream_index]->time_base,
3808 dst->streams[dst_stream]->time_base);
3809 if (pkt->dts != AV_NOPTS_VALUE)
3810 local_pkt.dts = av_rescale_q(pkt->dts,
3811 src->streams[pkt->stream_index]->time_base,
3812 dst->streams[dst_stream]->time_base);
3813 return av_write_frame(dst, &local_pkt);
3816 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
3819 const char *ptr = str;
3821 /* Parse key=value pairs. */
3824 char *dest = NULL, *dest_end;
3825 int key_len, dest_len = 0;
3827 /* Skip whitespace and potential commas. */
3828 while (*ptr && (isspace(*ptr) || *ptr == ','))
3835 if (!(ptr = strchr(key, '=')))
3838 key_len = ptr - key;
3840 callback_get_buf(context, key, key_len, &dest, &dest_len);
3841 dest_end = dest + dest_len - 1;
3845 while (*ptr && *ptr != '\"') {
3849 if (dest && dest < dest_end)
3853 if (dest && dest < dest_end)
3861 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
3862 if (dest && dest < dest_end)
3870 int ff_find_stream_index(AVFormatContext *s, int id)
3873 for (i = 0; i < s->nb_streams; i++) {
3874 if (s->streams[i]->id == id)
3880 void ff_make_absolute_url(char *buf, int size, const char *base,
3884 /* Absolute path, relative to the current server */
3885 if (base && strstr(base, "://") && rel[0] == '/') {
3887 av_strlcpy(buf, base, size);
3888 sep = strstr(buf, "://");
3891 sep = strchr(sep, '/');
3895 av_strlcat(buf, rel, size);
3898 /* If rel actually is an absolute url, just copy it */
3899 if (!base || strstr(rel, "://") || rel[0] == '/') {
3900 av_strlcpy(buf, rel, size);
3904 av_strlcpy(buf, base, size);
3905 /* Remove the file name from the base url */
3906 sep = strrchr(buf, '/');
3911 while (av_strstart(rel, "../", NULL) && sep) {
3912 /* Remove the path delimiter at the end */
3914 sep = strrchr(buf, '/');
3915 /* If the next directory name to pop off is "..", break here */
3916 if (!strcmp(sep ? &sep[1] : buf, "..")) {
3917 /* Readd the slash we just removed */
3918 av_strlcat(buf, "/", size);
3921 /* Cut off the directory name */
3928 av_strlcat(buf, rel, size);