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
22 #include "libavcodec/opt.h"
23 #include "libavutil/avstring.h"
32 * @file libavformat/utils.c
33 * various utility functions for use within FFmpeg
36 unsigned avformat_version(void)
38 return LIBAVFORMAT_VERSION_INT;
41 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
42 static void av_frac_add(AVFrac *f, int64_t incr);
44 /** head of registered input format linked list */
45 AVInputFormat *first_iformat = NULL;
46 /** head of registered output format linked list */
47 AVOutputFormat *first_oformat = NULL;
49 AVInputFormat *av_iformat_next(AVInputFormat *f)
52 else return first_iformat;
55 AVOutputFormat *av_oformat_next(AVOutputFormat *f)
58 else return first_oformat;
61 void av_register_input_format(AVInputFormat *format)
65 while (*p != NULL) p = &(*p)->next;
70 void av_register_output_format(AVOutputFormat *format)
74 while (*p != NULL) p = &(*p)->next;
79 int match_ext(const char *filename, const char *extensions)
87 ext = strrchr(filename, '.');
93 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
96 if (!strcasecmp(ext1, ext))
106 AVOutputFormat *guess_format(const char *short_name, const char *filename,
107 const char *mime_type)
109 AVOutputFormat *fmt, *fmt_found;
110 int score_max, score;
112 /* specific test for image sequences */
113 #ifdef CONFIG_IMAGE2_MUXER
114 if (!short_name && filename &&
115 av_filename_number_test(filename) &&
116 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
117 return guess_format("image2", NULL, NULL);
120 /* Find the proper file type. */
124 while (fmt != NULL) {
126 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
128 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
130 if (filename && fmt->extensions &&
131 match_ext(filename, fmt->extensions)) {
134 if (score > score_max) {
143 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
144 const char *mime_type)
146 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
149 AVOutputFormat *stream_fmt;
150 char stream_format_name[64];
152 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
153 stream_fmt = guess_format(stream_format_name, NULL, NULL);
162 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
163 const char *filename, const char *mime_type, enum CodecType type){
164 if(type == CODEC_TYPE_VIDEO){
165 enum CodecID codec_id= CODEC_ID_NONE;
167 #ifdef CONFIG_IMAGE2_MUXER
168 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
169 codec_id= av_guess_image2_codec(filename);
172 if(codec_id == CODEC_ID_NONE)
173 codec_id= fmt->video_codec;
175 }else if(type == CODEC_TYPE_AUDIO)
176 return fmt->audio_codec;
178 return CODEC_ID_NONE;
181 AVInputFormat *av_find_input_format(const char *short_name)
184 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
185 if (!strcmp(fmt->name, short_name))
191 /* memory handling */
193 void av_destruct_packet(AVPacket *pkt)
196 pkt->data = NULL; pkt->size = 0;
199 void av_init_packet(AVPacket *pkt)
201 pkt->pts = AV_NOPTS_VALUE;
202 pkt->dts = AV_NOPTS_VALUE;
206 pkt->stream_index = 0;
207 pkt->destruct= av_destruct_packet_nofree;
210 int av_new_packet(AVPacket *pkt, int size)
213 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
214 return AVERROR(ENOMEM);
215 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
217 return AVERROR(ENOMEM);
218 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
223 pkt->destruct = av_destruct_packet;
227 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
229 int ret= av_new_packet(pkt, size);
234 pkt->pos= url_ftell(s);
236 ret= get_buffer(s, pkt->data, size);
245 int av_dup_packet(AVPacket *pkt)
247 if (pkt->destruct != av_destruct_packet) {
249 /* We duplicate the packet and don't forget to add the padding again. */
250 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
251 return AVERROR(ENOMEM);
252 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
254 return AVERROR(ENOMEM);
256 memcpy(data, pkt->data, pkt->size);
257 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
259 pkt->destruct = av_destruct_packet;
264 int av_filename_number_test(const char *filename)
267 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
270 static AVInputFormat *av_probe_input_format2(AVProbeData *pd, int is_opened, int *score_max)
272 AVInputFormat *fmt1, *fmt;
276 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
277 if (!is_opened == !(fmt1->flags & AVFMT_NOFILE))
280 if (fmt1->read_probe) {
281 score = fmt1->read_probe(pd);
282 } else if (fmt1->extensions) {
283 if (match_ext(pd->filename, fmt1->extensions)) {
287 if (score > *score_max) {
290 }else if (score == *score_max)
296 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened){
298 return av_probe_input_format2(pd, is_opened, &score);
301 static int set_codec_from_probe_data(AVStream *st, AVProbeData *pd, int score)
304 fmt = av_probe_input_format2(pd, 1, &score);
307 if (!strcmp(fmt->name, "mp3"))
308 st->codec->codec_id = CODEC_ID_MP3;
309 else if (!strcmp(fmt->name, "ac3"))
310 st->codec->codec_id = CODEC_ID_AC3;
311 else if (!strcmp(fmt->name, "mpegvideo"))
312 st->codec->codec_id = CODEC_ID_MPEG2VIDEO;
313 else if (!strcmp(fmt->name, "h264"))
314 st->codec->codec_id = CODEC_ID_H264;
319 /************************************************************/
320 /* input media file */
323 * Open a media file from an IO stream. 'fmt' must be specified.
325 static const char* format_to_name(void* ptr)
327 AVFormatContext* fc = (AVFormatContext*) ptr;
328 if(fc->iformat) return fc->iformat->name;
329 else if(fc->oformat) return fc->oformat->name;
333 #define OFFSET(x) offsetof(AVFormatContext,x)
334 #define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
335 //these names are too long to be readable
336 #define E AV_OPT_FLAG_ENCODING_PARAM
337 #define D AV_OPT_FLAG_DECODING_PARAM
339 static const AVOption options[]={
340 {"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
341 {"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
342 {"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
343 {"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D|E, "fflags"},
344 {"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
345 {"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
346 {"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
347 {"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
348 {"analyzeduration", "how many microseconds are analyzed to estimate duration", OFFSET(max_analyze_duration), FF_OPT_TYPE_INT, 3*AV_TIME_BASE, 0, INT_MAX, D},
349 {"cryptokey", "decryption key", OFFSET(key), FF_OPT_TYPE_BINARY, 0, 0, 0, D},
350 {"indexmem", "max memory used for timestamp index (per stream)", OFFSET(max_index_size), FF_OPT_TYPE_INT, 1<<20, 0, INT_MAX, D},
351 {"rtbufsize", "max memory used for buffering real-time frames", OFFSET(max_picture_buffer), FF_OPT_TYPE_INT, 3041280, 0, INT_MAX, D}, /* defaults to 1s of 15fps 352x288 YUYV422 video */
352 {"fdebug", "print specific debug info", OFFSET(debug), FF_OPT_TYPE_FLAGS, DEFAULT, 0, INT_MAX, E|D, "fdebug"},
353 {"ts", NULL, 0, FF_OPT_TYPE_CONST, FF_FDEBUG_TS, INT_MIN, INT_MAX, E|D, "fdebug"},
361 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
363 static void avformat_get_context_defaults(AVFormatContext *s)
365 memset(s, 0, sizeof(AVFormatContext));
367 s->av_class = &av_format_context_class;
369 av_opt_set_defaults(s);
372 AVFormatContext *av_alloc_format_context(void)
375 ic = av_malloc(sizeof(AVFormatContext));
377 avformat_get_context_defaults(ic);
378 ic->av_class = &av_format_context_class;
382 int av_open_input_stream(AVFormatContext **ic_ptr,
383 ByteIOContext *pb, const char *filename,
384 AVInputFormat *fmt, AVFormatParameters *ap)
388 AVFormatParameters default_ap;
392 memset(ap, 0, sizeof(default_ap));
395 if(!ap->prealloced_context)
396 ic = av_alloc_format_context();
400 err = AVERROR(ENOMEM);
405 ic->duration = AV_NOPTS_VALUE;
406 ic->start_time = AV_NOPTS_VALUE;
407 av_strlcpy(ic->filename, filename, sizeof(ic->filename));
409 /* allocate private data */
410 if (fmt->priv_data_size > 0) {
411 ic->priv_data = av_mallocz(fmt->priv_data_size);
412 if (!ic->priv_data) {
413 err = AVERROR(ENOMEM);
417 ic->priv_data = NULL;
420 if (ic->iformat->read_header) {
421 err = ic->iformat->read_header(ic, ap);
426 if (pb && !ic->data_offset)
427 ic->data_offset = url_ftell(ic->pb);
434 av_freep(&ic->priv_data);
435 for(i=0;i<ic->nb_streams;i++) {
436 AVStream *st = ic->streams[i];
438 av_free(st->priv_data);
439 av_free(st->codec->extradata);
449 /** size of probe buffer, for guessing file type from file contents */
450 #define PROBE_BUF_MIN 2048
451 #define PROBE_BUF_MAX (1<<20)
453 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
456 AVFormatParameters *ap)
459 AVProbeData probe_data, *pd = &probe_data;
460 ByteIOContext *pb = NULL;
464 pd->filename = filename;
469 /* guess format if no file can be opened */
470 fmt = av_probe_input_format(pd, 0);
473 /* Do not open file if the format does not need it. XXX: specific
474 hack needed to handle RTSP/TCP */
475 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
476 /* if no file needed do not try to open one */
477 if ((err=url_fopen(&pb, filename, URL_RDONLY)) < 0) {
481 url_setbufsize(pb, buf_size);
484 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
485 int score= probe_size < PROBE_BUF_MAX ? AVPROBE_SCORE_MAX/4 : 0;
486 /* read probe data */
487 pd->buf= av_realloc(pd->buf, probe_size + AVPROBE_PADDING_SIZE);
488 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
489 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
490 if (url_fseek(pb, 0, SEEK_SET) < 0) {
492 if (url_fopen(&pb, filename, URL_RDONLY) < 0) {
498 /* guess file format */
499 fmt = av_probe_input_format2(pd, 1, &score);
504 /* if still no format found, error */
510 /* check filename in case an image number is expected */
511 if (fmt->flags & AVFMT_NEEDNUMBER) {
512 if (!av_filename_number_test(filename)) {
513 err = AVERROR_NUMEXPECTED;
517 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
530 /*******************************************************/
532 static AVPacket *add_to_pktbuf(AVPacketList **packet_buffer, AVPacket *pkt,
533 AVPacketList **plast_pktl){
534 AVPacketList *pktl = av_mallocz(sizeof(AVPacketList));
539 (*plast_pktl)->next = pktl;
541 *packet_buffer = pktl;
543 /* add the packet in the buffered packet list */
549 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
555 AVPacketList *pktl = s->raw_packet_buffer;
559 if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE){
560 s->raw_packet_buffer = pktl->next;
567 ret= s->iformat->read_packet(s, pkt);
570 st= s->streams[pkt->stream_index];
572 switch(st->codec->codec_type){
573 case CODEC_TYPE_VIDEO:
574 if(s->video_codec_id) st->codec->codec_id= s->video_codec_id;
576 case CODEC_TYPE_AUDIO:
577 if(s->audio_codec_id) st->codec->codec_id= s->audio_codec_id;
579 case CODEC_TYPE_SUBTITLE:
580 if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;
584 if(!pktl && st->codec->codec_id!=CODEC_ID_PROBE)
587 add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);
589 if(st->codec->codec_id == CODEC_ID_PROBE){
590 AVProbeData *pd = &st->probe_data;
592 pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);
593 memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);
594 pd->buf_size += pkt->size;
595 memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);
597 if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){
598 set_codec_from_probe_data(st, pd, 1);
599 if(st->codec->codec_id != CODEC_ID_PROBE){
608 /**********************************************************/
611 * Get the number of samples of an audio frame. Return -1 on error.
613 static int get_audio_frame_size(AVCodecContext *enc, int size)
617 if(enc->codec_id == CODEC_ID_VORBIS)
620 if (enc->frame_size <= 1) {
621 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
623 if (bits_per_sample) {
624 if (enc->channels == 0)
626 frame_size = (size << 3) / (bits_per_sample * enc->channels);
628 /* used for example by ADPCM codecs */
629 if (enc->bit_rate == 0)
631 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
634 frame_size = enc->frame_size;
641 * Return the frame duration in seconds. Return 0 if not available.
643 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
644 AVCodecParserContext *pc, AVPacket *pkt)
650 switch(st->codec->codec_type) {
651 case CODEC_TYPE_VIDEO:
652 if(st->time_base.num*1000LL > st->time_base.den){
653 *pnum = st->time_base.num;
654 *pden = st->time_base.den;
655 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
656 *pnum = st->codec->time_base.num;
657 *pden = st->codec->time_base.den;
658 if (pc && pc->repeat_pict) {
660 *pnum = (*pnum) * (2 + pc->repeat_pict);
664 case CODEC_TYPE_AUDIO:
665 frame_size = get_audio_frame_size(st->codec, pkt->size);
669 *pden = st->codec->sample_rate;
676 static int is_intra_only(AVCodecContext *enc){
677 if(enc->codec_type == CODEC_TYPE_AUDIO){
679 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
680 switch(enc->codec_id){
682 case CODEC_ID_MJPEGB:
684 case CODEC_ID_RAWVIDEO:
685 case CODEC_ID_DVVIDEO:
686 case CODEC_ID_HUFFYUV:
687 case CODEC_ID_FFVHUFF:
698 static void update_initial_timestamps(AVFormatContext *s, int stream_index,
699 int64_t dts, int64_t pts)
701 AVStream *st= s->streams[stream_index];
702 AVPacketList *pktl= s->packet_buffer;
704 if(st->first_dts != AV_NOPTS_VALUE || dts == AV_NOPTS_VALUE || st->cur_dts == AV_NOPTS_VALUE)
707 st->first_dts= dts - st->cur_dts;
710 for(; pktl; pktl= pktl->next){
711 if(pktl->pkt.stream_index != stream_index)
713 //FIXME think more about this check
714 if(pktl->pkt.pts != AV_NOPTS_VALUE && pktl->pkt.pts == pktl->pkt.dts)
715 pktl->pkt.pts += st->first_dts;
717 if(pktl->pkt.dts != AV_NOPTS_VALUE)
718 pktl->pkt.dts += st->first_dts;
720 if(st->start_time == AV_NOPTS_VALUE && pktl->pkt.pts != AV_NOPTS_VALUE)
721 st->start_time= pktl->pkt.pts;
723 if (st->start_time == AV_NOPTS_VALUE)
724 st->start_time = pts;
727 static void update_initial_durations(AVFormatContext *s, AVStream *st, AVPacket *pkt)
729 AVPacketList *pktl= s->packet_buffer;
732 if(st->first_dts != AV_NOPTS_VALUE){
733 cur_dts= st->first_dts;
734 for(; pktl; pktl= pktl->next){
735 if(pktl->pkt.stream_index == pkt->stream_index){
736 if(pktl->pkt.pts != pktl->pkt.dts || pktl->pkt.dts != AV_NOPTS_VALUE || pktl->pkt.duration)
738 cur_dts -= pkt->duration;
741 pktl= s->packet_buffer;
742 st->first_dts = cur_dts;
743 }else if(st->cur_dts)
746 for(; pktl; pktl= pktl->next){
747 if(pktl->pkt.stream_index != pkt->stream_index)
749 if(pktl->pkt.pts == pktl->pkt.dts && pktl->pkt.dts == AV_NOPTS_VALUE
750 && !pktl->pkt.duration){
751 pktl->pkt.dts= cur_dts;
752 if(!st->codec->has_b_frames)
753 pktl->pkt.pts= cur_dts;
754 cur_dts += pkt->duration;
755 pktl->pkt.duration= pkt->duration;
759 if(st->first_dts == AV_NOPTS_VALUE)
760 st->cur_dts= cur_dts;
763 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
764 AVCodecParserContext *pc, AVPacket *pkt)
766 int num, den, presentation_delayed, delay, i;
769 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63
770 /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){
771 pkt->dts -= 1LL<<st->pts_wrap_bits;
774 if (pkt->duration == 0) {
775 compute_frame_duration(&num, &den, st, pc, pkt);
777 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
779 if(pkt->duration != 0 && s->packet_buffer)
780 update_initial_durations(s, st, pkt);
784 /* correct timestamps with byte offset if demuxers only have timestamps
785 on packet boundaries */
786 if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){
787 /* this will estimate bitrate based on this frame's duration and size */
788 offset = av_rescale(pc->offset, pkt->duration, pkt->size);
789 if(pkt->pts != AV_NOPTS_VALUE)
791 if(pkt->dts != AV_NOPTS_VALUE)
795 /* do we have a video B-frame ? */
796 delay= st->codec->has_b_frames;
797 presentation_delayed = 0;
798 /* XXX: need has_b_frame, but cannot get it if the codec is
801 pc && pc->pict_type != FF_B_TYPE)
802 presentation_delayed = 1;
803 /* This may be redundant, but it should not hurt. */
804 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
805 presentation_delayed = 1;
807 // 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);
808 /* interpolate PTS and DTS if they are not present */
809 if(delay==0 || (delay==1 && pc)){
810 if (presentation_delayed) {
811 /* DTS = decompression timestamp */
812 /* PTS = presentation timestamp */
813 if (pkt->dts == AV_NOPTS_VALUE)
814 pkt->dts = st->last_IP_pts;
815 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);
816 if (pkt->dts == AV_NOPTS_VALUE)
817 pkt->dts = st->cur_dts;
819 /* this is tricky: the dts must be incremented by the duration
820 of the frame we are displaying, i.e. the last I- or P-frame */
821 if (st->last_IP_duration == 0)
822 st->last_IP_duration = pkt->duration;
823 if(pkt->dts != AV_NOPTS_VALUE)
824 st->cur_dts = pkt->dts + st->last_IP_duration;
825 st->last_IP_duration = pkt->duration;
826 st->last_IP_pts= pkt->pts;
827 /* cannot compute PTS if not present (we can compute it only
828 by knowing the future */
829 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
830 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
831 int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);
832 int64_t new_diff= FFABS(st->cur_dts - pkt->pts);
833 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
834 pkt->pts += pkt->duration;
835 // 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);
839 /* presentation is not delayed : PTS and DTS are the same */
840 if(pkt->pts == AV_NOPTS_VALUE)
842 update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);
843 if(pkt->pts == AV_NOPTS_VALUE)
844 pkt->pts = st->cur_dts;
846 if(pkt->pts != AV_NOPTS_VALUE)
847 st->cur_dts = pkt->pts + pkt->duration;
851 if(pkt->pts != AV_NOPTS_VALUE){
852 st->pts_buffer[0]= pkt->pts;
853 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
854 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
855 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
856 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
857 if(pkt->dts == AV_NOPTS_VALUE)
858 pkt->dts= st->pts_buffer[0];
860 update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet
862 if(pkt->dts > st->cur_dts)
863 st->cur_dts = pkt->dts;
866 // 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);
869 if(is_intra_only(st->codec))
870 pkt->flags |= PKT_FLAG_KEY;
873 /* keyframe computation */
874 if (pc->pict_type == FF_I_TYPE)
875 pkt->flags |= PKT_FLAG_KEY;
879 void av_destruct_packet_nofree(AVPacket *pkt)
881 pkt->data = NULL; pkt->size = 0;
884 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
892 /* select current input stream component */
895 if (!st->need_parsing || !st->parser) {
896 /* no parsing needed: we just output the packet as is */
897 /* raw data support */
899 compute_pkt_fields(s, st, NULL, pkt);
902 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
903 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
904 s->cur_ptr, s->cur_len,
905 s->cur_pkt.pts, s->cur_pkt.dts);
906 s->cur_pkt.pts = AV_NOPTS_VALUE;
907 s->cur_pkt.dts = AV_NOPTS_VALUE;
908 /* increment read pointer */
912 /* return packet if any */
915 pkt->pos = s->cur_pkt.pos; // Isn't quite accurate but close.
917 pkt->stream_index = st->index;
918 pkt->pts = st->parser->pts;
919 pkt->dts = st->parser->dts;
920 pkt->destruct = av_destruct_packet_nofree;
921 compute_pkt_fields(s, st, st->parser, pkt);
923 if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & PKT_FLAG_KEY){
924 ff_reduce_index(s, st->index);
925 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
926 0, 0, AVINDEX_KEYFRAME);
933 av_free_packet(&s->cur_pkt);
937 /* read next packet */
938 ret = av_read_packet(s, &s->cur_pkt);
940 if (ret == AVERROR(EAGAIN))
942 /* return the last frames, if any */
943 for(i = 0; i < s->nb_streams; i++) {
945 if (st->parser && st->need_parsing) {
946 av_parser_parse(st->parser, st->codec,
947 &pkt->data, &pkt->size,
949 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
954 /* no more packets: really terminate parsing */
958 if(s->cur_pkt.pts != AV_NOPTS_VALUE &&
959 s->cur_pkt.dts != AV_NOPTS_VALUE &&
960 s->cur_pkt.pts < s->cur_pkt.dts){
961 av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",
962 s->cur_pkt.stream_index,
966 // av_free_packet(&s->cur_pkt);
970 st = s->streams[s->cur_pkt.stream_index];
971 if(s->debug & FF_FDEBUG_TS)
972 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
973 s->cur_pkt.stream_index,
980 s->cur_ptr = s->cur_pkt.data;
981 s->cur_len = s->cur_pkt.size;
982 if (st->need_parsing && !st->parser) {
983 st->parser = av_parser_init(st->codec->codec_id);
985 /* no parser available: just output the raw packets */
986 st->need_parsing = AVSTREAM_PARSE_NONE;
987 }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){
988 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
990 if(st->parser && (s->iformat->flags & AVFMT_GENERIC_INDEX)){
991 st->parser->next_frame_offset=
992 st->parser->cur_offset= s->cur_pkt.pos;
997 if(s->debug & FF_FDEBUG_TS)
998 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, flags=%d\n",
1008 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1012 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1015 pktl = s->packet_buffer;
1017 AVPacket *next_pkt= &pktl->pkt;
1019 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1020 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1021 if( pktl->pkt.stream_index == next_pkt->stream_index
1022 && next_pkt->dts < pktl->pkt.dts
1023 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1024 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1025 next_pkt->pts= pktl->pkt.dts;
1029 pktl = s->packet_buffer;
1032 if( next_pkt->pts != AV_NOPTS_VALUE
1033 || next_pkt->dts == AV_NOPTS_VALUE
1035 /* read packet from packet buffer, if there is data */
1037 s->packet_buffer = pktl->next;
1043 int ret= av_read_frame_internal(s, pkt);
1045 if(pktl && ret != AVERROR(EAGAIN)){
1052 if(av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,
1053 &s->packet_buffer_end)) < 0)
1054 return AVERROR(ENOMEM);
1056 assert(!s->packet_buffer);
1057 return av_read_frame_internal(s, pkt);
1062 /* XXX: suppress the packet queue */
1063 static void flush_packet_queue(AVFormatContext *s)
1068 pktl = s->packet_buffer;
1071 s->packet_buffer = pktl->next;
1072 av_free_packet(&pktl->pkt);
1077 /*******************************************************/
1080 int av_find_default_stream_index(AVFormatContext *s)
1082 int first_audio_index = -1;
1086 if (s->nb_streams <= 0)
1088 for(i = 0; i < s->nb_streams; i++) {
1090 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1093 if (first_audio_index < 0 && st->codec->codec_type == CODEC_TYPE_AUDIO)
1094 first_audio_index = i;
1096 return first_audio_index >= 0 ? first_audio_index : 0;
1100 * Flush the frame reader.
1102 static void av_read_frame_flush(AVFormatContext *s)
1107 flush_packet_queue(s);
1109 /* free previous packet */
1111 if (s->cur_st->parser)
1112 av_free_packet(&s->cur_pkt);
1119 /* for each stream, reset read state */
1120 for(i = 0; i < s->nb_streams; i++) {
1124 av_parser_close(st->parser);
1127 st->last_IP_pts = AV_NOPTS_VALUE;
1128 st->cur_dts = AV_NOPTS_VALUE; /* we set the current DTS to an unspecified origin */
1132 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1135 for(i = 0; i < s->nb_streams; i++) {
1136 AVStream *st = s->streams[i];
1138 st->cur_dts = av_rescale(timestamp,
1139 st->time_base.den * (int64_t)ref_st->time_base.num,
1140 st->time_base.num * (int64_t)ref_st->time_base.den);
1144 void ff_reduce_index(AVFormatContext *s, int stream_index)
1146 AVStream *st= s->streams[stream_index];
1147 unsigned int max_entries= s->max_index_size / sizeof(AVIndexEntry);
1149 if((unsigned)st->nb_index_entries >= max_entries){
1151 for(i=0; 2*i<st->nb_index_entries; i++)
1152 st->index_entries[i]= st->index_entries[2*i];
1153 st->nb_index_entries= i;
1157 int av_add_index_entry(AVStream *st,
1158 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1160 AVIndexEntry *entries, *ie;
1163 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1166 entries = av_fast_realloc(st->index_entries,
1167 &st->index_entries_allocated_size,
1168 (st->nb_index_entries + 1) *
1169 sizeof(AVIndexEntry));
1173 st->index_entries= entries;
1175 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1178 index= st->nb_index_entries++;
1179 ie= &entries[index];
1180 assert(index==0 || ie[-1].timestamp < timestamp);
1182 ie= &entries[index];
1183 if(ie->timestamp != timestamp){
1184 if(ie->timestamp <= timestamp)
1186 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1187 st->nb_index_entries++;
1188 }else if(ie->pos == pos && distance < ie->min_distance) //do not reduce the distance
1189 distance= ie->min_distance;
1193 ie->timestamp = timestamp;
1194 ie->min_distance= distance;
1201 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1204 AVIndexEntry *entries= st->index_entries;
1205 int nb_entries= st->nb_index_entries;
1214 timestamp = entries[m].timestamp;
1215 if(timestamp >= wanted_timestamp)
1217 if(timestamp <= wanted_timestamp)
1220 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1222 if(!(flags & AVSEEK_FLAG_ANY)){
1223 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1224 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1235 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1236 AVInputFormat *avif= s->iformat;
1237 int64_t pos_min, pos_max, pos, pos_limit;
1238 int64_t ts_min, ts_max, ts;
1242 if (stream_index < 0)
1246 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1250 ts_min= AV_NOPTS_VALUE;
1251 pos_limit= -1; //gcc falsely says it may be uninitialized
1253 st= s->streams[stream_index];
1254 if(st->index_entries){
1257 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()
1258 index= FFMAX(index, 0);
1259 e= &st->index_entries[index];
1261 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1263 ts_min= e->timestamp;
1265 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1272 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1273 assert(index < st->nb_index_entries);
1275 e= &st->index_entries[index];
1276 assert(e->timestamp >= target_ts);
1278 ts_max= e->timestamp;
1279 pos_limit= pos_max - e->min_distance;
1281 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1282 pos_max,pos_limit, ts_max);
1287 pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);
1292 url_fseek(s->pb, pos, SEEK_SET);
1294 av_update_cur_dts(s, st, ts);
1299 int64_t av_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts, int64_t pos_min, int64_t pos_max, int64_t pos_limit, int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret, int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t )){
1301 int64_t start_pos, filesize;
1305 av_log(s, AV_LOG_DEBUG, "gen_seek: %d %"PRId64"\n", stream_index, target_ts);
1308 if(ts_min == AV_NOPTS_VALUE){
1309 pos_min = s->data_offset;
1310 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1311 if (ts_min == AV_NOPTS_VALUE)
1315 if(ts_max == AV_NOPTS_VALUE){
1317 filesize = url_fsize(s->pb);
1318 pos_max = filesize - 1;
1321 ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1323 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1324 if (ts_max == AV_NOPTS_VALUE)
1328 int64_t tmp_pos= pos_max + 1;
1329 int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1330 if(tmp_ts == AV_NOPTS_VALUE)
1334 if(tmp_pos >= filesize)
1340 if(ts_min > ts_max){
1342 }else if(ts_min == ts_max){
1347 while (pos_min < pos_limit) {
1349 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1353 assert(pos_limit <= pos_max);
1356 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1357 // interpolate position (better than dichotomy)
1358 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1359 + pos_min - approximate_keyframe_distance;
1360 }else if(no_change==1){
1361 // bisection, if interpolation failed to change min or max pos last time
1362 pos = (pos_min + pos_limit)>>1;
1364 /* linear search if bisection failed, can only happen if there
1365 are very few or no keyframes between min/max */
1370 else if(pos > pos_limit)
1374 ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1380 av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1382 if(ts == AV_NOPTS_VALUE){
1383 av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");
1386 assert(ts != AV_NOPTS_VALUE);
1387 if (target_ts <= ts) {
1388 pos_limit = start_pos - 1;
1392 if (target_ts >= ts) {
1398 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1399 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1402 ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1404 ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1405 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1406 pos, ts_min, target_ts, ts_max);
1412 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1413 int64_t pos_min, pos_max;
1417 if (stream_index < 0)
1420 st= s->streams[stream_index];
1423 pos_min = s->data_offset;
1424 pos_max = url_fsize(s->pb) - 1;
1426 if (pos < pos_min) pos= pos_min;
1427 else if(pos > pos_max) pos= pos_max;
1429 url_fseek(s->pb, pos, SEEK_SET);
1432 av_update_cur_dts(s, st, ts);
1437 static int av_seek_frame_generic(AVFormatContext *s,
1438 int stream_index, int64_t timestamp, int flags)
1444 st = s->streams[stream_index];
1446 index = av_index_search_timestamp(st, timestamp, flags);
1448 if(index < 0 || index==st->nb_index_entries-1){
1452 if(st->nb_index_entries){
1453 assert(st->index_entries);
1454 ie= &st->index_entries[st->nb_index_entries-1];
1455 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1457 av_update_cur_dts(s, st, ie->timestamp);
1459 if ((ret = url_fseek(s->pb, 0, SEEK_SET)) < 0)
1463 int ret = av_read_frame(s, &pkt);
1466 av_free_packet(&pkt);
1467 if(stream_index == pkt.stream_index){
1468 if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)
1472 index = av_index_search_timestamp(st, timestamp, flags);
1477 av_read_frame_flush(s);
1478 if (s->iformat->read_seek){
1479 if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)
1482 ie = &st->index_entries[index];
1483 if ((ret = url_fseek(s->pb, ie->pos, SEEK_SET)) < 0)
1485 av_update_cur_dts(s, st, ie->timestamp);
1490 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1495 av_read_frame_flush(s);
1497 if(flags & AVSEEK_FLAG_BYTE)
1498 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1500 if(stream_index < 0){
1501 stream_index= av_find_default_stream_index(s);
1502 if(stream_index < 0)
1505 st= s->streams[stream_index];
1506 /* timestamp for default must be expressed in AV_TIME_BASE units */
1507 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1509 st= s->streams[stream_index];
1511 /* first, we try the format specific seek */
1512 if (s->iformat->read_seek)
1513 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1520 if(s->iformat->read_timestamp)
1521 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1523 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1526 /*******************************************************/
1529 * Returns TRUE if the stream has accurate duration in any stream.
1531 * @return TRUE if the stream has accurate duration for at least one component.
1533 static int av_has_duration(AVFormatContext *ic)
1538 for(i = 0;i < ic->nb_streams; i++) {
1539 st = ic->streams[i];
1540 if (st->duration != AV_NOPTS_VALUE)
1547 * Estimate the stream timings from the one of each components.
1549 * Also computes the global bitrate if possible.
1551 static void av_update_stream_timings(AVFormatContext *ic)
1553 int64_t start_time, start_time1, end_time, end_time1;
1554 int64_t duration, duration1;
1558 start_time = INT64_MAX;
1559 end_time = INT64_MIN;
1560 duration = INT64_MIN;
1561 for(i = 0;i < ic->nb_streams; i++) {
1562 st = ic->streams[i];
1563 if (st->start_time != AV_NOPTS_VALUE && st->time_base.den) {
1564 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1565 if (start_time1 < start_time)
1566 start_time = start_time1;
1567 if (st->duration != AV_NOPTS_VALUE) {
1568 end_time1 = start_time1
1569 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1570 if (end_time1 > end_time)
1571 end_time = end_time1;
1574 if (st->duration != AV_NOPTS_VALUE) {
1575 duration1 = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1576 if (duration1 > duration)
1577 duration = duration1;
1580 if (start_time != INT64_MAX) {
1581 ic->start_time = start_time;
1582 if (end_time != INT64_MIN) {
1583 if (end_time - start_time > duration)
1584 duration = end_time - start_time;
1587 if (duration != INT64_MIN) {
1588 ic->duration = duration;
1589 if (ic->file_size > 0) {
1590 /* compute the bitrate */
1591 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1592 (double)ic->duration;
1597 static void fill_all_stream_timings(AVFormatContext *ic)
1602 av_update_stream_timings(ic);
1603 for(i = 0;i < ic->nb_streams; i++) {
1604 st = ic->streams[i];
1605 if (st->start_time == AV_NOPTS_VALUE) {
1606 if(ic->start_time != AV_NOPTS_VALUE)
1607 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1608 if(ic->duration != AV_NOPTS_VALUE)
1609 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1614 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1616 int64_t filesize, duration;
1620 /* if bit_rate is already set, we believe it */
1621 if (ic->bit_rate == 0) {
1623 for(i=0;i<ic->nb_streams;i++) {
1624 st = ic->streams[i];
1625 bit_rate += st->codec->bit_rate;
1627 ic->bit_rate = bit_rate;
1630 /* if duration is already set, we believe it */
1631 if (ic->duration == AV_NOPTS_VALUE &&
1632 ic->bit_rate != 0 &&
1633 ic->file_size != 0) {
1634 filesize = ic->file_size;
1636 for(i = 0; i < ic->nb_streams; i++) {
1637 st = ic->streams[i];
1638 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1639 if (st->duration == AV_NOPTS_VALUE)
1640 st->duration = duration;
1646 #define DURATION_MAX_READ_SIZE 250000
1648 /* only usable for MPEG-PS streams */
1649 static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)
1651 AVPacket pkt1, *pkt = &pkt1;
1653 int read_size, i, ret;
1655 int64_t filesize, offset, duration;
1657 /* free previous packet */
1658 if (ic->cur_st && ic->cur_st->parser)
1659 av_free_packet(&ic->cur_pkt);
1662 /* flush packet queue */
1663 flush_packet_queue(ic);
1665 for(i=0;i<ic->nb_streams;i++) {
1666 st = ic->streams[i];
1668 av_parser_close(st->parser);
1673 /* we read the first packets to get the first PTS (not fully
1674 accurate, but it is enough now) */
1675 url_fseek(ic->pb, 0, SEEK_SET);
1678 if (read_size >= DURATION_MAX_READ_SIZE)
1680 /* if all info is available, we can stop */
1681 for(i = 0;i < ic->nb_streams; i++) {
1682 st = ic->streams[i];
1683 if (st->start_time == AV_NOPTS_VALUE)
1686 if (i == ic->nb_streams)
1689 ret = av_read_packet(ic, pkt);
1692 read_size += pkt->size;
1693 st = ic->streams[pkt->stream_index];
1694 if (pkt->pts != AV_NOPTS_VALUE) {
1695 if (st->start_time == AV_NOPTS_VALUE)
1696 st->start_time = pkt->pts;
1698 av_free_packet(pkt);
1701 /* estimate the end time (duration) */
1702 /* XXX: may need to support wrapping */
1703 filesize = ic->file_size;
1704 offset = filesize - DURATION_MAX_READ_SIZE;
1708 url_fseek(ic->pb, offset, SEEK_SET);
1711 if (read_size >= DURATION_MAX_READ_SIZE)
1714 ret = av_read_packet(ic, pkt);
1717 read_size += pkt->size;
1718 st = ic->streams[pkt->stream_index];
1719 if (pkt->pts != AV_NOPTS_VALUE &&
1720 st->start_time != AV_NOPTS_VALUE) {
1721 end_time = pkt->pts;
1722 duration = end_time - st->start_time;
1724 if (st->duration == AV_NOPTS_VALUE ||
1725 st->duration < duration)
1726 st->duration = duration;
1729 av_free_packet(pkt);
1732 fill_all_stream_timings(ic);
1734 url_fseek(ic->pb, old_offset, SEEK_SET);
1735 for(i=0; i<ic->nb_streams; i++){
1737 st->cur_dts= st->first_dts;
1738 st->last_IP_pts = AV_NOPTS_VALUE;
1742 static void av_estimate_timings(AVFormatContext *ic, offset_t old_offset)
1746 /* get the file size, if possible */
1747 if (ic->iformat->flags & AVFMT_NOFILE) {
1750 file_size = url_fsize(ic->pb);
1754 ic->file_size = file_size;
1756 if ((!strcmp(ic->iformat->name, "mpeg") ||
1757 !strcmp(ic->iformat->name, "mpegts")) &&
1758 file_size && !url_is_streamed(ic->pb)) {
1759 /* get accurate estimate from the PTSes */
1760 av_estimate_timings_from_pts(ic, old_offset);
1761 } else if (av_has_duration(ic)) {
1762 /* at least one component has timings - we use them for all
1764 fill_all_stream_timings(ic);
1766 /* less precise: use bitrate info */
1767 av_estimate_timings_from_bit_rate(ic);
1769 av_update_stream_timings(ic);
1775 for(i = 0;i < ic->nb_streams; i++) {
1776 st = ic->streams[i];
1777 printf("%d: start_time: %0.3f duration: %0.3f\n",
1778 i, (double)st->start_time / AV_TIME_BASE,
1779 (double)st->duration / AV_TIME_BASE);
1781 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1782 (double)ic->start_time / AV_TIME_BASE,
1783 (double)ic->duration / AV_TIME_BASE,
1784 ic->bit_rate / 1000);
1789 static int has_codec_parameters(AVCodecContext *enc)
1792 switch(enc->codec_type) {
1793 case CODEC_TYPE_AUDIO:
1794 val = enc->sample_rate && enc->channels;
1795 if(!enc->frame_size &&
1796 (enc->codec_id == CODEC_ID_VORBIS ||
1797 enc->codec_id == CODEC_ID_AAC))
1800 case CODEC_TYPE_VIDEO:
1801 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1807 return enc->codec_id != CODEC_ID_NONE && val != 0;
1810 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1814 int got_picture, data_size, ret=0;
1817 if(!st->codec->codec){
1818 codec = avcodec_find_decoder(st->codec->codec_id);
1821 ret = avcodec_open(st->codec, codec);
1826 if(!has_codec_parameters(st->codec)){
1827 switch(st->codec->codec_type) {
1828 case CODEC_TYPE_VIDEO:
1829 ret = avcodec_decode_video(st->codec, &picture,
1830 &got_picture, data, size);
1832 case CODEC_TYPE_AUDIO:
1833 data_size = FFMAX(size, AVCODEC_MAX_AUDIO_FRAME_SIZE);
1834 samples = av_malloc(data_size);
1837 ret = avcodec_decode_audio2(st->codec, samples,
1838 &data_size, data, size);
1849 unsigned int codec_get_tag(const AVCodecTag *tags, int id)
1851 while (tags->id != CODEC_ID_NONE) {
1859 enum CodecID codec_get_id(const AVCodecTag *tags, unsigned int tag)
1862 for(i=0; tags[i].id != CODEC_ID_NONE;i++) {
1863 if(tag == tags[i].tag)
1866 for(i=0; tags[i].id != CODEC_ID_NONE; i++) {
1867 if( toupper((tag >> 0)&0xFF) == toupper((tags[i].tag >> 0)&0xFF)
1868 && toupper((tag >> 8)&0xFF) == toupper((tags[i].tag >> 8)&0xFF)
1869 && toupper((tag >>16)&0xFF) == toupper((tags[i].tag >>16)&0xFF)
1870 && toupper((tag >>24)&0xFF) == toupper((tags[i].tag >>24)&0xFF))
1873 return CODEC_ID_NONE;
1876 unsigned int av_codec_get_tag(const AVCodecTag *tags[4], enum CodecID id)
1879 for(i=0; tags && tags[i]; i++){
1880 int tag= codec_get_tag(tags[i], id);
1886 enum CodecID av_codec_get_id(const AVCodecTag *tags[4], unsigned int tag)
1889 for(i=0; tags && tags[i]; i++){
1890 enum CodecID id= codec_get_id(tags[i], tag);
1891 if(id!=CODEC_ID_NONE) return id;
1893 return CODEC_ID_NONE;
1896 static void compute_chapters_end(AVFormatContext *s)
1900 for (i=0; i+1<s->nb_chapters; i++)
1901 if (s->chapters[i]->end == AV_NOPTS_VALUE) {
1902 assert(s->chapters[i]->start <= s->chapters[i+1]->start);
1903 assert(!av_cmp_q(s->chapters[i]->time_base, s->chapters[i+1]->time_base));
1904 s->chapters[i]->end = s->chapters[i+1]->start;
1907 if (s->nb_chapters && s->chapters[i]->end == AV_NOPTS_VALUE) {
1908 assert(s->start_time != AV_NOPTS_VALUE);
1909 assert(s->duration > 0);
1910 s->chapters[i]->end = av_rescale_q(s->start_time + s->duration,
1912 s->chapters[i]->time_base);
1916 /* absolute maximum size we read until we abort */
1917 #define MAX_READ_SIZE 5000000
1919 #define MAX_STD_TIMEBASES (60*12+5)
1920 static int get_std_framerate(int i){
1921 if(i<60*12) return i*1001;
1922 else return ((int[]){24,30,60,12,15})[i-60*12]*1000*12;
1926 * Is the time base unreliable.
1927 * This is a heuristic to balance between quick acceptance of the values in
1928 * the headers vs. some extra checks.
1929 * Old DivX and Xvid often have nonsense timebases like 1fps or 2fps.
1930 * MPEG-2 commonly misuses field repeat flags to store different framerates.
1931 * And there are "variable" fps files this needs to detect as well.
1933 static int tb_unreliable(AVCodecContext *c){
1934 if( c->time_base.den >= 101L*c->time_base.num
1935 || c->time_base.den < 5L*c->time_base.num
1936 /* || c->codec_tag == ff_get_fourcc("DIVX")
1937 || c->codec_tag == ff_get_fourcc("XVID")*/
1938 || c->codec_id == CODEC_ID_MPEG2VIDEO)
1943 int av_find_stream_info(AVFormatContext *ic)
1945 int i, count, ret, read_size, j;
1947 AVPacket pkt1, *pkt;
1948 int64_t last_dts[MAX_STREAMS];
1949 int duration_count[MAX_STREAMS]={0};
1950 double (*duration_error)[MAX_STD_TIMEBASES];
1951 offset_t old_offset = url_ftell(ic->pb);
1952 int64_t codec_info_duration[MAX_STREAMS]={0};
1953 int codec_info_nb_frames[MAX_STREAMS]={0};
1955 duration_error = av_mallocz(MAX_STREAMS * sizeof(*duration_error));
1956 if (!duration_error) return AVERROR(ENOMEM);
1958 for(i=0;i<ic->nb_streams;i++) {
1959 st = ic->streams[i];
1960 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1961 /* if(!st->time_base.num)
1963 if(!st->codec->time_base.num)
1964 st->codec->time_base= st->time_base;
1966 //only for the split stuff
1968 st->parser = av_parser_init(st->codec->codec_id);
1969 if(st->need_parsing == AVSTREAM_PARSE_HEADERS && st->parser){
1970 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1975 for(i=0;i<MAX_STREAMS;i++){
1976 last_dts[i]= AV_NOPTS_VALUE;
1982 /* check if one codec still needs to be handled */
1983 for(i=0;i<ic->nb_streams;i++) {
1984 st = ic->streams[i];
1985 if (!has_codec_parameters(st->codec))
1987 /* variable fps and no guess at the real fps */
1988 if( tb_unreliable(st->codec)
1989 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1991 if(st->parser && st->parser->parser->split && !st->codec->extradata)
1993 if(st->first_dts == AV_NOPTS_VALUE)
1996 if (i == ic->nb_streams) {
1997 /* NOTE: if the format has no header, then we need to read
1998 some packets to get most of the streams, so we cannot
2000 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
2001 /* if we found the info for all the codecs, we can stop */
2006 /* we did not get all the codec info, but we read too much data */
2007 if (read_size >= MAX_READ_SIZE) {
2012 /* NOTE: a new stream can be added there if no header in file
2013 (AVFMTCTX_NOHEADER) */
2014 ret = av_read_frame_internal(ic, &pkt1);
2017 ret = -1; /* we could not have all the codec parameters before EOF */
2018 for(i=0;i<ic->nb_streams;i++) {
2019 st = ic->streams[i];
2020 if (!has_codec_parameters(st->codec)){
2022 avcodec_string(buf, sizeof(buf), st->codec, 0);
2023 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
2031 pkt= add_to_pktbuf(&ic->packet_buffer, &pkt1, &ic->packet_buffer_end);
2032 if(av_dup_packet(pkt) < 0) {
2033 av_free(duration_error);
2034 return AVERROR(ENOMEM);
2037 read_size += pkt->size;
2039 st = ic->streams[pkt->stream_index];
2040 if(codec_info_nb_frames[st->index]>1)
2041 codec_info_duration[st->index] += pkt->duration;
2042 if (pkt->duration != 0)
2043 codec_info_nb_frames[st->index]++;
2046 int index= pkt->stream_index;
2047 int64_t last= last_dts[index];
2048 int64_t duration= pkt->dts - last;
2050 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2051 double dur= duration * av_q2d(st->time_base);
2053 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2054 // av_log(NULL, AV_LOG_ERROR, "%f\n", dur);
2055 if(duration_count[index] < 2)
2056 memset(duration_error[index], 0, sizeof(*duration_error));
2057 for(i=1; i<MAX_STD_TIMEBASES; i++){
2058 int framerate= get_std_framerate(i);
2059 int ticks= lrintf(dur*framerate/(1001*12));
2060 double error= dur - ticks*1001*12/(double)framerate;
2061 duration_error[index][i] += error*error;
2063 duration_count[index]++;
2065 if(last == AV_NOPTS_VALUE || duration_count[index]<=1)
2066 last_dts[pkt->stream_index]= pkt->dts;
2068 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2069 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2071 st->codec->extradata_size= i;
2072 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2073 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2074 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2078 /* if still no information, we try to open the codec and to
2079 decompress the frame. We try to avoid that in most cases as
2080 it takes longer and uses more memory. For MPEG-4, we need to
2081 decompress for QuickTime. */
2082 if (!has_codec_parameters(st->codec) /*&&
2083 (st->codec->codec_id == CODEC_ID_FLV1 ||
2084 st->codec->codec_id == CODEC_ID_H264 ||
2085 st->codec->codec_id == CODEC_ID_H263 ||
2086 st->codec->codec_id == CODEC_ID_H261 ||
2087 st->codec->codec_id == CODEC_ID_VORBIS ||
2088 st->codec->codec_id == CODEC_ID_MJPEG ||
2089 st->codec->codec_id == CODEC_ID_PNG ||
2090 st->codec->codec_id == CODEC_ID_PAM ||
2091 st->codec->codec_id == CODEC_ID_PGM ||
2092 st->codec->codec_id == CODEC_ID_PGMYUV ||
2093 st->codec->codec_id == CODEC_ID_PBM ||
2094 st->codec->codec_id == CODEC_ID_PPM ||
2095 st->codec->codec_id == CODEC_ID_SHORTEN ||
2096 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2097 try_decode_frame(st, pkt->data, pkt->size);
2099 if (st->time_base.den > 0 && av_rescale_q(codec_info_duration[st->index], st->time_base, AV_TIME_BASE_Q) >= ic->max_analyze_duration) {
2105 // close codecs which were opened in try_decode_frame()
2106 for(i=0;i<ic->nb_streams;i++) {
2107 st = ic->streams[i];
2108 if(st->codec->codec)
2109 avcodec_close(st->codec);
2111 for(i=0;i<ic->nb_streams;i++) {
2112 st = ic->streams[i];
2113 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2114 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2115 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2117 if(duration_count[i]
2118 && tb_unreliable(st->codec) /*&&
2119 //FIXME we should not special-case MPEG-2, but this needs testing with non-MPEG-2 ...
2120 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den*/){
2121 double best_error= 2*av_q2d(st->time_base);
2122 best_error= best_error*best_error*duration_count[i]*1000*12*30;
2124 for(j=1; j<MAX_STD_TIMEBASES; j++){
2125 double error= duration_error[i][j] * get_std_framerate(j);
2126 // if(st->codec->codec_type == CODEC_TYPE_VIDEO)
2127 // av_log(NULL, AV_LOG_ERROR, "%f %f\n", get_std_framerate(j) / 12.0/1001, error);
2128 if(error < best_error){
2130 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, get_std_framerate(j), 12*1001, INT_MAX);
2135 if (!st->r_frame_rate.num){
2136 if( st->codec->time_base.den * (int64_t)st->time_base.num
2137 <= st->codec->time_base.num * (int64_t)st->time_base.den){
2138 st->r_frame_rate.num = st->codec->time_base.den;
2139 st->r_frame_rate.den = st->codec->time_base.num;
2141 st->r_frame_rate.num = st->time_base.den;
2142 st->r_frame_rate.den = st->time_base.num;
2145 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO) {
2146 if(!st->codec->bits_per_sample)
2147 st->codec->bits_per_sample= av_get_bits_per_sample(st->codec->codec_id);
2151 av_estimate_timings(ic, old_offset);
2153 compute_chapters_end(ic);
2156 /* correct DTS for B-frame streams with no timestamps */
2157 for(i=0;i<ic->nb_streams;i++) {
2158 st = ic->streams[i];
2159 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2161 ppktl = &ic->packet_buffer;
2163 if(ppkt1->stream_index != i)
2165 if(ppkt1->pkt->dts < 0)
2167 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2169 ppkt1->pkt->dts -= delta;
2174 st->cur_dts -= delta;
2180 av_free(duration_error);
2185 /*******************************************************/
2187 int av_read_play(AVFormatContext *s)
2189 if (s->iformat->read_play)
2190 return s->iformat->read_play(s);
2192 return av_url_read_fpause(s->pb, 0);
2193 return AVERROR(ENOSYS);
2196 int av_read_pause(AVFormatContext *s)
2198 if (s->iformat->read_pause)
2199 return s->iformat->read_pause(s);
2201 return av_url_read_fpause(s->pb, 1);
2202 return AVERROR(ENOSYS);
2205 void av_close_input_stream(AVFormatContext *s)
2210 /* free previous packet */
2211 if (s->cur_st && s->cur_st->parser)
2212 av_free_packet(&s->cur_pkt);
2214 if (s->iformat->read_close)
2215 s->iformat->read_close(s);
2216 for(i=0;i<s->nb_streams;i++) {
2217 /* free all data in a stream component */
2220 av_parser_close(st->parser);
2222 av_free(st->index_entries);
2223 av_free(st->codec->extradata);
2225 av_free(st->filename);
2226 av_free(st->priv_data);
2229 for(i=s->nb_programs-1; i>=0; i--) {
2230 av_freep(&s->programs[i]->provider_name);
2231 av_freep(&s->programs[i]->name);
2232 av_freep(&s->programs[i]->stream_index);
2233 av_freep(&s->programs[i]);
2235 av_freep(&s->programs);
2236 flush_packet_queue(s);
2237 av_freep(&s->priv_data);
2238 while(s->nb_chapters--) {
2239 av_free(s->chapters[s->nb_chapters]->title);
2240 av_free(s->chapters[s->nb_chapters]);
2242 av_freep(&s->chapters);
2246 void av_close_input_file(AVFormatContext *s)
2248 ByteIOContext *pb = s->iformat->flags & AVFMT_NOFILE ? NULL : s->pb;
2249 av_close_input_stream(s);
2254 AVStream *av_new_stream(AVFormatContext *s, int id)
2259 if (s->nb_streams >= MAX_STREAMS)
2262 st = av_mallocz(sizeof(AVStream));
2266 st->codec= avcodec_alloc_context();
2268 /* no default bitrate if decoding */
2269 st->codec->bit_rate = 0;
2271 st->index = s->nb_streams;
2273 st->start_time = AV_NOPTS_VALUE;
2274 st->duration = AV_NOPTS_VALUE;
2275 /* we set the current DTS to 0 so that formats without any timestamps
2276 but durations get some timestamps, formats with some unknown
2277 timestamps have their first few packets buffered and the
2278 timestamps corrected before they are returned to the user */
2280 st->first_dts = AV_NOPTS_VALUE;
2282 /* default pts setting is MPEG-like */
2283 av_set_pts_info(st, 33, 1, 90000);
2284 st->last_IP_pts = AV_NOPTS_VALUE;
2285 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2286 st->pts_buffer[i]= AV_NOPTS_VALUE;
2288 s->streams[s->nb_streams++] = st;
2292 AVProgram *av_new_program(AVFormatContext *ac, int id)
2294 AVProgram *program=NULL;
2298 av_log(ac, AV_LOG_DEBUG, "new_program: id=0x%04x\n", id);
2301 for(i=0; i<ac->nb_programs; i++)
2302 if(ac->programs[i]->id == id)
2303 program = ac->programs[i];
2306 program = av_mallocz(sizeof(AVProgram));
2309 dynarray_add(&ac->programs, &ac->nb_programs, program);
2310 program->discard = AVDISCARD_NONE;
2317 void av_set_program_name(AVProgram *program, char *provider_name, char *name)
2319 assert(!provider_name == !name);
2321 av_free(program->provider_name);
2322 av_free(program-> name);
2323 program->provider_name = av_strdup(provider_name);
2324 program-> name = av_strdup( name);
2328 AVChapter *ff_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
2330 AVChapter *chapter = NULL;
2333 for(i=0; i<s->nb_chapters; i++)
2334 if(s->chapters[i]->id == id)
2335 chapter = s->chapters[i];
2338 chapter= av_mallocz(sizeof(AVChapter));
2341 dynarray_add(&s->chapters, &s->nb_chapters, chapter);
2343 av_free(chapter->title);
2344 chapter->title = av_strdup(title);
2346 chapter->time_base= time_base;
2347 chapter->start = start;
2353 /************************************************************/
2354 /* output media file */
2356 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2360 if (s->oformat->priv_data_size > 0) {
2361 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2363 return AVERROR(ENOMEM);
2365 s->priv_data = NULL;
2367 if (s->oformat->set_parameters) {
2368 ret = s->oformat->set_parameters(s, ap);
2375 int av_write_header(AVFormatContext *s)
2380 // some sanity checks
2381 for(i=0;i<s->nb_streams;i++) {
2384 switch (st->codec->codec_type) {
2385 case CODEC_TYPE_AUDIO:
2386 if(st->codec->sample_rate<=0){
2387 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2391 case CODEC_TYPE_VIDEO:
2392 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2393 av_log(s, AV_LOG_ERROR, "time base not set\n");
2396 if(st->codec->width<=0 || st->codec->height<=0){
2397 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2403 if(s->oformat->codec_tag){
2404 if(st->codec->codec_tag){
2406 //check that tag + id is in the table
2407 //if neither is in the table -> OK
2408 //if tag is in the table with another id -> FAIL
2409 //if id is in the table with another tag -> FAIL unless strict < ?
2411 st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);
2415 if (!s->priv_data && s->oformat->priv_data_size > 0) {
2416 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2418 return AVERROR(ENOMEM);
2421 if(s->oformat->write_header){
2422 ret = s->oformat->write_header(s);
2427 /* init PTS generation */
2428 for(i=0;i<s->nb_streams;i++) {
2429 int64_t den = AV_NOPTS_VALUE;
2432 switch (st->codec->codec_type) {
2433 case CODEC_TYPE_AUDIO:
2434 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2436 case CODEC_TYPE_VIDEO:
2437 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2442 if (den != AV_NOPTS_VALUE) {
2444 return AVERROR_INVALIDDATA;
2445 av_frac_init(&st->pts, 0, 0, den);
2451 //FIXME merge with compute_pkt_fields
2452 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2453 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2454 int num, den, frame_size, i;
2456 // av_log(st->codec, AV_LOG_DEBUG, "av_write_frame: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2458 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2461 /* duration field */
2462 if (pkt->duration == 0) {
2463 compute_frame_duration(&num, &den, st, NULL, pkt);
2465 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2469 if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)
2472 //XXX/FIXME this is a temporary hack until all encoders output pts
2473 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2475 // pkt->pts= st->cur_dts;
2476 pkt->pts= st->pts.val;
2479 //calculate dts from pts
2480 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2481 st->pts_buffer[0]= pkt->pts;
2482 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2483 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2484 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2485 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2487 pkt->dts= st->pts_buffer[0];
2490 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2491 av_log(st->codec, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2494 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2495 av_log(st->codec, AV_LOG_ERROR, "error, pts < dts\n");
2499 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);
2500 st->cur_dts= pkt->dts;
2501 st->pts.val= pkt->dts;
2504 switch (st->codec->codec_type) {
2505 case CODEC_TYPE_AUDIO:
2506 frame_size = get_audio_frame_size(st->codec, pkt->size);
2508 /* HACK/FIXME, we skip the initial 0 size packets as they are most
2509 likely equal to the encoder delay, but it would be better if we
2510 had the real timestamps from the encoder */
2511 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2512 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2515 case CODEC_TYPE_VIDEO:
2516 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2524 static void truncate_ts(AVStream *st, AVPacket *pkt){
2525 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2528 // pkt->dts= 0; //this happens for low_delay=0 and B-frames, FIXME, needs further investigation about what we should do here
2530 if (pkt->pts != AV_NOPTS_VALUE)
2531 pkt->pts &= pts_mask;
2532 if (pkt->dts != AV_NOPTS_VALUE)
2533 pkt->dts &= pts_mask;
2536 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2538 int ret = compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2540 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2543 truncate_ts(s->streams[pkt->stream_index], pkt);
2545 ret= s->oformat->write_packet(s, pkt);
2547 ret= url_ferror(s->pb);
2551 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2552 AVPacketList *pktl, **next_point, *this_pktl;
2554 int streams[MAX_STREAMS];
2557 AVStream *st= s->streams[ pkt->stream_index];
2559 // assert(pkt->destruct != av_destruct_packet); //FIXME
2561 this_pktl = av_mallocz(sizeof(AVPacketList));
2562 this_pktl->pkt= *pkt;
2563 if(pkt->destruct == av_destruct_packet)
2564 pkt->destruct= NULL; // not shared -> must keep original from being freed
2566 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2568 next_point = &s->packet_buffer;
2570 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2571 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2572 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2573 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2575 next_point= &(*next_point)->next;
2577 this_pktl->next= *next_point;
2578 *next_point= this_pktl;
2581 memset(streams, 0, sizeof(streams));
2582 pktl= s->packet_buffer;
2584 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%"PRId64"\n", pktl->pkt.stream_index, pktl->pkt.dts);
2585 if(streams[ pktl->pkt.stream_index ] == 0)
2587 streams[ pktl->pkt.stream_index ]++;
2591 if(stream_count && (s->nb_streams == stream_count || flush)){
2592 pktl= s->packet_buffer;
2595 s->packet_buffer= pktl->next;
2599 av_init_packet(out);
2605 * Interleaves an AVPacket correctly so it can be muxed.
2606 * @param out the interleaved packet will be output here
2607 * @param in the input packet
2608 * @param flush 1 if no further packets are available as input and all
2609 * remaining packets should be output
2610 * @return 1 if a packet was output, 0 if no packet could be output,
2611 * < 0 if an error occurred
2613 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2614 if(s->oformat->interleave_packet)
2615 return s->oformat->interleave_packet(s, out, in, flush);
2617 return av_interleave_packet_per_dts(s, out, in, flush);
2620 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2621 AVStream *st= s->streams[ pkt->stream_index];
2623 //FIXME/XXX/HACK drop zero sized packets
2624 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2627 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %"PRId64" %"PRId64"\n", pkt->size, pkt->dts, pkt->pts);
2628 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2631 if(pkt->dts == AV_NOPTS_VALUE)
2636 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2637 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2640 truncate_ts(s->streams[opkt.stream_index], &opkt);
2641 ret= s->oformat->write_packet(s, &opkt);
2643 av_free_packet(&opkt);
2648 if(url_ferror(s->pb))
2649 return url_ferror(s->pb);
2653 int av_write_trailer(AVFormatContext *s)
2659 ret= av_interleave_packet(s, &pkt, NULL, 1);
2660 if(ret<0) //FIXME cleanup needed for ret<0 ?
2665 truncate_ts(s->streams[pkt.stream_index], &pkt);
2666 ret= s->oformat->write_packet(s, &pkt);
2668 av_free_packet(&pkt);
2672 if(url_ferror(s->pb))
2676 if(s->oformat->write_trailer)
2677 ret = s->oformat->write_trailer(s);
2680 ret=url_ferror(s->pb);
2681 for(i=0;i<s->nb_streams;i++)
2682 av_freep(&s->streams[i]->priv_data);
2683 av_freep(&s->priv_data);
2687 void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
2690 AVProgram *program=NULL;
2693 for(i=0; i<ac->nb_programs; i++){
2694 if(ac->programs[i]->id != progid)
2696 program = ac->programs[i];
2697 for(j=0; j<program->nb_stream_indexes; j++)
2698 if(program->stream_index[j] == idx)
2701 tmp = av_realloc(program->stream_index, sizeof(unsigned int)*(program->nb_stream_indexes+1));
2704 program->stream_index = tmp;
2705 program->stream_index[program->nb_stream_indexes++] = idx;
2710 /* "user interface" functions */
2711 static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)
2714 int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
2715 AVStream *st = ic->streams[i];
2716 int g = ff_gcd(st->time_base.num, st->time_base.den);
2717 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2718 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2719 /* the pid is an important information, so we display it */
2720 /* XXX: add a generic system */
2721 if (flags & AVFMT_SHOW_IDS)
2722 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2723 if (strlen(st->language) > 0)
2724 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2725 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2726 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2727 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2728 if(st->r_frame_rate.den && st->r_frame_rate.num)
2729 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(r)", av_q2d(st->r_frame_rate));
2730 /* else if(st->time_base.den && st->time_base.num)
2731 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(m)", 1/av_q2d(st->time_base));*/
2733 av_log(NULL, AV_LOG_INFO, ", %5.2f tb(c)", 1/av_q2d(st->codec->time_base));
2735 av_log(NULL, AV_LOG_INFO, "\n");
2738 void dump_format(AVFormatContext *ic,
2745 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2746 is_output ? "Output" : "Input",
2748 is_output ? ic->oformat->name : ic->iformat->name,
2749 is_output ? "to" : "from", url);
2751 av_log(NULL, AV_LOG_INFO, " Duration: ");
2752 if (ic->duration != AV_NOPTS_VALUE) {
2753 int hours, mins, secs, us;
2754 secs = ic->duration / AV_TIME_BASE;
2755 us = ic->duration % AV_TIME_BASE;
2760 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%02d", hours, mins, secs,
2761 (100 * us) / AV_TIME_BASE);
2763 av_log(NULL, AV_LOG_INFO, "N/A");
2765 if (ic->start_time != AV_NOPTS_VALUE) {
2767 av_log(NULL, AV_LOG_INFO, ", start: ");
2768 secs = ic->start_time / AV_TIME_BASE;
2769 us = ic->start_time % AV_TIME_BASE;
2770 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2771 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2773 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2775 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2777 av_log(NULL, AV_LOG_INFO, "N/A");
2779 av_log(NULL, AV_LOG_INFO, "\n");
2781 if(ic->nb_programs) {
2783 for(j=0; j<ic->nb_programs; j++) {
2784 av_log(NULL, AV_LOG_INFO, " Program %d %s\n", ic->programs[j]->id,
2785 ic->programs[j]->name ? ic->programs[j]->name : "");
2786 for(k=0; k<ic->programs[j]->nb_stream_indexes; k++)
2787 dump_stream_format(ic, ic->programs[j]->stream_index[k], index, is_output);
2790 for(i=0;i<ic->nb_streams;i++)
2791 dump_stream_format(ic, i, index, is_output);
2794 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2796 return av_parse_video_frame_size(width_ptr, height_ptr, str);
2799 int parse_frame_rate(int *frame_rate_num, int *frame_rate_den, const char *arg)
2801 AVRational frame_rate;
2802 int ret = av_parse_video_frame_rate(&frame_rate, arg);
2803 *frame_rate_num= frame_rate.num;
2804 *frame_rate_den= frame_rate.den;
2809 * Gets the current time in microseconds.
2811 int64_t av_gettime(void)
2814 gettimeofday(&tv,NULL);
2815 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
2818 int64_t parse_date(const char *datestr, int duration)
2824 static const char *date_fmt[] = {
2828 static const char *time_fmt[] = {
2838 time_t now = time(0);
2840 len = strlen(datestr);
2842 lastch = datestr[len - 1];
2845 is_utc = (lastch == 'z' || lastch == 'Z');
2847 memset(&dt, 0, sizeof(dt));
2852 /* parse the year-month-day part */
2853 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2854 q = small_strptime(p, date_fmt[i], &dt);
2860 /* if the year-month-day part is missing, then take the
2861 * current year-month-day time */
2866 dt = *localtime(&now);
2868 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2873 if (*p == 'T' || *p == 't' || *p == ' ')
2876 /* parse the hour-minute-second part */
2877 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2878 q = small_strptime(p, time_fmt[i], &dt);
2884 /* parse datestr as a duration */
2889 /* parse datestr as HH:MM:SS */
2890 q = small_strptime(p, time_fmt[0], &dt);
2892 /* parse datestr as S+ */
2893 dt.tm_sec = strtol(p, (char **)&q, 10);
2895 /* the parsing didn't succeed */
2902 /* Now we have all the fields that we can get */
2908 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2910 dt.tm_isdst = -1; /* unknown */
2920 /* parse the .m... part */
2924 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2927 val += n * (*q - '0');
2931 return negative ? -t : t;
2934 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2944 while (*p != '\0' && *p != '=' && *p != '&') {
2945 if ((q - tag) < sizeof(tag) - 1)
2953 while (*p != '&' && *p != '\0') {
2954 if ((q - arg) < arg_size - 1) {
2964 if (!strcmp(tag, tag1))
2973 int av_get_frame_filename(char *buf, int buf_size,
2974 const char *path, int number)
2977 char *q, buf1[20], c;
2978 int nd, len, percentd_found;
2990 while (isdigit(*p)) {
2991 nd = nd * 10 + *p++ - '0';
2994 } while (isdigit(c));
3003 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3005 if ((q - buf + len) > buf_size - 1)
3007 memcpy(q, buf1, len);
3015 if ((q - buf) < buf_size - 1)
3019 if (!percentd_found)
3028 static void hex_dump_internal(void *avcl, FILE *f, int level, uint8_t *buf, int size)
3031 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3033 for(i=0;i<size;i+=16) {
3040 PRINT(" %02x", buf[i+j]);
3045 for(j=0;j<len;j++) {
3047 if (c < ' ' || c > '~')
3056 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3058 hex_dump_internal(NULL, f, 0, buf, size);
3061 void av_hex_dump_log(void *avcl, int level, uint8_t *buf, int size)
3063 hex_dump_internal(avcl, NULL, level, buf, size);
3066 //FIXME needs to know the time_base
3067 static void pkt_dump_internal(void *avcl, FILE *f, int level, AVPacket *pkt, int dump_payload)
3069 #define PRINT(...) do { if (!f) av_log(avcl, level, __VA_ARGS__); else fprintf(f, __VA_ARGS__); } while(0)
3070 PRINT("stream #%d:\n", pkt->stream_index);
3071 PRINT(" keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3072 PRINT(" duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3073 /* DTS is _always_ valid after av_read_frame() */
3075 if (pkt->dts == AV_NOPTS_VALUE)
3078 PRINT("%0.3f", (double)pkt->dts / AV_TIME_BASE);
3079 /* PTS may not be known if B-frames are present. */
3081 if (pkt->pts == AV_NOPTS_VALUE)
3084 PRINT("%0.3f", (double)pkt->pts / AV_TIME_BASE);
3086 PRINT(" size=%d\n", pkt->size);
3089 av_hex_dump(f, pkt->data, pkt->size);
3092 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3094 pkt_dump_internal(NULL, f, 0, pkt, dump_payload);
3097 void av_pkt_dump_log(void *avcl, int level, AVPacket *pkt, int dump_payload)
3099 pkt_dump_internal(avcl, NULL, level, pkt, dump_payload);
3102 void url_split(char *proto, int proto_size,
3103 char *authorization, int authorization_size,
3104 char *hostname, int hostname_size,
3106 char *path, int path_size,
3109 const char *p, *ls, *at, *col, *brk;
3111 if (port_ptr) *port_ptr = -1;
3112 if (proto_size > 0) proto[0] = 0;
3113 if (authorization_size > 0) authorization[0] = 0;
3114 if (hostname_size > 0) hostname[0] = 0;
3115 if (path_size > 0) path[0] = 0;
3117 /* parse protocol */
3118 if ((p = strchr(url, ':'))) {
3119 av_strlcpy(proto, url, FFMIN(proto_size, p + 1 - url));
3124 /* no protocol means plain filename */
3125 av_strlcpy(path, url, path_size);
3129 /* separate path from hostname */
3130 ls = strchr(p, '/');
3132 ls = strchr(p, '?');
3134 av_strlcpy(path, ls, path_size);
3136 ls = &p[strlen(p)]; // XXX
3138 /* the rest is hostname, use that to parse auth/port */
3140 /* authorization (user[:pass]@hostname) */
3141 if ((at = strchr(p, '@')) && at < ls) {
3142 av_strlcpy(authorization, p,
3143 FFMIN(authorization_size, at + 1 - p));
3144 p = at + 1; /* skip '@' */
3147 if (*p == '[' && (brk = strchr(p, ']')) && brk < ls) {
3149 av_strlcpy(hostname, p + 1,
3150 FFMIN(hostname_size, brk - p));
3151 if (brk[1] == ':' && port_ptr)
3152 *port_ptr = atoi(brk + 2);
3153 } else if ((col = strchr(p, ':')) && col < ls) {
3154 av_strlcpy(hostname, p,
3155 FFMIN(col + 1 - p, hostname_size));
3156 if (port_ptr) *port_ptr = atoi(col + 1);
3158 av_strlcpy(hostname, p,
3159 FFMIN(ls + 1 - p, hostname_size));
3163 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3164 int pts_num, int pts_den)
3166 unsigned int gcd= ff_gcd(pts_num, pts_den);
3167 s->pts_wrap_bits = pts_wrap_bits;
3168 s->time_base.num = pts_num/gcd;
3169 s->time_base.den = pts_den/gcd;
3172 av_log(NULL, AV_LOG_DEBUG, "st:%d removing common factor %d from timebase\n", s->index, gcd);
3175 /* fraction handling */
3178 * f = val + (num / den) + 0.5.
3180 * 'num' is normalized so that it is such as 0 <= num < den.
3182 * @param f fractional number
3183 * @param val integer value
3184 * @param num must be >= 0
3185 * @param den must be >= 1
3187 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3200 * Fractional addition to f: f = f + (incr / f->den).
3202 * @param f fractional number
3203 * @param incr increment, can be positive or negative
3205 static void av_frac_add(AVFrac *f, int64_t incr)
3209 num = f->num + incr;
3212 f->val += num / den;
3218 } else if (num >= den) {
3219 f->val += num / den;