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"
30 #include "libavutil/dict.h"
31 #include "libavutil/pixdesc.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/parseutils.h"
38 #include "audiointerleave.h"
52 * various utility functions for use within FFmpeg
55 unsigned avformat_version(void)
57 return LIBAVFORMAT_VERSION_INT;
60 const char *avformat_configuration(void)
62 return FFMPEG_CONFIGURATION;
65 const char *avformat_license(void)
67 #define LICENSE_PREFIX "libavformat license: "
68 return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
71 /* fraction handling */
74 * f = val + (num / den) + 0.5.
76 * 'num' is normalized so that it is such as 0 <= num < den.
78 * @param f fractional number
79 * @param val integer value
80 * @param num must be >= 0
81 * @param den must be >= 1
83 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
96 * Fractional addition to f: f = f + (incr / f->den).
98 * @param f fractional number
99 * @param incr increment, can be positive or negative
101 static void frac_add(AVFrac *f, int64_t incr)
114 } else if (num >= den) {
121 /** head of registered input format linked list */
122 static AVInputFormat *first_iformat = NULL;
123 /** head of registered output format linked list */
124 static AVOutputFormat *first_oformat = NULL;
126 AVInputFormat *av_iformat_next(AVInputFormat *f)
128 if(f) return f->next;
129 else return first_iformat;
132 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
134 if(f) return f->next;
135 else return first_oformat;
138 void av_register_input_format(AVInputFormat *format)
142 while (*p != NULL) p = &(*p)->next;
147 void av_register_output_format(AVOutputFormat *format)
151 while (*p != NULL) p = &(*p)->next;
156 int av_match_ext(const char *filename, const char *extensions)
164 ext = strrchr(filename, '.');
170 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
173 if (!av_strcasecmp(ext1, ext))
183 static int match_format(const char *name, const char *names)
191 namelen = strlen(name);
192 while ((p = strchr(names, ','))) {
193 len = FFMAX(p - names, namelen);
194 if (!av_strncasecmp(name, names, len))
198 return !av_strcasecmp(name, names);
201 AVOutputFormat *av_guess_format(const char *short_name, const char *filename,
202 const char *mime_type)
204 AVOutputFormat *fmt = NULL, *fmt_found;
205 int score_max, score;
207 /* specific test for image sequences */
208 #if CONFIG_IMAGE2_MUXER
209 if (!short_name && filename &&
210 av_filename_number_test(filename) &&
211 ff_guess_image2_codec(filename) != CODEC_ID_NONE) {
212 return av_guess_format("image2", NULL, NULL);
215 /* Find the proper file type. */
218 while ((fmt = av_oformat_next(fmt))) {
220 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
222 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
224 if (filename && fmt->extensions &&
225 av_match_ext(filename, fmt->extensions)) {
228 if (score > score_max) {
236 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
237 const char *filename, const char *mime_type, enum AVMediaType type){
238 if(type == AVMEDIA_TYPE_VIDEO){
239 enum CodecID codec_id= CODEC_ID_NONE;
241 #if CONFIG_IMAGE2_MUXER
242 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
243 codec_id= ff_guess_image2_codec(filename);
246 if(codec_id == CODEC_ID_NONE)
247 codec_id= fmt->video_codec;
249 }else if(type == AVMEDIA_TYPE_AUDIO)
250 return fmt->audio_codec;
251 else if (type == AVMEDIA_TYPE_SUBTITLE)
252 return fmt->subtitle_codec;
254 return CODEC_ID_NONE;
257 AVInputFormat *av_find_input_format(const char *short_name)
259 AVInputFormat *fmt = NULL;
260 while ((fmt = av_iformat_next(fmt))) {
261 if (match_format(short_name, fmt->name))
268 int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
273 int64_t remaining= s->maxsize - avio_tell(s);
274 if(remaining < size){
275 int64_t newsize= avio_size(s);
276 if(!s->maxsize || s->maxsize<newsize)
278 remaining= s->maxsize - avio_tell(s);
281 if(s->maxsize>=0 && remaining>=0)
282 size= FFMIN(size, remaining+1);
285 ret= av_new_packet(pkt, size);
290 pkt->pos= avio_tell(s);
292 ret= avio_read(s, pkt->data, size);
296 av_shrink_packet(pkt, ret);
301 int av_append_packet(AVIOContext *s, AVPacket *pkt, int size)
306 return av_get_packet(s, pkt, size);
307 old_size = pkt->size;
308 ret = av_grow_packet(pkt, size);
311 ret = avio_read(s, pkt->data + old_size, size);
312 av_shrink_packet(pkt, old_size + FFMAX(ret, 0));
317 int av_filename_number_test(const char *filename)
320 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
323 AVInputFormat *av_probe_input_format3(AVProbeData *pd, int is_opened, int *score_ret)
325 AVProbeData lpd = *pd;
326 AVInputFormat *fmt1 = NULL, *fmt;
327 int score, nodat = 0, score_max=0;
329 if (lpd.buf_size > 10 && ff_id3v2_match(lpd.buf, ID3v2_DEFAULT_MAGIC)) {
330 int id3len = ff_id3v2_tag_len(lpd.buf);
331 if (lpd.buf_size > id3len + 16) {
333 lpd.buf_size -= id3len;
339 while ((fmt1 = av_iformat_next(fmt1))) {
340 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
343 if (fmt1->read_probe) {
344 score = fmt1->read_probe(&lpd);
345 if(fmt1->extensions && av_match_ext(lpd.filename, fmt1->extensions))
346 score = FFMAX(score, nodat ? AVPROBE_SCORE_MAX/4-1 : 1);
347 } else if (fmt1->extensions) {
348 if (av_match_ext(lpd.filename, fmt1->extensions)) {
352 if (score > score_max) {
355 }else if (score == score_max)
358 *score_ret= score_max;
363 AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
366 AVInputFormat *fmt= av_probe_input_format3(pd, is_opened, &score_ret);
367 if(score_ret > *score_max){
368 *score_max= score_ret;
374 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
376 return av_probe_input_format2(pd, is_opened, &score);
379 static int set_codec_from_probe_data(AVFormatContext *s, AVStream *st, AVProbeData *pd)
381 static const struct {
382 const char *name; enum CodecID id; enum AVMediaType type;
384 { "aac" , CODEC_ID_AAC , AVMEDIA_TYPE_AUDIO },
385 { "ac3" , CODEC_ID_AC3 , AVMEDIA_TYPE_AUDIO },
386 { "dts" , CODEC_ID_DTS , AVMEDIA_TYPE_AUDIO },
387 { "eac3" , CODEC_ID_EAC3 , AVMEDIA_TYPE_AUDIO },
388 { "h264" , CODEC_ID_H264 , AVMEDIA_TYPE_VIDEO },
389 { "loas" , CODEC_ID_AAC_LATM , AVMEDIA_TYPE_AUDIO },
390 { "m4v" , CODEC_ID_MPEG4 , AVMEDIA_TYPE_VIDEO },
391 { "mp3" , CODEC_ID_MP3 , AVMEDIA_TYPE_AUDIO },
392 { "mpegvideo", CODEC_ID_MPEG2VIDEO, AVMEDIA_TYPE_VIDEO },
396 AVInputFormat *fmt = av_probe_input_format3(pd, 1, &score);
400 av_log(s, AV_LOG_DEBUG, "Probe with size=%d, packets=%d detected %s with score=%d\n",
401 pd->buf_size, MAX_PROBE_PACKETS - st->probe_packets, fmt->name, score);
402 for (i = 0; fmt_id_type[i].name; i++) {
403 if (!strcmp(fmt->name, fmt_id_type[i].name)) {
404 st->codec->codec_id = fmt_id_type[i].id;
405 st->codec->codec_type = fmt_id_type[i].type;
413 /************************************************************/
414 /* input media file */
416 #if FF_API_FORMAT_PARAMETERS
417 static AVDictionary *convert_format_parameters(AVFormatParameters *ap)
420 AVDictionary *opts = NULL;
425 AV_NOWARN_DEPRECATED(
426 if (ap->time_base.num) {
427 snprintf(buf, sizeof(buf), "%d/%d", ap->time_base.den, ap->time_base.num);
428 av_dict_set(&opts, "framerate", buf, 0);
430 if (ap->sample_rate) {
431 snprintf(buf, sizeof(buf), "%d", ap->sample_rate);
432 av_dict_set(&opts, "sample_rate", buf, 0);
435 snprintf(buf, sizeof(buf), "%d", ap->channels);
436 av_dict_set(&opts, "channels", buf, 0);
438 if (ap->width || ap->height) {
439 snprintf(buf, sizeof(buf), "%dx%d", ap->width, ap->height);
440 av_dict_set(&opts, "video_size", buf, 0);
442 if (ap->pix_fmt != PIX_FMT_NONE) {
443 av_dict_set(&opts, "pixel_format", av_get_pix_fmt_name(ap->pix_fmt), 0);
446 snprintf(buf, sizeof(buf), "%d", ap->channel);
447 av_dict_set(&opts, "channel", buf, 0);
450 av_dict_set(&opts, "standard", ap->standard, 0);
452 if (ap->mpeg2ts_compute_pcr) {
453 av_dict_set(&opts, "mpeg2ts_compute_pcr", "1", 0);
455 if (ap->initial_pause) {
456 av_dict_set(&opts, "initial_pause", "1", 0);
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)
472 AVFormatParameters default_ap;
476 memset(ap, 0, sizeof(default_ap));
478 opts = convert_format_parameters(ap);
480 AV_NOWARN_DEPRECATED(
481 if(!ap->prealloced_context)
482 *ic_ptr = ic = avformat_alloc_context();
487 err = AVERROR(ENOMEM);
490 if (pb && fmt && fmt->flags & AVFMT_NOFILE)
491 av_log(ic, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
492 "will be ignored with AVFMT_NOFILE format.\n");
496 if ((err = avformat_open_input(&ic, filename, fmt, &opts)) < 0)
498 ic->pb = ic->pb ? ic->pb : pb; // don't leak custom pb if it wasn't set above
507 int av_demuxer_open(AVFormatContext *ic, AVFormatParameters *ap){
510 if (ic->iformat->read_header) {
511 err = ic->iformat->read_header(ic, ap);
516 if (ic->pb && !ic->data_offset)
517 ic->data_offset = avio_tell(ic->pb);
523 /** size of probe buffer, for guessing file type from file contents */
524 #define PROBE_BUF_MIN 2048
525 #define PROBE_BUF_MAX (1<<20)
527 int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,
528 const char *filename, void *logctx,
529 unsigned int offset, unsigned int max_probe_size)
531 AVProbeData pd = { filename ? filename : "", NULL, -offset };
532 unsigned char *buf = NULL;
533 int ret = 0, probe_size;
535 if (!max_probe_size) {
536 max_probe_size = PROBE_BUF_MAX;
537 } else if (max_probe_size > PROBE_BUF_MAX) {
538 max_probe_size = PROBE_BUF_MAX;
539 } else if (max_probe_size < PROBE_BUF_MIN) {
540 return AVERROR(EINVAL);
543 if (offset >= max_probe_size) {
544 return AVERROR(EINVAL);
547 for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;
548 probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {
549 int score = probe_size < max_probe_size ? AVPROBE_SCORE_MAX/4 : 0;
550 int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;
553 if (probe_size < offset) {
557 /* read probe data */
558 buftmp = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);
561 return AVERROR(ENOMEM);
564 if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {
565 /* fail if error was not end of file, otherwise, lower score */
566 if (ret != AVERROR_EOF) {
571 ret = 0; /* error was end of file, nothing read */
574 pd.buf = &buf[offset];
576 memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);
578 /* guess file format */
579 *fmt = av_probe_input_format2(&pd, 1, &score);
581 if(score <= AVPROBE_SCORE_MAX/4){ //this can only be true in the last iteration
582 av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);
584 av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);
590 return AVERROR_INVALIDDATA;
593 /* rewind. reuse probe buffer to avoid seeking */
594 if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)
600 #if FF_API_FORMAT_PARAMETERS
601 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
604 AVFormatParameters *ap)
607 AVDictionary *opts = convert_format_parameters(ap);
609 AV_NOWARN_DEPRECATED(
610 if (!ap || !ap->prealloced_context)
614 err = avformat_open_input(ic_ptr, filename, fmt, &opts);
621 /* open input file and probe the format if necessary */
622 static int init_input(AVFormatContext *s, const char *filename, AVDictionary **options)
625 AVProbeData pd = {filename, NULL, 0};
627 if(s->iformat && !strlen(filename))
631 s->flags |= AVFMT_FLAG_CUSTOM_IO;
633 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
634 else if (s->iformat->flags & AVFMT_NOFILE)
635 av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
636 "will be ignored with AVFMT_NOFILE format.\n");
640 if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
641 (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
644 if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ,
645 &s->interrupt_callback, options)) < 0)
649 return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
652 int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
654 AVFormatContext *s = *ps;
656 AVFormatParameters ap = { { 0 } };
657 AVDictionary *tmp = NULL;
659 if (!s && !(s = avformat_alloc_context()))
660 return AVERROR(ENOMEM);
665 av_dict_copy(&tmp, *options, 0);
667 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
670 if ((ret = init_input(s, filename, &tmp)) < 0)
673 /* check filename in case an image number is expected */
674 if (s->iformat->flags & AVFMT_NEEDNUMBER) {
675 if (!av_filename_number_test(filename)) {
676 ret = AVERROR(EINVAL);
681 s->duration = s->start_time = AV_NOPTS_VALUE;
682 av_strlcpy(s->filename, filename, sizeof(s->filename));
684 /* allocate private data */
685 if (s->iformat->priv_data_size > 0) {
686 if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {
687 ret = AVERROR(ENOMEM);
690 if (s->iformat->priv_class) {
691 *(const AVClass**)s->priv_data = s->iformat->priv_class;
692 av_opt_set_defaults(s->priv_data);
693 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
698 /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */
700 ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC);
702 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)
703 if ((ret = s->iformat->read_header(s, &ap)) < 0)
706 if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)
707 s->data_offset = avio_tell(s->pb);
709 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
712 av_dict_free(options);
720 if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))
722 avformat_free_context(s);
727 /*******************************************************/
729 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
730 AVPacketList **plast_pktl){
731 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
736 (*plast_pktl)->next = pktl;
738 *packet_buffer = pktl;
740 /* add the packet in the buffered packet list */
746 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
752 AVPacketList *pktl = s->raw_packet_buffer;
756 if(s->streams[pkt->stream_index]->request_probe <= 0){
757 s->raw_packet_buffer = pktl->next;
758 s->raw_packet_buffer_remaining_size += pkt->size;
765 ret= s->iformat->read_packet(s, pkt);
767 if (!pktl || ret == AVERROR(EAGAIN))
769 for (i = 0; i < s->nb_streams; i++)
770 if(s->streams[i]->request_probe > 0)
771 s->streams[i]->request_probe = -1;
775 if ((s->flags & AVFMT_FLAG_DISCARD_CORRUPT) &&
776 (pkt->flags & AV_PKT_FLAG_CORRUPT)) {
777 av_log(s, AV_LOG_WARNING,
778 "Dropped corrupted packet (stream = %d)\n",
784 if(!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))
785 av_packet_merge_side_data(pkt);
787 if(pkt->stream_index >= (unsigned)s->nb_streams){
788 av_log(s, AV_LOG_ERROR, "Invalid stream index %d\n", pkt->stream_index);
792 st= s->streams[pkt->stream_index];
794 switch(st->codec->codec_type){
795 case AVMEDIA_TYPE_VIDEO:
796 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
798 case AVMEDIA_TYPE_AUDIO:
799 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
801 case AVMEDIA_TYPE_SUBTITLE:
802 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
806 if(!pktl && st->request_probe <= 0)
809 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
810 s->raw_packet_buffer_remaining_size -= pkt->size;
812 if(st->request_probe>0){
813 AVProbeData *pd = &st->probe_data;
815 av_log(s, AV_LOG_DEBUG, "probing stream %d pp:%d\n", st->index, st->probe_packets);
818 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
819 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
820 pd->buf_size += pkt->size;
821 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
823 end= s->raw_packet_buffer_remaining_size <= 0
824 || st->probe_packets<=0;
826 if(end || av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
827 int score= set_codec_from_probe_data(s, st, pd);
828 if( (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)
832 st->request_probe= -1;
833 if(st->codec->codec_id != CODEC_ID_NONE){
834 av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);
836 av_log(s, AV_LOG_WARNING, "probed stream %d failed\n", st->index);
843 /**********************************************************/
846 * Get the number of samples of an audio frame. Return -1 on error.
848 static int get_audio_frame_size(AVCodecContext *enc, int size)
852 if(enc->codec_id == CODEC_ID_VORBIS)
855 if (enc->frame_size <= 1) {
856 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
858 if (bits_per_sample) {
859 if (enc->channels == 0)
861 frame_size = (size << 3) / (bits_per_sample * enc->channels);
863 /* used for example by ADPCM codecs */
864 if (enc->bit_rate == 0)
866 frame_size = ((int64_t)size * 8 * enc->sample_rate) / enc->bit_rate;
869 frame_size = enc->frame_size;
876 * Return the frame duration in seconds. Return 0 if not available.
878 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
879 AVCodecParserContext *pc, AVPacket *pkt)
885 switch(st->codec->codec_type) {
886 case AVMEDIA_TYPE_VIDEO:
887 if (st->r_frame_rate.num && !pc) {
888 *pnum = st->r_frame_rate.den;
889 *pden = st->r_frame_rate.num;
890 } else if(st->time_base.num*1000LL > st->time_base.den) {
891 *pnum = st->time_base.num;
892 *pden = st->time_base.den;
893 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
894 *pnum = st->codec->time_base.num;
895 *pden = st->codec->time_base.den;
896 if (pc && pc->repeat_pict) {
897 *pnum = (*pnum) * (1 + pc->repeat_pict);
899 //If this codec can be interlaced or progressive then we need a parser to compute duration of a packet
900 //Thus if we have no parser in such case leave duration undefined.
901 if(st->codec->ticks_per_frame>1 && !pc){
906 case AVMEDIA_TYPE_AUDIO:
907 frame_size = get_audio_frame_size(st->codec, pkt->size);
908 if (frame_size <= 0 || st->codec->sample_rate <= 0)
911 *pden = st->codec->sample_rate;
918 static int is_intra_only(AVCodecContext *enc){
919 if(enc->codec_type == AVMEDIA_TYPE_AUDIO){
921 }else if(enc->codec_type == AVMEDIA_TYPE_VIDEO){
922 switch(enc->codec_id){
924 case CODEC_ID_MJPEGB:
926 case CODEC_ID_PRORES:
927 case CODEC_ID_RAWVIDEO:
928 case CODEC_ID_DVVIDEO:
929 case CODEC_ID_HUFFYUV:
930 case CODEC_ID_FFVHUFF:
935 case CODEC_ID_JPEG2000:
943 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
944 int64_t dts, int64_t pts)
946 AVStream *st= s->streams[stream_index];
947 AVPacketList *pktl= s->packet_buffer;
949 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
952 st->first_dts= dts - st->cur_dts;
955 for(; pktl; pktl= pktl->next){
956 if(pktl->pkt.stream_index != stream_index)
958 //FIXME think more about this check
959 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
960 pktl->pkt.pts += st->first_dts;
962 if(pktl->pkt.dts != AV_NOPTS_VALUE)
963 pktl->pkt.dts += st->first_dts;
965 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
966 st->start_time= pktl->pkt.pts;
968 if (st->start_time == AV_NOPTS_VALUE)
969 st->start_time = pts;
972 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
974 AVPacketList *pktl= s->packet_buffer;
977 if(st->first_dts != AV_NOPTS_VALUE){
978 cur_dts= st->first_dts;
979 for(; pktl; pktl= pktl->next){
980 if(pktl->pkt.stream_index == pkt->stream_index){
981 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
983 cur_dts -= pkt->duration;
986 pktl= s->packet_buffer;
987 st->first_dts = cur_dts;
988 }else if(st->cur_dts)
991 for(; pktl; pktl= pktl->next){
992 if(pktl->pkt.stream_index != pkt->stream_index)
994 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
995 && !pktl->pkt.duration){
996 pktl->pkt.dts= cur_dts;
997 if(!st->codec->has_b_frames)
998 pktl->pkt.pts= cur_dts;
999 cur_dts += pkt->duration;
1000 pktl->pkt.duration= pkt->duration;
1004 if(st->first_dts == AV_NOPTS_VALUE)
1005 st->cur_dts= cur_dts;
1008 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
1009 AVCodecParserContext *pc, AVPacket *pkt)
1011 int num, den, presentation_delayed, delay, i;
1014 if (s->flags & AVFMT_FLAG_NOFILLIN)
1017 if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)
1018 pkt->dts= AV_NOPTS_VALUE;
1020 if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == AV_PICTURE_TYPE_B)
1021 //FIXME Set low_delay = 0 when has_b_frames = 1
1022 st->codec->has_b_frames = 1;
1024 /* do we have a video B-frame ? */
1025 delay= st->codec->has_b_frames;
1026 presentation_delayed = 0;
1028 /* XXX: need has_b_frame, but cannot get it if the codec is
1031 pc && pc->pict_type != AV_PICTURE_TYPE_B)
1032 presentation_delayed = 1;
1034 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts - (1LL<<(st->pts_wrap_bits-1)) > pkt->pts && st->pts_wrap_bits<63){
1035 pkt->dts -= 1LL<<st->pts_wrap_bits;
1038 // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)
1039 // we take the conservative approach and discard both
1040 // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.
1041 if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){
1042 av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);
1043 pkt->dts= AV_NOPTS_VALUE;
1046 if (pkt->duration == 0) {
1047 compute_frame_duration(&num, &den, st, pc, pkt);
1049 pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);
1051 if(pkt->duration != 0 && s->packet_buffer)
1052 update_initial_durations(s, st, pkt);
1056 /* correct timestamps with byte offset if demuxers only have timestamps
1057 on packet boundaries */
1058 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
1059 /* this will estimate bitrate based on this frame's duration and size */
1060 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
1061 if(pkt->pts != AV_NOPTS_VALUE)
1063 if(pkt->dts != AV_NOPTS_VALUE)
1067 if (pc && pc->dts_sync_point >= 0) {
1068 // we have synchronization info from the parser
1069 int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;
1071 int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;
1072 if (pkt->dts != AV_NOPTS_VALUE) {
1073 // got DTS from the stream, update reference timestamp
1074 st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;
1075 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1076 } else if (st->reference_dts != AV_NOPTS_VALUE) {
1077 // compute DTS based on reference timestamp
1078 pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;
1079 pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;
1081 if (pc->dts_sync_point > 0)
1082 st->reference_dts = pkt->dts; // new reference
1086 /* This may be redundant, but it should not hurt. */
1087 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
1088 presentation_delayed = 1;
1090 // 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);
1091 /* interpolate PTS and DTS if they are not present */
1092 //We skip H264 currently because delay and has_b_frames are not reliably set
1093 if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){
1094 if (presentation_delayed) {
1095 /* DTS = decompression timestamp */
1096 /* PTS = presentation timestamp */
1097 if (pkt->dts == AV_NOPTS_VALUE)
1098 pkt->dts = st->last_IP_pts;
1099 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
1100 if (pkt->dts == AV_NOPTS_VALUE)
1101 pkt->dts = st->cur_dts;
1103 /* this is tricky: the dts must be incremented by the duration
1104 of the frame we are displaying, i.e. the last I- or P-frame */
1105 if (st->last_IP_duration == 0)
1106 st->last_IP_duration = pkt->duration;
1107 if(pkt->dts != AV_NOPTS_VALUE)
1108 st->cur_dts = pkt->dts + st->last_IP_duration;
1109 st->last_IP_duration = pkt->duration;
1110 st->last_IP_pts= pkt->pts;
1111 /* cannot compute PTS if not present (we can compute it only
1112 by knowing the future */
1113 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
1114 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
1115 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
1116 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
1117 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
1118 pkt->pts += pkt->duration;
1119 // 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);
1123 /* presentation is not delayed : PTS and DTS are the same */
1124 if(pkt->pts == AV_NOPTS_VALUE)
1125 pkt->pts = pkt->dts;
1126 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
1127 if(pkt->pts == AV_NOPTS_VALUE)
1128 pkt->pts = st->cur_dts;
1129 pkt->dts = pkt->pts;
1130 if(pkt->pts != AV_NOPTS_VALUE)
1131 st->cur_dts = pkt->pts + pkt->duration;
1135 if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
1136 st->pts_buffer[0]= pkt->pts;
1137 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
1138 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
1139 if(pkt->dts == AV_NOPTS_VALUE)
1140 pkt->dts= st->pts_buffer[0];
1141 if(st->codec->codec_id == CODEC_ID_H264){ // we skipped it above so we try here
1142 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
1144 if(pkt->dts > st->cur_dts)
1145 st->cur_dts = pkt->dts;
1148 // 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);
1151 if(is_intra_only(st->codec))
1152 pkt->flags |= AV_PKT_FLAG_KEY;
1155 /* keyframe computation */
1156 if (pc->key_frame == 1)
1157 pkt->flags |= AV_PKT_FLAG_KEY;
1158 else if (pc->key_frame == -1 && pc->pict_type == AV_PICTURE_TYPE_I)
1159 pkt->flags |= AV_PKT_FLAG_KEY;
1162 pkt->convergence_duration = pc->convergence_duration;
1166 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
1171 av_init_packet(pkt);
1174 /* select current input stream component */
1177 if (!st->need_parsing || !st->parser) {
1178 /* no parsing needed: we just output the packet as is */
1179 /* raw data support */
1181 st->cur_pkt.data= NULL;
1182 st->cur_pkt.side_data_elems = 0;
1183 st->cur_pkt.side_data = NULL;
1184 compute_pkt_fields(s, st, NULL, pkt);
1186 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
1187 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
1188 ff_reduce_index(s, st->index);
1189 av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);
1192 } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {
1193 len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,
1194 st->cur_ptr, st->cur_len,
1195 st->cur_pkt.pts, st->cur_pkt.dts,
1197 st->cur_pkt.pts = AV_NOPTS_VALUE;
1198 st->cur_pkt.dts = AV_NOPTS_VALUE;
1199 /* increment read pointer */
1203 /* return packet if any */
1207 pkt->stream_index = st->index;
1208 pkt->pts = st->parser->pts;
1209 pkt->dts = st->parser->dts;
1210 pkt->pos = st->parser->pos;
1211 if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){
1213 pkt->destruct= st->cur_pkt.destruct;
1214 st->cur_pkt.destruct= NULL;
1215 st->cur_pkt.data = NULL;
1216 assert(st->cur_len == 0);
1218 pkt->destruct = NULL;
1220 compute_pkt_fields(s, st, st->parser, pkt);
1222 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){
1223 int64_t pos= (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->pos : st->parser->frame_offset;
1224 ff_reduce_index(s, st->index);
1225 av_add_index_entry(st, pos, pkt->dts,
1226 0, 0, AVINDEX_KEYFRAME);
1233 av_free_packet(&st->cur_pkt);
1238 /* read next packet */
1239 ret = av_read_packet(s, &cur_pkt);
1241 if (ret == AVERROR(EAGAIN))
1243 /* return the last frames, if any */
1244 for(i = 0; i < s->nb_streams; i++) {
1246 if (st->parser && st->need_parsing) {
1247 av_parser_parse2(st->parser, st->codec,
1248 &pkt->data, &pkt->size,
1250 AV_NOPTS_VALUE, AV_NOPTS_VALUE,
1256 /* no more packets: really terminate parsing */
1259 st = s->streams[cur_pkt.stream_index];
1260 st->cur_pkt= cur_pkt;
1262 if(st->cur_pkt.pts != AV_NOPTS_VALUE &&
1263 st->cur_pkt.dts != AV_NOPTS_VALUE &&
1264 st->cur_pkt.pts < st->cur_pkt.dts){
1265 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
1266 st->cur_pkt.stream_index,
1270 // av_free_packet(&st->cur_pkt);
1274 if(s->debug & FF_FDEBUG_TS)
1275 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1276 st->cur_pkt.stream_index,
1280 st->cur_pkt.duration,
1284 st->cur_ptr = st->cur_pkt.data;
1285 st->cur_len = st->cur_pkt.size;
1286 if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
1287 st->parser = av_parser_init(st->codec->codec_id);
1289 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
1290 "%s, packets or times may be invalid.\n",
1291 avcodec_get_name(st->codec->codec_id));
1292 /* no parser available: just output the raw packets */
1293 st->need_parsing = AVSTREAM_PARSE_NONE;
1294 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
1295 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1296 }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){
1297 st->parser->flags |= PARSER_FLAG_ONCE;
1302 if(s->debug & FF_FDEBUG_TS)
1303 av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",
1314 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1318 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1321 pktl = s->packet_buffer;
1323 AVPacket *next_pkt= &pktl->pkt;
1325 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1326 int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;
1327 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1328 if( pktl->pkt.stream_index == next_pkt->stream_index
1329 && (0 > av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)))
1330 && av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame
1331 next_pkt->pts= pktl->pkt.dts;
1335 pktl = s->packet_buffer;
1338 if( next_pkt->pts != AV_NOPTS_VALUE
1339 || next_pkt->dts == AV_NOPTS_VALUE
1341 /* read packet from packet buffer, if there is data */
1343 s->packet_buffer = pktl->next;
1349 int ret= read_frame_internal(s, pkt);
1351 if(pktl && ret != AVERROR(EAGAIN)){
1358 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1359 &s->packet_buffer_end)) < 0)
1360 return AVERROR(ENOMEM);
1362 assert(!s->packet_buffer);
1363 return read_frame_internal(s, pkt);
1368 /* XXX: suppress the packet queue */
1369 static void flush_packet_queue(AVFormatContext *s)
1374 pktl = s->packet_buffer;
1377 s->packet_buffer = pktl->next;
1378 av_free_packet(&pktl->pkt);
1381 while(s->raw_packet_buffer){
1382 pktl = s->raw_packet_buffer;
1383 s->raw_packet_buffer = pktl->next;
1384 av_free_packet(&pktl->pkt);
1387 s->packet_buffer_end=
1388 s->raw_packet_buffer_end= NULL;
1389 s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
1392 /*******************************************************/
1395 int av_find_default_stream_index(AVFormatContext *s)
1397 int first_audio_index = -1;
1401 if (s->nb_streams <= 0)
1403 for(i = 0; i < s->nb_streams; i++) {
1405 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1408 if (first_audio_index < 0 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1409 first_audio_index = i;
1411 return first_audio_index >= 0 ? first_audio_index : 0;
1415 * Flush the frame reader.
1417 void ff_read_frame_flush(AVFormatContext *s)
1422 flush_packet_queue(s);
1426 /* for each stream, reset read state */
1427 for(i = 0; i < s->nb_streams; i++) {
1431 av_parser_close(st->parser);
1433 av_free_packet(&st->cur_pkt);
1435 st->last_IP_pts = AV_NOPTS_VALUE;
1436 if(st->first_dts == AV_NOPTS_VALUE) st->cur_dts = 0;
1437 else st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1438 st->reference_dts = AV_NOPTS_VALUE;
1443 st->probe_packets = MAX_PROBE_PACKETS;
1445 for(j=0; j<MAX_REORDER_DELAY+1; j++)
1446 st->pts_buffer[j]= AV_NOPTS_VALUE;
1450 #if FF_API_SEEK_PUBLIC
1451 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1453 ff_update_cur_dts(s, ref_st, timestamp);
1457 void ff_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp)
1461 for(i = 0; i < s->nb_streams; i++) {
1462 AVStream *st = s->streams[i];
1464 st->cur_dts = av_rescale(timestamp,
1465 st->time_base.den * (int64_t)ref_st->time_base.num,
1466 st->time_base.num * (int64_t)ref_st->time_base.den);
1470 void ff_reduce_index(AVFormatContext *s, int stream_index)
1472 AVStream *st= s->streams[stream_index];
1473 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1475 if((unsigned)st->nb_index_entries >= max_entries){
1477 for(i=0; 2*i<st->nb_index_entries; i++)
1478 st->index_entries[i]= st->index_entries[2*i];
1479 st->nb_index_entries= i;
1483 int ff_add_index_entry(AVIndexEntry **index_entries,
1484 int *nb_index_entries,
1485 unsigned int *index_entries_allocated_size,
1486 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1488 AVIndexEntry *entries, *ie;
1491 if((unsigned)*nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1494 entries = av_fast_realloc(*index_entries,
1495 index_entries_allocated_size,
1496 (*nb_index_entries + 1) *
1497 sizeof(AVIndexEntry));
1501 *index_entries= entries;
1503 index= ff_index_search_timestamp(*index_entries, *nb_index_entries, timestamp, AVSEEK_FLAG_ANY);
1506 index= (*nb_index_entries)++;
1507 ie= &entries[index];
1508 assert(index==0 || ie[-1].timestamp < timestamp);
1510 ie= &entries[index];
1511 if(ie->timestamp != timestamp){
1512 if(ie->timestamp <= timestamp)
1514 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(*nb_index_entries - index));
1515 (*nb_index_entries)++;
1516 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1517 distance= ie->min_distance;
1521 ie->timestamp = timestamp;
1522 ie->min_distance= distance;
1529 int av_add_index_entry(AVStream *st,
1530 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1532 return ff_add_index_entry(&st->index_entries, &st->nb_index_entries,
1533 &st->index_entries_allocated_size, pos,
1534 timestamp, size, distance, flags);
1537 int ff_index_search_timestamp(const AVIndexEntry *entries, int nb_entries,
1538 int64_t wanted_timestamp, int flags)
1546 //optimize appending index entries at the end
1547 if(b && entries[b-1].timestamp < wanted_timestamp)
1552 timestamp = entries[m].timestamp;
1553 if(timestamp >= wanted_timestamp)
1555 if(timestamp <= wanted_timestamp)
1558 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1560 if(!(flags & AVSEEK_FLAG_ANY)){
1561 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1562 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1571 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1574 return ff_index_search_timestamp(st->index_entries, st->nb_index_entries,
1575 wanted_timestamp, flags);
1578 #if FF_API_SEEK_PUBLIC
1579 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1580 return ff_seek_frame_binary(s, stream_index, target_ts, flags);
1584 int ff_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
1586 AVInputFormat *avif= s->iformat;
1587 int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;
1588 int64_t ts_min, ts_max, ts;
1593 if (stream_index < 0)
1596 av_dlog(s, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1599 ts_min= AV_NOPTS_VALUE;
1600 pos_limit= -1; //gcc falsely says it may be uninitialized
1602 st= s->streams[stream_index];
1603 if(st->index_entries){
1606 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()
1607 index= FFMAX(index, 0);
1608 e= &st->index_entries[index];
1610 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1612 ts_min= e->timestamp;
1613 av_dlog(s, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1619 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1620 assert(index < st->nb_index_entries);
1622 e= &st->index_entries[index];
1623 assert(e->timestamp >= target_ts);
1625 ts_max= e->timestamp;
1626 pos_limit= pos_max - e->min_distance;
1627 av_dlog(s, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1628 pos_max,pos_limit, ts_max);
1632 pos= ff_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1637 if ((ret = avio_seek(s->pb, pos, SEEK_SET)) < 0)
1640 ff_read_frame_flush(s);
1641 ff_update_cur_dts(s, st, ts);
1646 #if FF_API_SEEK_PUBLIC
1647 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1648 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1649 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1650 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1652 return ff_gen_search(s, stream_index, target_ts, pos_min, pos_max,
1653 pos_limit, ts_min, ts_max, flags, ts_ret,
1658 int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,
1659 int64_t pos_min, int64_t pos_max, int64_t pos_limit,
1660 int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,
1661 int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))
1664 int64_t start_pos, filesize;
1667 av_dlog(s, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1669 if(ts_min == AV_NOPTS_VALUE){
1670 pos_min = s->data_offset;
1671 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1672 if (ts_min == AV_NOPTS_VALUE)
1676 if(ts_min >= target_ts){
1681 if(ts_max == AV_NOPTS_VALUE){
1683 filesize = avio_size(s->pb);
1684 pos_max = filesize - 1;
1687 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1689 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1690 if (ts_max == AV_NOPTS_VALUE)
1694 int64_t tmp_pos= pos_max + 1;
1695 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1696 if(tmp_ts == AV_NOPTS_VALUE)
1700 if(tmp_pos >= filesize)
1706 if(ts_max <= target_ts){
1711 if(ts_min > ts_max){
1713 }else if(ts_min == ts_max){
1718 while (pos_min < pos_limit) {
1719 av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1720 pos_min, pos_max, ts_min, ts_max);
1721 assert(pos_limit <= pos_max);
1724 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1725 // interpolate position (better than dichotomy)
1726 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1727 + pos_min - approximate_keyframe_distance;
1728 }else if(no_change==1){
1729 // bisection, if interpolation failed to change min or max pos last time
1730 pos = (pos_min + pos_limit)>>1;
1732 /* linear search if bisection failed, can only happen if there
1733 are very few or no keyframes between min/max */
1738 else if(pos > pos_limit)
1742 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1747 av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n",
1748 pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts,
1749 pos_limit, start_pos, no_change);
1750 if(ts == AV_NOPTS_VALUE){
1751 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1754 assert(ts != AV_NOPTS_VALUE);
1755 if (target_ts <= ts) {
1756 pos_limit = start_pos - 1;
1760 if (target_ts >= ts) {
1766 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1767 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1770 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1772 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1773 av_dlog(s, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1774 pos, ts_min, target_ts, ts_max);
1780 static int seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1781 int64_t pos_min, pos_max;
1785 if (stream_index < 0)
1788 st= s->streams[stream_index];
1791 pos_min = s->data_offset;
1792 pos_max = avio_size(s->pb) - 1;
1794 if (pos < pos_min) pos= pos_min;
1795 else if(pos > pos_max) pos= pos_max;
1797 avio_seek(s->pb, pos, SEEK_SET);
1800 av_update_cur_dts(s, st, ts);
1805 static int seek_frame_generic(AVFormatContext *s,
1806 int stream_index, int64_t timestamp, int flags)
1813 st = s->streams[stream_index];
1815 index = av_index_search_timestamp(st, timestamp, flags);
1817 if(index < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
1820 if(index < 0 || index==st->nb_index_entries-1){
1824 if(st->nb_index_entries){
1825 assert(st->index_entries);
1826 ie= &st->index_entries[st->nb_index_entries-1];
1827 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1829 ff_update_cur_dts(s, st, ie->timestamp);
1831 if ((ret = avio_seek(s->pb, s->data_offset, SEEK_SET)) < 0)
1837 read_status = av_read_frame(s, &pkt);
1838 } while (read_status == AVERROR(EAGAIN));
1839 if (read_status < 0)
1841 av_free_packet(&pkt);
1842 if(stream_index == pkt.stream_index && pkt.dts > timestamp){
1843 if(pkt.flags & AV_PKT_FLAG_KEY)
1845 if(nonkey++ > 1000 && st->codec->codec_id != CODEC_ID_CDGRAPHICS){
1846 av_log(s, AV_LOG_ERROR,"seek_frame_generic failed as this stream seems to contain no keyframes after the target timestamp, %d non keyframes found\n", nonkey);
1851 index = av_index_search_timestamp(st, timestamp, flags);
1856 ff_read_frame_flush(s);
1857 AV_NOWARN_DEPRECATED(
1858 if (s->iformat->read_seek){
1859 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1863 ie = &st->index_entries[index];
1864 if ((ret = avio_seek(s->pb, ie->pos, SEEK_SET)) < 0)
1866 ff_update_cur_dts(s, st, ie->timestamp);
1871 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1876 if (flags & AVSEEK_FLAG_BYTE) {
1877 if (s->iformat->flags & AVFMT_NO_BYTE_SEEK)
1879 ff_read_frame_flush(s);
1880 return seek_frame_byte(s, stream_index, timestamp, flags);
1883 if(stream_index < 0){
1884 stream_index= av_find_default_stream_index(s);
1885 if(stream_index < 0)
1888 st= s->streams[stream_index];
1889 /* timestamp for default must be expressed in AV_TIME_BASE units */
1890 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1893 /* first, we try the format specific seek */
1894 AV_NOWARN_DEPRECATED(
1895 if (s->iformat->read_seek) {
1896 ff_read_frame_flush(s);
1897 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1905 if (s->iformat->read_timestamp && !(s->iformat->flags & AVFMT_NOBINSEARCH)) {
1906 ff_read_frame_flush(s);
1907 return ff_seek_frame_binary(s, stream_index, timestamp, flags);
1908 } else if (!(s->iformat->flags & AVFMT_NOGENSEARCH)) {
1909 ff_read_frame_flush(s);
1910 return seek_frame_generic(s, stream_index, timestamp, flags);
1916 int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1918 if(min_ts > ts || max_ts < ts)
1921 if (s->iformat->read_seek2) {
1922 ff_read_frame_flush(s);
1923 return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);
1926 if(s->iformat->read_timestamp){
1927 //try to seek via read_timestamp()
1930 //Fallback to old API if new is not implemented but old is
1931 //Note the old has somewat different sematics
1932 AV_NOWARN_DEPRECATED(
1933 if(s->iformat->read_seek || 1)
1934 return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));
1937 // try some generic seek like seek_frame_generic() but with new ts semantics
1940 /*******************************************************/
1943 * Return TRUE if the stream has accurate duration in any stream.
1945 * @return TRUE if the stream has accurate duration for at least one component.
1947 static int has_duration(AVFormatContext *ic)
1951 if(ic->duration != AV_NOPTS_VALUE)
1954 for(i = 0;i < ic->nb_streams; i++) {
1955 st = ic->streams[i];
1956 if (st->duration != AV_NOPTS_VALUE)
1963 * Estimate the stream timings from the one of each components.
1965 * Also computes the global bitrate if possible.
1967 static void update_stream_timings(AVFormatContext *ic)
1969 int64_t start_time, start_time1, start_time_text, end_time, end_time1;
1970 int64_t duration, duration1, filesize;
1974 start_time = INT64_MAX;
1975 start_time_text = INT64_MAX;
1976 end_time = INT64_MIN;
1977 duration = INT64_MIN;
1978 for(i = 0;i < ic->nb_streams; i++) {
1979 st = ic->streams[i];
1980 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1981 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1982 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1983 if (start_time1 < start_time_text)
1984 start_time_text = start_time1;
1986 start_time = FFMIN(start_time, start_time1);
1987 if (st->duration != AV_NOPTS_VALUE) {
1988 end_time1 = start_time1
1989 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1990 end_time = FFMAX(end_time, end_time1);
1993 if (st->duration != AV_NOPTS_VALUE) {
1994 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1995 duration = FFMAX(duration, duration1);
1998 if (start_time == INT64_MAX || (start_time > start_time_text && start_time - start_time_text < AV_TIME_BASE))
1999 start_time = start_time_text;
2000 if (start_time != INT64_MAX) {
2001 ic->start_time = start_time;
2002 if (end_time != INT64_MIN)
2003 duration = FFMAX(duration, end_time - start_time);
2005 if (duration != INT64_MIN && ic->duration == AV_NOPTS_VALUE) {
2006 ic->duration = duration;
2008 if (ic->pb && (filesize = avio_size(ic->pb)) > 0 && ic->duration != AV_NOPTS_VALUE) {
2009 /* compute the bitrate */
2010 ic->bit_rate = (double)filesize * 8.0 * AV_TIME_BASE /
2011 (double)ic->duration;
2015 static void fill_all_stream_timings(AVFormatContext *ic)
2020 update_stream_timings(ic);
2021 for(i = 0;i < ic->nb_streams; i++) {
2022 st = ic->streams[i];
2023 if (st->start_time == AV_NOPTS_VALUE) {
2024 if(ic->start_time != AV_NOPTS_VALUE)
2025 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
2026 if(ic->duration != AV_NOPTS_VALUE)
2027 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
2032 static void estimate_timings_from_bit_rate(AVFormatContext *ic)
2034 int64_t filesize, duration;
2038 /* if bit_rate is already set, we believe it */
2039 if (ic->bit_rate <= 0) {
2041 for(i=0;i<ic->nb_streams;i++) {
2042 st = ic->streams[i];
2043 if (st->codec->bit_rate > 0)
2044 bit_rate += st->codec->bit_rate;
2046 ic->bit_rate = bit_rate;
2049 /* if duration is already set, we believe it */
2050 if (ic->duration == AV_NOPTS_VALUE &&
2051 ic->bit_rate != 0) {
2052 filesize = ic->pb ? avio_size(ic->pb) : 0;
2054 for(i = 0; i < ic->nb_streams; i++) {
2055 st = ic->streams[i];
2056 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
2057 if (st->duration == AV_NOPTS_VALUE)
2058 st->duration = duration;
2064 #define DURATION_MAX_READ_SIZE 250000
2065 #define DURATION_MAX_RETRY 3
2067 /* only usable for MPEG-PS streams */
2068 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
2070 AVPacket pkt1, *pkt = &pkt1;
2072 int read_size, i, ret;
2074 int64_t filesize, offset, duration;
2079 /* flush packet queue */
2080 flush_packet_queue(ic);
2082 for (i=0; i<ic->nb_streams; i++) {
2083 st = ic->streams[i];
2084 if (st->start_time == AV_NOPTS_VALUE && st->first_dts == AV_NOPTS_VALUE)
2085 av_log(st->codec, AV_LOG_WARNING, "start time is not set in estimate_timings_from_pts\n");
2088 av_parser_close(st->parser);
2090 av_free_packet(&st->cur_pkt);
2094 /* estimate the end time (duration) */
2095 /* XXX: may need to support wrapping */
2096 filesize = ic->pb ? avio_size(ic->pb) : 0;
2097 end_time = AV_NOPTS_VALUE;
2099 offset = filesize - (DURATION_MAX_READ_SIZE<<retry);
2103 avio_seek(ic->pb, offset, SEEK_SET);
2106 if (read_size >= DURATION_MAX_READ_SIZE<<(FFMAX(retry-1,0)))
2110 ret = av_read_packet(ic, pkt);
2111 } while(ret == AVERROR(EAGAIN));
2114 read_size += pkt->size;
2115 st = ic->streams[pkt->stream_index];
2116 if (pkt->pts != AV_NOPTS_VALUE &&
2117 (st->start_time != AV_NOPTS_VALUE ||
2118 st->first_dts != AV_NOPTS_VALUE)) {
2119 duration = end_time = pkt->pts;
2120 if (st->start_time != AV_NOPTS_VALUE)
2121 duration -= st->start_time;
2123 duration -= st->first_dts;
2125 duration += 1LL<<st->pts_wrap_bits;
2127 if (st->duration == AV_NOPTS_VALUE || st->duration < duration)
2128 st->duration = duration;
2131 av_free_packet(pkt);
2133 }while( end_time==AV_NOPTS_VALUE
2134 && filesize > (DURATION_MAX_READ_SIZE<<retry)
2135 && ++retry <= DURATION_MAX_RETRY);
2137 fill_all_stream_timings(ic);
2139 avio_seek(ic->pb, old_offset, SEEK_SET);
2140 for (i=0; i<ic->nb_streams; i++) {
2142 st->cur_dts= st->first_dts;
2143 st->last_IP_pts = AV_NOPTS_VALUE;
2144 st->reference_dts = AV_NOPTS_VALUE;
2148 static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
2152 /* get the file size, if possible */
2153 if (ic->iformat->flags & AVFMT_NOFILE) {
2156 file_size = avio_size(ic->pb);
2157 file_size = FFMAX(0, file_size);
2160 if ((!strcmp(ic->iformat->name, "mpeg") ||
2161 !strcmp(ic->iformat->name, "mpegts")) &&
2162 file_size && ic->pb->seekable) {
2163 /* get accurate estimate from the PTSes */
2164 estimate_timings_from_pts(ic, old_offset);
2165 } else if (has_duration(ic)) {
2166 /* at least one component has timings - we use them for all
2168 fill_all_stream_timings(ic);
2170 av_log(ic, AV_LOG_WARNING, "Estimating duration from bitrate, this may be inaccurate\n");
2171 /* less precise: use bitrate info */
2172 estimate_timings_from_bit_rate(ic);
2174 update_stream_timings(ic);
2178 AVStream av_unused *st;
2179 for(i = 0;i < ic->nb_streams; i++) {
2180 st = ic->streams[i];
2181 av_dlog(ic, "%d: start_time: %0.3f duration: %0.3f\n", i,
2182 (double) st->start_time / AV_TIME_BASE,
2183 (double) st->duration / AV_TIME_BASE);
2185 av_dlog(ic, "stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
2186 (double) ic->start_time / AV_TIME_BASE,
2187 (double) ic->duration / AV_TIME_BASE,
2188 ic->bit_rate / 1000);
2192 static int has_codec_parameters(AVCodecContext *avctx)
2195 switch (avctx->codec_type) {
2196 case AVMEDIA_TYPE_AUDIO:
2197 val = avctx->sample_rate && avctx->channels && avctx->sample_fmt != AV_SAMPLE_FMT_NONE;
2198 if (!avctx->frame_size &&
2199 (avctx->codec_id == CODEC_ID_VORBIS ||
2200 avctx->codec_id == CODEC_ID_AAC ||
2201 avctx->codec_id == CODEC_ID_MP1 ||
2202 avctx->codec_id == CODEC_ID_MP2 ||
2203 avctx->codec_id == CODEC_ID_MP3 ||
2204 avctx->codec_id == CODEC_ID_CELT))
2207 case AVMEDIA_TYPE_VIDEO:
2208 val = avctx->width && avctx->pix_fmt != PIX_FMT_NONE;
2210 case AVMEDIA_TYPE_DATA:
2211 if(avctx->codec_id == CODEC_ID_NONE) return 1;
2216 return avctx->codec_id != CODEC_ID_NONE && val != 0;
2219 static int has_decode_delay_been_guessed(AVStream *st)
2221 return st->codec->codec_id != CODEC_ID_H264 ||
2222 st->info->nb_decoded_frames >= 6;
2225 static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)
2228 int got_picture, ret = 0;
2230 AVPacket pkt = *avpkt;
2232 if(!st->codec->codec){
2233 codec = avcodec_find_decoder(st->codec->codec_id);
2236 ret = avcodec_open2(st->codec, codec, options);
2241 while (pkt.size > 0 && ret >= 0 &&
2242 (!has_codec_parameters(st->codec) ||
2243 !has_decode_delay_been_guessed(st) ||
2244 (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {
2246 avcodec_get_frame_defaults(&picture);
2247 switch(st->codec->codec_type) {
2248 case AVMEDIA_TYPE_VIDEO:
2249 ret = avcodec_decode_video2(st->codec, &picture,
2250 &got_picture, &pkt);
2252 case AVMEDIA_TYPE_AUDIO:
2253 ret = avcodec_decode_audio4(st->codec, &picture, &got_picture, &pkt);
2260 st->info->nb_decoded_frames++;
2268 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum CodecID id)
2270 while (tags->id != CODEC_ID_NONE) {
2278 enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
2281 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
2282 if(tag == tags[i].tag)
2285 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
2286 if (avpriv_toupper4(tag) == avpriv_toupper4(tags[i].tag))
2289 return CODEC_ID_NONE;
2292 unsigned int av_codec_get_tag(const AVCodecTag * const *tags, enum CodecID id)
2295 for(i=0; tags && tags[i]; i++){
2296 int tag= ff_codec_get_tag(tags[i], id);
2302 enum CodecID av_codec_get_id(const AVCodecTag * const *tags, unsigned int tag)
2305 for(i=0; tags && tags[i]; i++){
2306 enum CodecID id= ff_codec_get_id(tags[i], tag);
2307 if(id!=CODEC_ID_NONE) return id;
2309 return CODEC_ID_NONE;
2312 static void compute_chapters_end(AVFormatContext *s)
2315 int64_t max_time = s->duration + ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);
2317 for (i = 0; i < s->nb_chapters; i++)
2318 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
2319 AVChapter *ch = s->chapters[i];
2320 int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q, ch->time_base)
2323 for (j = 0; j < s->nb_chapters; j++) {
2324 AVChapter *ch1 = s->chapters[j];
2325 int64_t next_start = av_rescale_q(ch1->start, ch1->time_base, ch->time_base);
2326 if (j != i && next_start > ch->start && next_start < end)
2329 ch->end = (end == INT64_MAX) ? ch->start : end;
2333 static int get_std_framerate(int i){
2334 if(i<60*12) return i*1001;
2335 else return ((const int[]){24,30,60,12,15})[i-60*12]*1000*12;
2339 * Is the time base unreliable.
2340 * This is a heuristic to balance between quick acceptance of the values in
2341 * the headers vs. some extra checks.
2342 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
2343 * MPEG-2 commonly misuses field repeat flags to store different framerates.
2344 * And there are "variable" fps files this needs to detect as well.
2346 static int tb_unreliable(AVCodecContext *c){
2347 if( c->time_base.den >= 101L*c->time_base.num
2348 || c->time_base.den < 5L*c->time_base.num
2349 /* || c->codec_tag == AV_RL32("DIVX")
2350 || c->codec_tag == AV_RL32("XVID")*/
2351 || c->codec_id == CODEC_ID_MPEG2VIDEO
2352 || c->codec_id == CODEC_ID_H264
2358 #if FF_API_FORMAT_PARAMETERS
2359 int av_find_stream_info(AVFormatContext *ic)
2361 return avformat_find_stream_info(ic, NULL);
2365 int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
2367 int i, count, ret, read_size, j;
2369 AVPacket pkt1, *pkt;
2370 int64_t old_offset = avio_tell(ic->pb);
2371 int orig_nb_streams = ic->nb_streams; // new streams might appear, no options for those
2373 for(i=0;i<ic->nb_streams;i++) {
2375 st = ic->streams[i];
2377 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2378 st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2379 /* if(!st->time_base.num)
2381 if(!st->codec->time_base.num)
2382 st->codec->time_base= st->time_base;
2384 //only for the split stuff
2385 if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {
2386 st->parser = av_parser_init(st->codec->codec_id);
2387 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
2388 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
2391 assert(!st->codec->codec);
2392 codec = avcodec_find_decoder(st->codec->codec_id);
2394 /* Ensure that subtitle_header is properly set. */
2395 if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
2396 && codec && !st->codec->codec)
2397 avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
2399 //try to just open decoders, in case this is enough to get parameters
2400 if(!has_codec_parameters(st->codec)){
2401 if (codec && !st->codec->codec){
2402 AVDictionary *tmp = NULL;
2404 av_dict_copy(&tmp, options[i], 0);
2405 av_dict_set(&tmp, "threads", 0, 0);
2407 avcodec_open2(st->codec, codec, options ? &tmp : NULL);
2413 for (i=0; i<ic->nb_streams; i++) {
2414 ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;
2420 if (ff_check_interrupt(&ic->interrupt_callback)){
2422 av_log(ic, AV_LOG_DEBUG, "interrupted\n");
2426 /* check if one codec still needs to be handled */
2427 for(i=0;i<ic->nb_streams;i++) {
2428 int fps_analyze_framecount = 20;
2430 st = ic->streams[i];
2431 if (!has_codec_parameters(st->codec))
2433 /* if the timebase is coarse (like the usual millisecond precision
2434 of mkv), we need to analyze more frames to reliably arrive at
2436 if (av_q2d(st->time_base) > 0.0005)
2437 fps_analyze_framecount *= 2;
2438 if (ic->fps_probe_size >= 0)
2439 fps_analyze_framecount = ic->fps_probe_size;
2440 /* variable fps and no guess at the real fps */
2441 if( tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)
2442 && st->info->duration_count < fps_analyze_framecount
2443 && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2445 if(st->parser && st->parser->parser->split && !st->codec->extradata)
2447 if(st->first_dts == AV_NOPTS_VALUE && (st->codec->codec_type == AVMEDIA_TYPE_VIDEO || st->codec->codec_type == AVMEDIA_TYPE_AUDIO))
2450 if (i == ic->nb_streams) {
2451 /* NOTE: if the format has no header, then we need to read
2452 some packets to get most of the streams, so we cannot
2454 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2455 /* if we found the info for all the codecs, we can stop */
2457 av_log(ic, AV_LOG_DEBUG, "All info found\n");
2461 /* we did not get all the codec info, but we read too much data */
2462 if (read_size >= ic->probesize) {
2464 av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit %d reached\n", ic->probesize);
2468 /* NOTE: a new stream can be added there if no header in file
2469 (AVFMTCTX_NOHEADER) */
2470 ret = read_frame_internal(ic, &pkt1);
2471 if (ret == AVERROR(EAGAIN))
2476 ret = -1; /* we could not have all the codec parameters before EOF */
2477 for(i=0;i<ic->nb_streams;i++) {
2478 st = ic->streams[i];
2479 if (!has_codec_parameters(st->codec)){
2481 avcodec_string(buf, sizeof(buf), st->codec, 0);
2482 av_log(ic, AV_LOG_WARNING, "Could not find codec parameters (%s)\n", buf);
2490 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2491 if ((ret = av_dup_packet(pkt)) < 0)
2492 goto find_stream_info_err;
2494 read_size += pkt->size;
2496 st = ic->streams[pkt->stream_index];
2497 if (st->codec_info_nb_frames>1) {
2499 if (st->time_base.den > 0 && (t=av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q)) >= ic->max_analyze_duration) {
2500 av_log(ic, AV_LOG_WARNING, "max_analyze_duration %d reached at %"PRId64"\n", ic->max_analyze_duration, t);
2503 st->info->codec_info_duration += pkt->duration;
2506 int64_t last = st->info->last_dts;
2508 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last){
2509 double dts= pkt->dts * av_q2d(st->time_base);
2510 int64_t duration= pkt->dts - last;
2512 // if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2513 // av_log(NULL, AV_LOG_ERROR, "%f\n", dts);
2514 for (i=1; i<FF_ARRAY_ELEMS(st->info->duration_error[0][0]); i++) {
2515 int framerate= get_std_framerate(i);
2516 double sdts= dts*framerate/(1001*12);
2518 int ticks= lrintf(sdts+j*0.5);
2519 double error= sdts - ticks + j*0.5;
2520 st->info->duration_error[j][0][i] += error;
2521 st->info->duration_error[j][1][i] += error*error;
2524 st->info->duration_count++;
2525 // ignore the first 4 values, they might have some random jitter
2526 if (st->info->duration_count > 3)
2527 st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);
2529 if (last == AV_NOPTS_VALUE || st->info->duration_count <= 1)
2530 st->info->last_dts = pkt->dts;
2532 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2533 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2535 st->codec->extradata_size= i;
2536 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2537 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2538 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2542 /* if still no information, we try to open the codec and to
2543 decompress the frame. We try to avoid that in most cases as
2544 it takes longer and uses more memory. For MPEG-4, we need to
2545 decompress for QuickTime.
2547 If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at
2548 least one frame of codec data, this makes sure the codec initializes
2549 the channel configuration and does not only trust the values from the container.
2551 try_decode_frame(st, pkt, (options && i < orig_nb_streams )? &options[i] : NULL);
2553 st->codec_info_nb_frames++;
2557 // close codecs which were opened in try_decode_frame()
2558 for(i=0;i<ic->nb_streams;i++) {
2559 st = ic->streams[i];
2560 if(st->codec->codec)
2561 avcodec_close(st->codec);
2563 for(i=0;i<ic->nb_streams;i++) {
2564 st = ic->streams[i];
2565 if (st->codec_info_nb_frames>2 && !st->avg_frame_rate.num && st->info->codec_info_duration)
2566 av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2567 (st->codec_info_nb_frames-2)*(int64_t)st->time_base.den,
2568 st->info->codec_info_duration*(int64_t)st->time_base.num, 60000);
2569 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2570 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){
2571 uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2572 if(ff_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)
2573 st->codec->codec_tag= tag;
2576 // the check for tb_unreliable() is not completely correct, since this is not about handling
2577 // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
2578 // ipmovie.c produces.
2579 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)
2580 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);
2581 if (st->info->duration_count && !st->r_frame_rate.num
2582 && tb_unreliable(st->codec) /*&&
2583 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2584 st->time_base.num*duration_sum[i]/st->info->duration_count*101LL > st->time_base.den*/){
2586 double best_error= 0.01;
2588 for (j=1; j<FF_ARRAY_ELEMS(st->info->duration_error[0][0]); j++) {
2591 if(st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
2593 if(!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
2596 int n= st->info->duration_count;
2597 double a= st->info->duration_error[k][0][j] / n;
2598 double error= st->info->duration_error[k][1][j]/n - a*a;
2600 if(error < best_error && best_error> 0.000000001){
2602 num = get_std_framerate(j);
2605 av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
2608 // do not increase frame rate by more than 1 % in order to match a standard rate.
2609 if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
2610 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
2613 if (!st->r_frame_rate.num){
2614 if( st->codec->time_base.den * (int64_t)st->time_base.num
2615 <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){
2616 st->r_frame_rate.num = st->codec->time_base.den;
2617 st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;
2619 st->r_frame_rate.num = st->time_base.den;
2620 st->r_frame_rate.den = st->time_base.num;
2623 }else if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2624 if(!st->codec->bits_per_coded_sample)
2625 st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);
2626 // set stream disposition based on audio service type
2627 switch (st->codec->audio_service_type) {
2628 case AV_AUDIO_SERVICE_TYPE_EFFECTS:
2629 st->disposition = AV_DISPOSITION_CLEAN_EFFECTS; break;
2630 case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:
2631 st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED; break;
2632 case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:
2633 st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;
2634 case AV_AUDIO_SERVICE_TYPE_COMMENTARY:
2635 st->disposition = AV_DISPOSITION_COMMENT; break;
2636 case AV_AUDIO_SERVICE_TYPE_KARAOKE:
2637 st->disposition = AV_DISPOSITION_KARAOKE; break;
2642 estimate_timings(ic, old_offset);
2644 compute_chapters_end(ic);
2647 /* correct DTS for B-frame streams with no timestamps */
2648 for(i=0;i<ic->nb_streams;i++) {
2649 st = ic->streams[i];
2650 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2652 ppktl = &ic->packet_buffer;
2654 if(ppkt1->stream_index != i)
2656 if(ppkt1->pkt->dts < 0)
2658 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2660 ppkt1->pkt->dts -= delta;
2665 st->cur_dts -= delta;
2671 find_stream_info_err:
2672 for (i=0; i < ic->nb_streams; i++)
2673 av_freep(&ic->streams[i]->info);
2677 AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
2681 for (i = 0; i < ic->nb_programs; i++) {
2682 if (ic->programs[i] == last) {
2686 for (j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
2687 if (ic->programs[i]->stream_index[j] == s)
2688 return ic->programs[i];
2694 int av_find_best_stream(AVFormatContext *ic,
2695 enum AVMediaType type,
2696 int wanted_stream_nb,
2698 AVCodec **decoder_ret,
2701 int i, nb_streams = ic->nb_streams;
2702 int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;
2703 unsigned *program = NULL;
2704 AVCodec *decoder = NULL, *best_decoder = NULL;
2706 if (related_stream >= 0 && wanted_stream_nb < 0) {
2707 AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
2709 program = p->stream_index;
2710 nb_streams = p->nb_stream_indexes;
2713 for (i = 0; i < nb_streams; i++) {
2714 int real_stream_index = program ? program[i] : i;
2715 AVStream *st = ic->streams[real_stream_index];
2716 AVCodecContext *avctx = st->codec;
2717 if (avctx->codec_type != type)
2719 if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
2721 if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))
2724 decoder = avcodec_find_decoder(st->codec->codec_id);
2727 ret = AVERROR_DECODER_NOT_FOUND;
2731 if (best_count >= st->codec_info_nb_frames)
2733 best_count = st->codec_info_nb_frames;
2734 ret = real_stream_index;
2735 best_decoder = decoder;
2736 if (program && i == nb_streams - 1 && ret < 0) {
2738 nb_streams = ic->nb_streams;
2739 i = 0; /* no related stream found, try again with everything */
2743 *decoder_ret = best_decoder;
2747 /*******************************************************/
2749 int av_read_play(AVFormatContext *s)
2751 if (s->iformat->read_play)
2752 return s->iformat->read_play(s);
2754 return avio_pause(s->pb, 0);
2755 return AVERROR(ENOSYS);
2758 int av_read_pause(AVFormatContext *s)
2760 if (s->iformat->read_pause)
2761 return s->iformat->read_pause(s);
2763 return avio_pause(s->pb, 1);
2764 return AVERROR(ENOSYS);
2767 #if FF_API_FORMAT_PARAMETERS
2768 void av_close_input_stream(AVFormatContext *s)
2770 flush_packet_queue(s);
2771 if (s->iformat->read_close)
2772 s->iformat->read_close(s);
2773 avformat_free_context(s);
2777 void avformat_free_context(AVFormatContext *s)
2783 if (s->iformat && s->iformat->priv_class && s->priv_data)
2784 av_opt_free(s->priv_data);
2786 for(i=0;i<s->nb_streams;i++) {
2787 /* free all data in a stream component */
2790 av_parser_close(st->parser);
2791 av_free_packet(&st->cur_pkt);
2793 av_dict_free(&st->metadata);
2794 av_freep(&st->index_entries);
2795 av_freep(&st->codec->extradata);
2796 av_freep(&st->codec->subtitle_header);
2797 av_freep(&st->codec);
2798 av_freep(&st->priv_data);
2799 av_freep(&st->info);
2802 for(i=s->nb_programs-1; i>=0; i--) {
2803 av_dict_free(&s->programs[i]->metadata);
2804 av_freep(&s->programs[i]->stream_index);
2805 av_freep(&s->programs[i]);
2807 av_freep(&s->programs);
2808 av_freep(&s->priv_data);
2809 while(s->nb_chapters--) {
2810 av_dict_free(&s->chapters[s->nb_chapters]->metadata);
2811 av_freep(&s->chapters[s->nb_chapters]);
2813 av_freep(&s->chapters);
2814 av_dict_free(&s->metadata);
2815 av_freep(&s->streams);
2819 #if FF_API_CLOSE_INPUT_FILE
2820 void av_close_input_file(AVFormatContext *s)
2822 avformat_close_input(&s);
2826 void avformat_close_input(AVFormatContext **ps)
2828 AVFormatContext *s = *ps;
2829 AVIOContext *pb = (s->iformat && (s->iformat->flags & AVFMT_NOFILE)) || (s->flags & AVFMT_FLAG_CUSTOM_IO) ?
2831 flush_packet_queue(s);
2832 if (s->iformat && (s->iformat->read_close))
2833 s->iformat->read_close(s);
2834 avformat_free_context(s);
2840 #if FF_API_NEW_STREAM
2841 AVStream *av_new_stream(AVFormatContext *s, int id)
2843 AVStream *st = avformat_new_stream(s, NULL);
2850 AVStream *avformat_new_stream(AVFormatContext *s, AVCodec *c)
2856 if (s->nb_streams >= INT_MAX/sizeof(*streams))
2858 streams = av_realloc(s->streams, (s->nb_streams + 1) * sizeof(*streams));
2861 s->streams = streams;
2863 st = av_mallocz(sizeof(AVStream));
2866 if (!(st->info = av_mallocz(sizeof(*st->info)))) {
2871 st->codec = avcodec_alloc_context3(c);
2873 /* no default bitrate if decoding */
2874 st->codec->bit_rate = 0;
2876 st->index = s->nb_streams;
2877 st->start_time = AV_NOPTS_VALUE;
2878 st->duration = AV_NOPTS_VALUE;
2879 /* we set the current DTS to 0 so that formats without any timestamps
2880 but durations get some timestamps, formats with some unknown
2881 timestamps have their first few packets buffered and the
2882 timestamps corrected before they are returned to the user */
2884 st->first_dts = AV_NOPTS_VALUE;
2885 st->probe_packets = MAX_PROBE_PACKETS;
2887 /* default pts setting is MPEG-like */
2888 avpriv_set_pts_info(st, 33, 1, 90000);
2889 st->last_IP_pts = AV_NOPTS_VALUE;
2890 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2891 st->pts_buffer[i]= AV_NOPTS_VALUE;
2892 st->reference_dts = AV_NOPTS_VALUE;
2894 st->sample_aspect_ratio = (AVRational){0,1};
2896 s->streams[s->nb_streams++] = st;
2900 AVProgram *av_new_program(AVFormatContext *ac, int id)
2902 AVProgram *program=NULL;
2905 av_dlog(ac, "new_program: id=0x%04x\n", id);
2907 for(i=0; i<ac->nb_programs; i++)
2908 if(ac->programs[i]->id == id)
2909 program = ac->programs[i];
2912 program = av_mallocz(sizeof(AVProgram));
2915 dynarray_add(&ac->programs, &ac->nb_programs, program);
2916 program->discard = AVDISCARD_NONE;
2923 AVChapter *avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2925 AVChapter *chapter = NULL;
2928 for(i=0; i<s->nb_chapters; i++)
2929 if(s->chapters[i]->id == id)
2930 chapter = s->chapters[i];
2933 chapter= av_mallocz(sizeof(AVChapter));
2936 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2938 av_dict_set(&chapter->metadata, "title", title, 0);
2940 chapter->time_base= time_base;
2941 chapter->start = start;
2947 /************************************************************/
2948 /* output media file */
2950 #if FF_API_FORMAT_PARAMETERS
2951 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2953 if (s->oformat->priv_data_size > 0) {
2954 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2956 return AVERROR(ENOMEM);
2957 if (s->oformat->priv_class) {
2958 *(const AVClass**)s->priv_data= s->oformat->priv_class;
2959 av_opt_set_defaults(s->priv_data);
2962 s->priv_data = NULL;
2968 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
2969 const char *format, const char *filename)
2971 AVFormatContext *s = avformat_alloc_context();
2980 oformat = av_guess_format(format, NULL, NULL);
2982 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
2983 ret = AVERROR(EINVAL);
2987 oformat = av_guess_format(NULL, filename, NULL);
2989 ret = AVERROR(EINVAL);
2990 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
2997 s->oformat = oformat;
2998 if (s->oformat->priv_data_size > 0) {
2999 s->priv_data = av_mallocz(s->oformat->priv_data_size);
3002 if (s->oformat->priv_class) {
3003 *(const AVClass**)s->priv_data= s->oformat->priv_class;
3004 av_opt_set_defaults(s->priv_data);
3007 s->priv_data = NULL;
3010 av_strlcpy(s->filename, filename, sizeof(s->filename));
3014 av_log(s, AV_LOG_ERROR, "Out of memory\n");
3015 ret = AVERROR(ENOMEM);
3017 avformat_free_context(s);
3021 #if FF_API_ALLOC_OUTPUT_CONTEXT
3022 AVFormatContext *avformat_alloc_output_context(const char *format,
3023 AVOutputFormat *oformat, const char *filename)
3025 AVFormatContext *avctx;
3026 int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
3027 return ret < 0 ? NULL : avctx;
3031 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
3033 const AVCodecTag *avctag;
3035 enum CodecID id = CODEC_ID_NONE;
3036 unsigned int tag = 0;
3039 * Check that tag + id is in the table
3040 * If neither is in the table -> OK
3041 * If tag is in the table with another id -> FAIL
3042 * If id is in the table with another tag -> FAIL unless strict < normal
3044 for (n = 0; s->oformat->codec_tag[n]; n++) {
3045 avctag = s->oformat->codec_tag[n];
3046 while (avctag->id != CODEC_ID_NONE) {
3047 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
3049 if (id == st->codec->codec_id)
3052 if (avctag->id == st->codec->codec_id)
3057 if (id != CODEC_ID_NONE)
3059 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
3064 #if FF_API_FORMAT_PARAMETERS
3065 int av_write_header(AVFormatContext *s)
3067 return avformat_write_header(s, NULL);
3071 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
3075 AVDictionary *tmp = NULL;
3078 av_dict_copy(&tmp, *options, 0);
3079 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
3081 if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
3082 (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
3085 // some sanity checks
3086 if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {
3087 av_log(s, AV_LOG_ERROR, "no streams\n");
3088 ret = AVERROR(EINVAL);
3092 for(i=0;i<s->nb_streams;i++) {
3095 switch (st->codec->codec_type) {
3096 case AVMEDIA_TYPE_AUDIO:
3097 if(st->codec->sample_rate<=0){
3098 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
3099 ret = AVERROR(EINVAL);
3102 if(!st->codec->block_align)
3103 st->codec->block_align = st->codec->channels *
3104 av_get_bits_per_sample(st->codec->codec_id) >> 3;
3106 case AVMEDIA_TYPE_VIDEO:
3107 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
3108 av_log(s, AV_LOG_ERROR, "time base not set\n");
3109 ret = AVERROR(EINVAL);
3112 if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){
3113 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
3114 ret = AVERROR(EINVAL);
3117 if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)
3118 && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(st->codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
3120 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");
3121 ret = AVERROR(EINVAL);
3127 if(s->oformat->codec_tag){
3128 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)){
3129 //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here
3130 st->codec->codec_tag= 0;
3132 if(st->codec->codec_tag){
3133 if (!validate_codec_tag(s, st)) {
3135 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);
3136 av_log(s, AV_LOG_ERROR,
3137 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
3138 tagbuf, st->codec->codec_tag, st->codec->codec_id);
3139 ret = AVERROR_INVALIDDATA;
3143 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
3146 if(s->oformat->flags & AVFMT_GLOBALHEADER &&
3147 !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))
3148 av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);
3151 if (!s->priv_data && s->oformat->priv_data_size > 0) {
3152 s->priv_data = av_mallocz(s->oformat->priv_data_size);
3153 if (!s->priv_data) {
3154 ret = AVERROR(ENOMEM);
3157 if (s->oformat->priv_class) {
3158 *(const AVClass**)s->priv_data= s->oformat->priv_class;
3159 av_opt_set_defaults(s->priv_data);
3160 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
3165 /* set muxer identification string */
3166 if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
3167 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
3170 if(s->oformat->write_header){
3171 ret = s->oformat->write_header(s);
3176 /* init PTS generation */
3177 for(i=0;i<s->nb_streams;i++) {
3178 int64_t den = AV_NOPTS_VALUE;
3181 switch (st->codec->codec_type) {
3182 case AVMEDIA_TYPE_AUDIO:
3183 den = (int64_t)st->time_base.num * st->codec->sample_rate;
3185 case AVMEDIA_TYPE_VIDEO:
3186 den = (int64_t)st->time_base.num * st->codec->time_base.den;
3191 if (den != AV_NOPTS_VALUE) {
3193 ret = AVERROR_INVALIDDATA;
3196 frac_init(&st->pts, 0, 0, den);
3201 av_dict_free(options);
3210 //FIXME merge with compute_pkt_fields
3211 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){
3212 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
3213 int num, den, frame_size, i;
3215 av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",
3216 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
3218 /* duration field */
3219 if (pkt->duration == 0) {
3220 compute_frame_duration(&num, &den, st, NULL, pkt);
3222 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
3226 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
3229 //XXX/FIXME this is a temporary hack until all encoders output pts
3230 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
3232 // pkt->pts= st->cur_dts;
3233 pkt->pts= st->pts.val;
3236 //calculate dts from pts
3237 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){
3238 st->pts_buffer[0]= pkt->pts;
3239 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
3240 st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;
3241 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
3242 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
3244 pkt->dts= st->pts_buffer[0];
3247 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)){
3248 av_log(s, AV_LOG_ERROR,
3249 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",
3250 st->index, st->cur_dts, pkt->dts);
3251 return AVERROR(EINVAL);
3253 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
3254 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
3255 return AVERROR(EINVAL);
3258 // av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
3259 st->cur_dts= pkt->dts;
3260 st->pts.val= pkt->dts;
3263 switch (st->codec->codec_type) {
3264 case AVMEDIA_TYPE_AUDIO:
3265 frame_size = get_audio_frame_size(st->codec, pkt->size);
3267 /* HACK/FIXME, we skip the initial 0 size packets as they are most
3268 likely equal to the encoder delay, but it would be better if we
3269 had the real timestamps from the encoder */
3270 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
3271 frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
3274 case AVMEDIA_TYPE_VIDEO:
3275 frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
3283 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
3285 int ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
3287 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3290 ret= s->oformat->write_packet(s, pkt);
3293 s->streams[pkt->stream_index]->nb_frames++;
3297 #define CHUNK_START 0x1000
3299 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
3300 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
3302 AVPacketList **next_point, *this_pktl;
3303 AVStream *st= s->streams[pkt->stream_index];
3304 int chunked= s->max_chunk_size || s->max_chunk_duration;
3306 this_pktl = av_mallocz(sizeof(AVPacketList));
3308 return AVERROR(ENOMEM);
3309 this_pktl->pkt= *pkt;
3310 pkt->destruct= NULL; // do not free original but only the copy
3311 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
3313 if(s->streams[pkt->stream_index]->last_in_packet_buffer){
3314 next_point = &(st->last_in_packet_buffer->next);
3316 next_point = &s->packet_buffer;
3321 uint64_t max= av_rescale_q(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base);
3322 if( st->interleaver_chunk_size + pkt->size <= s->max_chunk_size-1U
3323 && st->interleaver_chunk_duration + pkt->duration <= max-1U){
3324 st->interleaver_chunk_size += pkt->size;
3325 st->interleaver_chunk_duration += pkt->duration;
3328 st->interleaver_chunk_size =
3329 st->interleaver_chunk_duration = 0;
3330 this_pktl->pkt.flags |= CHUNK_START;
3334 if(compare(s, &s->packet_buffer_end->pkt, pkt)){
3336 && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
3337 || !compare(s, &(*next_point)->pkt, pkt))){
3338 next_point= &(*next_point)->next;
3343 next_point = &(s->packet_buffer_end->next);
3346 assert(!*next_point);
3348 s->packet_buffer_end= this_pktl;
3351 this_pktl->next= *next_point;
3353 s->streams[pkt->stream_index]->last_in_packet_buffer=
3354 *next_point= this_pktl;
3358 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
3360 AVStream *st = s->streams[ pkt ->stream_index];
3361 AVStream *st2= s->streams[ next->stream_index];
3362 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
3364 if(s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))){
3365 int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
3366 int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
3368 ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
3369 -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
3372 comp= (ts>ts2) - (ts<ts2);
3376 return pkt->stream_index < next->stream_index;
3380 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
3382 int stream_count=0, noninterleaved_count=0;
3383 int64_t delta_dts_max = 0;
3387 ret = ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
3392 for(i=0; i < s->nb_streams; i++) {
3393 if (s->streams[i]->last_in_packet_buffer) {
3395 } else if(s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3396 ++noninterleaved_count;
3400 if (s->nb_streams == stream_count) {
3403 for(i=0; i < s->nb_streams; i++) {
3404 if (s->streams[i]->last_in_packet_buffer) {
3406 av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
3407 s->streams[i]->time_base,
3409 av_rescale_q(s->packet_buffer->pkt.dts,
3410 s->streams[s->packet_buffer->pkt.stream_index]->time_base,
3412 delta_dts_max= FFMAX(delta_dts_max, delta_dts);
3415 if(s->nb_streams == stream_count+noninterleaved_count &&
3416 delta_dts_max > 20*AV_TIME_BASE) {
3417 av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
3421 if(stream_count && flush){
3422 pktl= s->packet_buffer;
3425 s->packet_buffer= pktl->next;
3426 if(!s->packet_buffer)
3427 s->packet_buffer_end= NULL;
3429 if(s->streams[out->stream_index]->last_in_packet_buffer == pktl)
3430 s->streams[out->stream_index]->last_in_packet_buffer= NULL;
3434 av_init_packet(out);
3440 * Interleave an AVPacket correctly so it can be muxed.
3441 * @param out the interleaved packet will be output here
3442 * @param in the input packet
3443 * @param flush 1 if no further packets are available as input and all
3444 * remaining packets should be output
3445 * @return 1 if a packet was output, 0 if no packet could be output,
3446 * < 0 if an error occurred
3448 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
3449 if(s->oformat->interleave_packet)
3450 return s->oformat->interleave_packet(s, out, in, flush);
3452 return av_interleave_packet_per_dts(s, out, in, flush);
3455 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
3456 AVStream *st= s->streams[ pkt->stream_index];
3459 //FIXME/XXX/HACK drop zero sized packets
3460 if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size==0)
3463 av_dlog(s, "av_interleaved_write_frame size:%d dts:%"PRId64" pts:%"PRId64"\n",
3464 pkt->size, pkt->dts, pkt->pts);
3465 if((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3468 if(pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
3469 return AVERROR(EINVAL);
3473 int ret= interleave_packet(s, &opkt, pkt, 0);
3474 if(ret<=0) //FIXME cleanup needed for ret<0 ?
3477 ret= s->oformat->write_packet(s, &opkt);
3479 s->streams[opkt.stream_index]->nb_frames++;
3481 av_free_packet(&opkt);
3486 if(s->pb && s->pb->error)
3487 return s->pb->error;
3491 int av_write_trailer(AVFormatContext *s)
3497 ret= interleave_packet(s, &pkt, NULL, 1);
3498 if(ret<0) //FIXME cleanup needed for ret<0 ?
3503 ret= s->oformat->write_packet(s, &pkt);
3505 s->streams[pkt.stream_index]->nb_frames++;
3507 av_free_packet(&pkt);
3511 if(s->pb && s->pb->error)
3515 if(s->oformat->write_trailer)
3516 ret = s->oformat->write_trailer(s);
3519 ret = s->pb ? s->pb->error : 0;
3520 for(i=0;i<s->nb_streams;i++) {
3521 av_freep(&s->streams[i]->priv_data);
3522 av_freep(&s->streams[i]->index_entries);
3524 if (s->oformat->priv_class)
3525 av_opt_free(s->priv_data);
3526 av_freep(&s->priv_data);
3530 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
3531 int64_t *dts, int64_t *wall)
3533 if (!s->oformat || !s->oformat->get_output_timestamp)
3534 return AVERROR(ENOSYS);
3535 s->oformat->get_output_timestamp(s, stream, dts, wall);
3539 void ff_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
3542 AVProgram *program=NULL;
3545 if (idx >= ac->nb_streams) {
3546 av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
3550 for(i=0; i<ac->nb_programs; i++){
3551 if(ac->programs[i]->id != progid)
3553 program = ac->programs[i];
3554 for(j=0; j<program->nb_stream_indexes; j++)
3555 if(program->stream_index[j] == idx)
3558 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
3561 program->stream_index = tmp;
3562 program->stream_index[program->nb_stream_indexes++] = idx;
3567 static void print_fps(double d, const char *postfix){
3568 uint64_t v= lrintf(d*100);
3569 if (v% 100 ) av_log(NULL, AV_LOG_INFO, ", %3.2f %s", d, postfix);
3570 else if(v%(100*1000)) av_log(NULL, AV_LOG_INFO, ", %1.0f %s", d, postfix);
3571 else av_log(NULL, AV_LOG_INFO, ", %1.0fk %s", d/1000, postfix);
3574 static void dump_metadata(void *ctx, AVDictionary *m, const char *indent)
3576 if(m && !(m->count == 1 && av_dict_get(m, "language", NULL, 0))){
3577 AVDictionaryEntry *tag=NULL;
3579 av_log(ctx, AV_LOG_INFO, "%sMetadata:\n", indent);
3580 while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
3581 if(strcmp("language", tag->key)){
3584 av_strlcpy(tmp, tag->value, sizeof(tmp));
3585 for(i=0; i<strlen(tmp); i++) if(tmp[i]==0xd) tmp[i]=' ';
3586 av_log(ctx, AV_LOG_INFO, "%s %-16s: %s\n", indent, tag->key, tmp);
3592 /* "user interface" functions */
3593 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
3596 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
3597 AVStream *st = ic->streams[i];
3598 int g = av_gcd(st->time_base.num, st->time_base.den);
3599 AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
3600 avcodec_string(buf, sizeof(buf), st->codec, is_output);
3601 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d", index, i);
3602 /* the pid is an important information, so we display it */
3603 /* XXX: add a generic system */
3604 if (flags & AVFMT_SHOW_IDS)
3605 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
3607 av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
3608 av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames, st->time_base.num/g, st->time_base.den/g);
3609 av_log(NULL, AV_LOG_INFO, ": %s", buf);
3610 if (st->sample_aspect_ratio.num && // default
3611 av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
3612 AVRational display_aspect_ratio;
3613 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
3614 st->codec->width*st->sample_aspect_ratio.num,
3615 st->codec->height*st->sample_aspect_ratio.den,
3617 av_log(NULL, AV_LOG_INFO, ", SAR %d:%d DAR %d:%d",
3618 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
3619 display_aspect_ratio.num, display_aspect_ratio.den);
3621 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
3622 if(st->avg_frame_rate.den && st->avg_frame_rate.num)
3623 print_fps(av_q2d(st->avg_frame_rate), "fps");
3624 if(st->r_frame_rate.den && st->r_frame_rate.num)
3625 print_fps(av_q2d(st->r_frame_rate), "tbr");
3626 if(st->time_base.den && st->time_base.num)
3627 print_fps(1/av_q2d(st->time_base), "tbn");
3628 if(st->codec->time_base.den && st->codec->time_base.num)
3629 print_fps(1/av_q2d(st->codec->time_base), "tbc");
3631 if (st->disposition & AV_DISPOSITION_DEFAULT)
3632 av_log(NULL, AV_LOG_INFO, " (default)");
3633 if (st->disposition & AV_DISPOSITION_DUB)
3634 av_log(NULL, AV_LOG_INFO, " (dub)");
3635 if (st->disposition & AV_DISPOSITION_ORIGINAL)
3636 av_log(NULL, AV_LOG_INFO, " (original)");
3637 if (st->disposition & AV_DISPOSITION_COMMENT)
3638 av_log(NULL, AV_LOG_INFO, " (comment)");
3639 if (st->disposition & AV_DISPOSITION_LYRICS)
3640 av_log(NULL, AV_LOG_INFO, " (lyrics)");
3641 if (st->disposition & AV_DISPOSITION_KARAOKE)
3642 av_log(NULL, AV_LOG_INFO, " (karaoke)");
3643 if (st->disposition & AV_DISPOSITION_FORCED)
3644 av_log(NULL, AV_LOG_INFO, " (forced)");
3645 if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
3646 av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
3647 if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
3648 av_log(NULL, AV_LOG_INFO, " (visual impaired)");
3649 if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
3650 av_log(NULL, AV_LOG_INFO, " (clean effects)");
3651 av_log(NULL, AV_LOG_INFO, "\n");
3652 dump_metadata(NULL, st->metadata, " ");
3655 #if FF_API_DUMP_FORMAT
3656 void dump_format(AVFormatContext *ic,
3661 av_dump_format(ic, index, url, is_output);
3665 void av_dump_format(AVFormatContext *ic,
3671 uint8_t *printed = ic->nb_streams ? av_mallocz(ic->nb_streams) : NULL;
3672 if (ic->nb_streams && !printed)
3675 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
3676 is_output ? "Output" : "Input",
3678 is_output ? ic->oformat->name : ic->iformat->name,
3679 is_output ? "to" : "from", url);
3680 dump_metadata(NULL, ic->metadata, " ");
3682 av_log(NULL, AV_LOG_INFO, " Duration: ");
3683 if (ic->duration != AV_NOPTS_VALUE) {
3684 int hours, mins, secs, us;
3685 secs = ic->duration / AV_TIME_BASE;
3686 us = ic->duration % AV_TIME_BASE;
3691 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
3692 (100 * us) / AV_TIME_BASE);
3694 av_log(NULL, AV_LOG_INFO, "N/A");
3696 if (ic->start_time != AV_NOPTS_VALUE) {
3698 av_log(NULL, AV_LOG_INFO, ", start: ");
3699 secs = ic->start_time / AV_TIME_BASE;
3700 us = abs(ic->start_time % AV_TIME_BASE);
3701 av_log(NULL, AV_LOG_INFO, "%d.%06d",
3702 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
3704 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
3706 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
3708 av_log(NULL, AV_LOG_INFO, "N/A");
3710 av_log(NULL, AV_LOG_INFO, "\n");
3712 for (i = 0; i < ic->nb_chapters; i++) {
3713 AVChapter *ch = ic->chapters[i];
3714 av_log(NULL, AV_LOG_INFO, " Chapter #%d.%d: ", index, i);
3715 av_log(NULL, AV_LOG_INFO, "start %f, ", ch->start * av_q2d(ch->time_base));
3716 av_log(NULL, AV_LOG_INFO, "end %f\n", ch->end * av_q2d(ch->time_base));
3718 dump_metadata(NULL, ch->metadata, " ");
3720 if(ic->nb_programs) {
3721 int j, k, total = 0;
3722 for(j=0; j<ic->nb_programs; j++) {
3723 AVDictionaryEntry *name = av_dict_get(ic->programs[j]->metadata,
3725 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
3726 name ? name->value : "");
3727 dump_metadata(NULL, ic->programs[j]->metadata, " ");
3728 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++) {
3729 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
3730 printed[ic->programs[j]->stream_index[k]] = 1;
3732 total += ic->programs[j]->nb_stream_indexes;
3734 if (total < ic->nb_streams)
3735 av_log(NULL, AV_LOG_INFO, " No Program\n");
3737 for(i=0;i<ic->nb_streams;i++)
3739 dump_stream_format(ic, i, index, is_output);
3744 int64_t av_gettime(void)
3747 gettimeofday(&tv,NULL);
3748 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
3751 uint64_t ff_ntp_time(void)
3753 return (av_gettime() / 1000) * 1000 + NTP_OFFSET_US;
3756 #if FF_API_PARSE_DATE
3757 #include "libavutil/parseutils.h"
3759 int64_t parse_date(const char *timestr, int duration)
3762 av_parse_time(&timeval, timestr, duration);
3767 #if FF_API_FIND_INFO_TAG
3768 #include "libavutil/parseutils.h"
3770 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
3772 return av_find_info_tag(arg, arg_size, tag1, info);
3776 int av_get_frame_filename(char *buf, int buf_size,
3777 const char *path, int number)
3780 char *q, buf1[20], c;
3781 int nd, len, percentd_found;
3793 while (isdigit(*p)) {
3794 nd = nd * 10 + *p++ - '0';
3797 } while (isdigit(c));
3806 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3808 if ((q - buf + len) > buf_size - 1)
3810 memcpy(q, buf1, len);
3818 if ((q - buf) < buf_size - 1)
3822 if (!percentd_found)
3831 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3835 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3837 for(i=0;i<size;i+=16) {
3844 PRINT(" %02x", buf[i+j]);
3849 for(j=0;j<len;j++) {
3851 if (c < ' ' || c > '~')
3860 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3862 hex_dump_internal(NULL, f, 0, buf, size);
3865 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3867 hex_dump_internal(avcl, NULL, level, buf, size);
3870 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload, AVRational time_base)
3873 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3874 PRINT("stream #%d:\n", pkt->stream_index);
3875 PRINT(" keyframe=%d\n", ((pkt->flags & AV_PKT_FLAG_KEY) != 0));
3876 PRINT(" duration=%0.3f\n", pkt->duration * av_q2d(time_base));
3877 /* DTS is _always_ valid after av_read_frame() */
3879 if (pkt->dts == AV_NOPTS_VALUE)
3882 PRINT("%0.3f", pkt->dts * av_q2d(time_base));
3883 /* PTS may not be known if B-frames are present. */
3885 if (pkt->pts == AV_NOPTS_VALUE)
3888 PRINT("%0.3f", pkt->pts * av_q2d(time_base));
3890 PRINT(" size=%d\n", pkt->size);
3893 av_hex_dump(f, pkt->data, pkt->size);
3897 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3899 AVRational tb = { 1, AV_TIME_BASE };
3900 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, tb);
3904 void av_pkt_dump2(FILE *f, AVPacket *pkt, int dump_payload, AVStream *st)
3906 pkt_dump_internal(NULL, f, 0, pkt, dump_payload, st->time_base);
3910 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3912 AVRational tb = { 1, AV_TIME_BASE };
3913 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, tb);
3917 void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload,
3920 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload, st->time_base);
3923 void av_url_split(char *proto, int proto_size,
3924 char *authorization, int authorization_size,
3925 char *hostname, int hostname_size,
3927 char *path, int path_size,
3930 const char *p, *ls, *at, *col, *brk;
3932 if (port_ptr) *port_ptr = -1;
3933 if (proto_size > 0) proto[0] = 0;
3934 if (authorization_size > 0) authorization[0] = 0;
3935 if (hostname_size > 0) hostname[0] = 0;
3936 if (path_size > 0) path[0] = 0;
3938 /* parse protocol */
3939 if ((p = strchr(url, ':'))) {
3940 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3945 /* no protocol means plain filename */
3946 av_strlcpy(path, url, path_size);
3950 /* separate path from hostname */
3951 ls = strchr(p, '/');
3953 ls = strchr(p, '?');
3955 av_strlcpy(path, ls, path_size);
3957 ls = &p[strlen(p)]; // XXX
3959 /* the rest is hostname, use that to parse auth/port */
3961 /* authorization (user[:pass]@hostname) */
3962 if ((at = strchr(p, '@')) && at < ls) {
3963 av_strlcpy(authorization, p,
3964 FFMIN(authorization_size, at + 1 - p));
3965 p = at + 1; /* skip '@' */
3968 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3970 av_strlcpy(hostname, p + 1,
3971 FFMIN(hostname_size, brk - p));
3972 if (brk[1] == ':' && port_ptr)
3973 *port_ptr = atoi(brk + 2);
3974 } else if ((col = strchr(p, ':')) && col < ls) {
3975 av_strlcpy(hostname, p,
3976 FFMIN(col + 1 - p, hostname_size));
3977 if (port_ptr) *port_ptr = atoi(col + 1);
3979 av_strlcpy(hostname, p,
3980 FFMIN(ls + 1 - p, hostname_size));
3984 char *ff_data_to_hex(char *buff, const uint8_t *src, int s, int lowercase)
3987 static const char hex_table_uc[16] = { '0', '1', '2', '3',
3990 'C', 'D', 'E', 'F' };
3991 static const char hex_table_lc[16] = { '0', '1', '2', '3',
3994 'c', 'd', 'e', 'f' };
3995 const char *hex_table = lowercase ? hex_table_lc : hex_table_uc;
3997 for(i = 0; i < s; i++) {
3998 buff[i * 2] = hex_table[src[i] >> 4];
3999 buff[i * 2 + 1] = hex_table[src[i] & 0xF];
4005 int ff_hex_to_data(uint8_t *data, const char *p)
4012 p += strspn(p, SPACE_CHARS);
4015 c = toupper((unsigned char) *p++);
4016 if (c >= '0' && c <= '9')
4018 else if (c >= 'A' && c <= 'F')
4033 #if FF_API_SET_PTS_INFO
4034 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
4035 unsigned int pts_num, unsigned int pts_den)
4037 avpriv_set_pts_info(s, pts_wrap_bits, pts_num, pts_den);
4041 void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits,
4042 unsigned int pts_num, unsigned int pts_den)
4045 if(av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)){
4046 if(new_tb.num != pts_num)
4047 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, pts_num/new_tb.num);
4049 av_log(NULL, AV_LOG_WARNING, "st:%d has too large timebase, reducing\n", s->index);
4051 if(new_tb.num <= 0 || new_tb.den <= 0) {
4052 av_log(NULL, AV_LOG_ERROR, "Ignoring attempt to set invalid timebase for st:%d\n", s->index);
4055 s->time_base = new_tb;
4056 s->pts_wrap_bits = pts_wrap_bits;
4059 int ff_url_join(char *str, int size, const char *proto,
4060 const char *authorization, const char *hostname,
4061 int port, const char *fmt, ...)
4064 struct addrinfo hints, *ai;
4069 av_strlcatf(str, size, "%s://", proto);
4070 if (authorization && authorization[0])
4071 av_strlcatf(str, size, "%s@", authorization);
4072 #if CONFIG_NETWORK && defined(AF_INET6)
4073 /* Determine if hostname is a numerical IPv6 address,
4074 * properly escape it within [] in that case. */
4075 memset(&hints, 0, sizeof(hints));
4076 hints.ai_flags = AI_NUMERICHOST;
4077 if (!getaddrinfo(hostname, NULL, &hints, &ai)) {
4078 if (ai->ai_family == AF_INET6) {
4079 av_strlcat(str, "[", size);
4080 av_strlcat(str, hostname, size);
4081 av_strlcat(str, "]", size);
4083 av_strlcat(str, hostname, size);
4088 /* Not an IPv6 address, just output the plain string. */
4089 av_strlcat(str, hostname, size);
4092 av_strlcatf(str, size, ":%d", port);
4095 int len = strlen(str);
4098 vsnprintf(str + len, size > len ? size - len : 0, fmt, vl);
4104 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
4105 AVFormatContext *src)
4110 local_pkt.stream_index = dst_stream;
4111 if (pkt->pts != AV_NOPTS_VALUE)
4112 local_pkt.pts = av_rescale_q(pkt->pts,
4113 src->streams[pkt->stream_index]->time_base,
4114 dst->streams[dst_stream]->time_base);
4115 if (pkt->dts != AV_NOPTS_VALUE)
4116 local_pkt.dts = av_rescale_q(pkt->dts,
4117 src->streams[pkt->stream_index]->time_base,
4118 dst->streams[dst_stream]->time_base);
4119 return av_write_frame(dst, &local_pkt);
4122 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
4125 const char *ptr = str;
4127 /* Parse key=value pairs. */
4130 char *dest = NULL, *dest_end;
4131 int key_len, dest_len = 0;
4133 /* Skip whitespace and potential commas. */
4134 while (*ptr && (isspace(*ptr) || *ptr == ','))
4141 if (!(ptr = strchr(key, '=')))
4144 key_len = ptr - key;
4146 callback_get_buf(context, key, key_len, &dest, &dest_len);
4147 dest_end = dest + dest_len - 1;
4151 while (*ptr && *ptr != '\"') {
4155 if (dest && dest < dest_end)
4159 if (dest && dest < dest_end)
4167 for (; *ptr && !(isspace(*ptr) || *ptr == ','); ptr++)
4168 if (dest && dest < dest_end)
4176 int ff_find_stream_index(AVFormatContext *s, int id)
4179 for (i = 0; i < s->nb_streams; i++) {
4180 if (s->streams[i]->id == id)
4186 void ff_make_absolute_url(char *buf, int size, const char *base,
4190 /* Absolute path, relative to the current server */
4191 if (base && strstr(base, "://") && rel[0] == '/') {
4193 av_strlcpy(buf, base, size);
4194 sep = strstr(buf, "://");
4197 sep = strchr(sep, '/');
4201 av_strlcat(buf, rel, size);
4204 /* If rel actually is an absolute url, just copy it */
4205 if (!base || strstr(rel, "://") || rel[0] == '/') {
4206 av_strlcpy(buf, rel, size);
4210 av_strlcpy(buf, base, size);
4211 /* Remove the file name from the base url */
4212 sep = strrchr(buf, '/');
4217 while (av_strstart(rel, "../", NULL) && sep) {
4218 /* Remove the path delimiter at the end */
4220 sep = strrchr(buf, '/');
4221 /* If the next directory name to pop off is "..", break here */
4222 if (!strcmp(sep ? &sep[1] : buf, "..")) {
4223 /* Readd the slash we just removed */
4224 av_strlcat(buf, "/", size);
4227 /* Cut off the directory name */
4234 av_strlcat(buf, rel, size);
4237 int64_t ff_iso8601_to_unix_time(const char *datestr)
4240 struct tm time1 = {0}, time2 = {0};
4242 ret1 = strptime(datestr, "%Y - %m - %d %T", &time1);
4243 ret2 = strptime(datestr, "%Y - %m - %dT%T", &time2);
4245 return av_timegm(&time2);
4247 return av_timegm(&time1);
4249 av_log(NULL, AV_LOG_WARNING, "strptime() unavailable on this system, cannot convert "
4250 "the date string.\n");
4255 int avformat_query_codec(AVOutputFormat *ofmt, enum CodecID codec_id, int std_compliance)
4258 if (ofmt->query_codec)
4259 return ofmt->query_codec(codec_id, std_compliance);
4260 else if (ofmt->codec_tag)
4261 return !!av_codec_get_tag(ofmt->codec_tag, codec_id);
4262 else if (codec_id == ofmt->video_codec || codec_id == ofmt->audio_codec ||
4263 codec_id == ofmt->subtitle_codec)
4266 return AVERROR_PATCHWELCOME;
4269 int avformat_network_init(void)
4273 ff_network_inited_globally = 1;
4274 if ((ret = ff_network_init()) < 0)
4281 int avformat_network_deinit(void)