2 * Various utilities for ffmpeg system
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 #include "allformats.h"
27 * @file libavformat/utils.c
28 * Various utility functions for using ffmpeg library.
31 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
32 static void av_frac_add(AVFrac *f, int64_t incr);
33 static void av_frac_set(AVFrac *f, int64_t val);
35 /** head of registered input format linked list. */
36 AVInputFormat *first_iformat = NULL;
37 /** head of registered output format linked list. */
38 AVOutputFormat *first_oformat = NULL;
39 /** head of registered image format linked list. */
40 AVImageFormat *first_image_format = NULL;
42 void av_register_input_format(AVInputFormat *format)
46 while (*p != NULL) p = &(*p)->next;
51 void av_register_output_format(AVOutputFormat *format)
55 while (*p != NULL) p = &(*p)->next;
60 int match_ext(const char *filename, const char *extensions)
68 ext = strrchr(filename, '.');
74 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
77 if (!strcasecmp(ext1, ext))
87 AVOutputFormat *guess_format(const char *short_name, const char *filename,
88 const char *mime_type)
90 AVOutputFormat *fmt, *fmt_found;
93 /* specific test for image sequences */
94 #ifdef CONFIG_IMAGE2_MUXER
95 if (!short_name && filename &&
96 filename_number_test(filename) >= 0 &&
97 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
98 return guess_format("image2", NULL, NULL);
101 if (!short_name && filename &&
102 filename_number_test(filename) >= 0 &&
103 guess_image_format(filename)) {
104 return guess_format("image", NULL, NULL);
107 /* find the proper file type */
111 while (fmt != NULL) {
113 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
115 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
117 if (filename && fmt->extensions &&
118 match_ext(filename, fmt->extensions)) {
121 if (score > score_max) {
130 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
131 const char *mime_type)
133 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
136 AVOutputFormat *stream_fmt;
137 char stream_format_name[64];
139 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
140 stream_fmt = guess_format(stream_format_name, NULL, NULL);
150 * Guesses the codec id based upon muxer and filename.
152 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
153 const char *filename, const char *mime_type, enum CodecType type){
154 if(type == CODEC_TYPE_VIDEO){
155 enum CodecID codec_id= CODEC_ID_NONE;
157 #ifdef CONFIG_IMAGE2_MUXER
158 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
159 codec_id= av_guess_image2_codec(filename);
162 if(codec_id == CODEC_ID_NONE)
163 codec_id= fmt->video_codec;
165 }else if(type == CODEC_TYPE_AUDIO)
166 return fmt->audio_codec;
168 return CODEC_ID_NONE;
172 * finds AVInputFormat based on input format's short name.
174 AVInputFormat *av_find_input_format(const char *short_name)
177 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
178 if (!strcmp(fmt->name, short_name))
184 /* memory handling */
187 * Default packet destructor.
189 void av_destruct_packet(AVPacket *pkt)
192 pkt->data = NULL; pkt->size = 0;
196 * Allocate the payload of a packet and intialized its fields to default values.
199 * @param size wanted payload size
200 * @return 0 if OK. AVERROR_xxx otherwise.
202 int av_new_packet(AVPacket *pkt, int size)
205 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
206 return AVERROR_NOMEM;
207 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
209 return AVERROR_NOMEM;
210 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
215 pkt->destruct = av_destruct_packet;
220 * Allocate and read the payload of a packet and intialized its fields to default values.
223 * @param size wanted payload size
224 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
226 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
228 int ret= av_new_packet(pkt, size);
233 pkt->pos= url_ftell(s);
235 ret= get_buffer(s, pkt->data, size);
244 /* This is a hack - the packet memory allocation stuff is broken. The
245 packet is allocated if it was not really allocated */
246 int av_dup_packet(AVPacket *pkt)
248 if (pkt->destruct != av_destruct_packet) {
250 /* we duplicate the packet and don't forget to put the padding
252 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
253 return AVERROR_NOMEM;
254 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
256 return AVERROR_NOMEM;
258 memcpy(data, pkt->data, pkt->size);
259 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
261 pkt->destruct = av_destruct_packet;
268 int fifo_init(FifoBuffer *f, int size)
270 f->buffer = av_malloc(size);
273 f->end = f->buffer + size;
274 f->wptr = f->rptr = f->buffer;
278 void fifo_free(FifoBuffer *f)
283 int fifo_size(FifoBuffer *f, uint8_t *rptr)
290 if (f->wptr >= rptr) {
291 size = f->wptr - rptr;
293 size = (f->end - rptr) + (f->wptr - f->buffer);
299 * Get data from the fifo (returns -1 if not enough data).
301 int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
310 if (f->wptr >= rptr) {
311 size = f->wptr - rptr;
313 size = (f->end - rptr) + (f->wptr - f->buffer);
318 while (buf_size > 0) {
322 memcpy(buf, rptr, len);
336 void fifo_realloc(FifoBuffer *f, unsigned int new_size){
337 unsigned int old_size= f->end - f->buffer;
339 if(old_size < new_size){
340 uint8_t *old= f->buffer;
342 f->buffer= av_realloc(f->buffer, new_size);
344 f->rptr += f->buffer - old;
345 f->wptr += f->buffer - old;
347 if(f->wptr < f->rptr){
348 memmove(f->rptr + new_size - old_size, f->rptr, f->buffer + old_size - f->rptr);
349 f->rptr += new_size - old_size;
351 f->end= f->buffer + new_size;
355 void fifo_write(FifoBuffer *f, const uint8_t *buf, int size, uint8_t **wptr_ptr)
368 memcpy(wptr, buf, len);
378 /* get data from the fifo (return -1 if not enough data) */
379 int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
381 uint8_t *rptr = *rptr_ptr;
384 if (f->wptr >= rptr) {
385 size = f->wptr - rptr;
387 size = (f->end - rptr) + (f->wptr - f->buffer);
392 while (buf_size > 0) {
396 put_buffer(pb, rptr, len);
406 int filename_number_test(const char *filename)
411 return get_frame_filename(buf, sizeof(buf), filename, 1);
417 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
419 AVInputFormat *fmt1, *fmt;
420 int score, score_max;
424 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
425 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
428 if (fmt1->read_probe) {
429 score = fmt1->read_probe(pd);
430 } else if (fmt1->extensions) {
431 if (match_ext(pd->filename, fmt1->extensions)) {
435 if (score > score_max) {
443 /************************************************************/
444 /* input media file */
447 * Open a media file from an IO stream. 'fmt' must be specified.
449 static const char* format_to_name(void* ptr)
451 AVFormatContext* fc = (AVFormatContext*) ptr;
452 if(fc->iformat) return fc->iformat->name;
453 else if(fc->oformat) return fc->oformat->name;
457 #define OFFSET(x) (int)&((AVFormatContext*)0)->x
458 #define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
459 //these names are too long to be readable
460 #define E AV_OPT_FLAG_ENCODING_PARAM
461 #define D AV_OPT_FLAG_DECODING_PARAM
463 static const AVOption options[]={
464 {"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, DEFAULT, 32, INT_MAX, D},
468 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
470 void avformat_get_context_defaults(AVFormatContext *s){
471 memset(s, 0, sizeof(AVFormatContext));
473 /* from mpegts.c: 1.0 second at 24Mbit/s */
477 AVFormatContext *av_alloc_format_context(void)
480 ic = av_mallocz(sizeof(AVFormatContext));
482 avformat_get_context_defaults(ic);
483 ic->av_class = &av_format_context_class;
488 * Allocates all the structures needed to read an input stream.
489 * This does not open the needed codecs for decoding the stream[s].
491 int av_open_input_stream(AVFormatContext **ic_ptr,
492 ByteIOContext *pb, const char *filename,
493 AVInputFormat *fmt, AVFormatParameters *ap)
497 AVFormatParameters default_ap;
501 memset(ap, 0, sizeof(default_ap));
504 if(!ap->prealloced_context)
505 ic = av_alloc_format_context();
515 ic->duration = AV_NOPTS_VALUE;
516 ic->start_time = AV_NOPTS_VALUE;
517 pstrcpy(ic->filename, sizeof(ic->filename), filename);
519 /* allocate private data */
520 if (fmt->priv_data_size > 0) {
521 ic->priv_data = av_mallocz(fmt->priv_data_size);
522 if (!ic->priv_data) {
527 ic->priv_data = NULL;
530 err = ic->iformat->read_header(ic, ap);
535 ic->data_offset = url_ftell(&ic->pb);
541 av_freep(&ic->priv_data);
548 /** Size of probe buffer, for guessing file type from file contents. */
549 #define PROBE_BUF_MIN 2048
550 #define PROBE_BUF_MAX (1<<20)
553 * Open a media file as input. The codec are not opened. Only the file
554 * header (if present) is read.
556 * @param ic_ptr the opened media file handle is put here
557 * @param filename filename to open.
558 * @param fmt if non NULL, force the file format to use
559 * @param buf_size optional buffer size (zero if default is OK)
560 * @param ap additionnal parameters needed when opening the file (NULL if default)
561 * @return 0 if OK. AVERROR_xxx otherwise.
563 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
566 AVFormatParameters *ap)
568 int err, must_open_file, file_opened, probe_size;
569 AVProbeData probe_data, *pd = &probe_data;
570 ByteIOContext pb1, *pb = &pb1;
575 pd->filename = filename;
580 /* guess format if no file can be opened */
581 fmt = av_probe_input_format(pd, 0);
584 /* do not open file if the format does not need it. XXX: specific
585 hack needed to handle RTSP/TCP */
587 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
589 pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
592 if (!fmt || must_open_file) {
593 /* if no file needed do not try to open one */
594 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
600 url_setbufsize(pb, buf_size);
603 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
604 /* read probe data */
605 pd->buf= av_realloc(pd->buf, probe_size);
606 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
607 if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
609 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
615 /* guess file format */
616 fmt = av_probe_input_format(pd, 1);
621 /* if still no format found, error */
627 /* XXX: suppress this hack for redirectors */
628 #ifdef CONFIG_NETWORK
629 if (fmt == &redir_demuxer) {
630 err = redir_open(ic_ptr, pb);
636 /* check filename in case of an image number is expected */
637 if (fmt->flags & AVFMT_NEEDNUMBER) {
638 if (filename_number_test(filename) < 0) {
639 err = AVERROR_NUMEXPECTED;
643 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
656 /*******************************************************/
659 * Read a transport packet from a media file.
661 * This function is absolete and should never be used.
662 * Use av_read_frame() instead.
664 * @param s media file handle
665 * @param pkt is filled
666 * @return 0 if OK. AVERROR_xxx if error.
668 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
670 return s->iformat->read_packet(s, pkt);
673 /**********************************************************/
676 * Get the number of samples of an audio frame. Return (-1) if error.
678 static int get_audio_frame_size(AVCodecContext *enc, int size)
682 if (enc->frame_size <= 1) {
683 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
685 if (bits_per_sample) {
686 if (enc->channels == 0)
688 frame_size = (size << 3) / (bits_per_sample * enc->channels);
690 /* used for example by ADPCM codecs */
691 if (enc->bit_rate == 0)
693 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
696 frame_size = enc->frame_size;
703 * Return the frame duration in seconds, return 0 if not available.
705 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
706 AVCodecParserContext *pc, AVPacket *pkt)
712 switch(st->codec->codec_type) {
713 case CODEC_TYPE_VIDEO:
714 if(st->time_base.num*1000LL > st->time_base.den){
715 *pnum = st->time_base.num;
716 *pden = st->time_base.den;
717 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
718 *pnum = st->codec->time_base.num;
719 *pden = st->codec->time_base.den;
720 if (pc && pc->repeat_pict) {
722 *pnum = (*pnum) * (2 + pc->repeat_pict);
726 case CODEC_TYPE_AUDIO:
727 frame_size = get_audio_frame_size(st->codec, pkt->size);
731 *pden = st->codec->sample_rate;
738 static int is_intra_only(AVCodecContext *enc){
739 if(enc->codec_type == CODEC_TYPE_AUDIO){
741 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
742 switch(enc->codec_id){
744 case CODEC_ID_MJPEGB:
746 case CODEC_ID_RAWVIDEO:
747 case CODEC_ID_DVVIDEO:
748 case CODEC_ID_HUFFYUV:
749 case CODEC_ID_FFVHUFF:
760 static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
761 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
762 int64_t delta= last_ts - mask/2;
763 return ((lsb - delta)&mask) + delta;
766 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
767 AVCodecParserContext *pc, AVPacket *pkt)
769 int num, den, presentation_delayed;
770 /* handle wrapping */
771 if(st->cur_dts != AV_NOPTS_VALUE){
772 if(pkt->pts != AV_NOPTS_VALUE)
773 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
774 if(pkt->dts != AV_NOPTS_VALUE)
775 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
778 if (pkt->duration == 0) {
779 compute_frame_duration(&num, &den, st, pc, pkt);
781 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
785 if(is_intra_only(st->codec))
786 pkt->flags |= PKT_FLAG_KEY;
788 /* do we have a video B frame ? */
789 presentation_delayed = 0;
790 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
791 /* XXX: need has_b_frame, but cannot get it if the codec is
793 if (( st->codec->codec_id == CODEC_ID_H264
794 || st->codec->has_b_frames) &&
795 pc && pc->pict_type != FF_B_TYPE)
796 presentation_delayed = 1;
797 /* this may be redundant, but it shouldnt hurt */
798 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
799 presentation_delayed = 1;
802 if(st->cur_dts == AV_NOPTS_VALUE){
803 if(presentation_delayed) st->cur_dts = -pkt->duration;
804 else st->cur_dts = 0;
807 // av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld 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 (presentation_delayed) {
810 /* DTS = decompression time stamp */
811 /* PTS = presentation time stamp */
812 if (pkt->dts == AV_NOPTS_VALUE) {
813 /* if we know the last pts, use it */
814 if(st->last_IP_pts != AV_NOPTS_VALUE)
815 st->cur_dts = pkt->dts = st->last_IP_pts;
817 pkt->dts = st->cur_dts;
819 st->cur_dts = pkt->dts;
821 /* this is tricky: the dts must be incremented by the duration
822 of the frame we are displaying, i.e. the last I or P frame */
823 if (st->last_IP_duration == 0)
824 st->cur_dts += pkt->duration;
826 st->cur_dts += st->last_IP_duration;
827 st->last_IP_duration = pkt->duration;
828 st->last_IP_pts= pkt->pts;
829 /* cannot compute PTS if not present (we can compute it only
830 by knowing the futur */
831 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
832 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
833 int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
834 int64_t new_diff= ABS(st->cur_dts - pkt->pts);
835 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
836 pkt->pts += pkt->duration;
837 // av_log(NULL, AV_LOG_DEBUG, "id:%d old:%Ld new:%Ld dur:%d cur:%Ld size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
841 /* presentation is not delayed : PTS and DTS are the same */
842 if (pkt->pts == AV_NOPTS_VALUE) {
843 if (pkt->dts == AV_NOPTS_VALUE) {
844 pkt->pts = st->cur_dts;
845 pkt->dts = st->cur_dts;
848 st->cur_dts = pkt->dts;
852 st->cur_dts = pkt->pts;
855 st->cur_dts += pkt->duration;
857 // av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
862 /* key frame computation */
863 switch(st->codec->codec_type) {
864 case CODEC_TYPE_VIDEO:
865 if (pc->pict_type == FF_I_TYPE)
866 pkt->flags |= PKT_FLAG_KEY;
868 case CODEC_TYPE_AUDIO:
869 pkt->flags |= PKT_FLAG_KEY;
877 void av_destruct_packet_nofree(AVPacket *pkt)
879 pkt->data = NULL; pkt->size = 0;
882 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
888 /* select current input stream component */
891 if (!st->need_parsing || !st->parser) {
892 /* no parsing needed: we just output the packet as is */
893 /* raw data support */
895 compute_pkt_fields(s, st, NULL, pkt);
898 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
899 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
900 s->cur_ptr, s->cur_len,
901 s->cur_pkt.pts, s->cur_pkt.dts);
902 s->cur_pkt.pts = AV_NOPTS_VALUE;
903 s->cur_pkt.dts = AV_NOPTS_VALUE;
904 /* increment read pointer */
908 /* return packet if any */
912 pkt->stream_index = st->index;
913 pkt->pts = st->parser->pts;
914 pkt->dts = st->parser->dts;
915 pkt->destruct = av_destruct_packet_nofree;
916 compute_pkt_fields(s, st, st->parser, pkt);
921 av_free_packet(&s->cur_pkt);
925 /* read next packet */
926 ret = av_read_packet(s, &s->cur_pkt);
930 /* return the last frames, if any */
931 for(i = 0; i < s->nb_streams; i++) {
933 if (st->parser && st->need_parsing) {
934 av_parser_parse(st->parser, st->codec,
935 &pkt->data, &pkt->size,
937 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
942 /* no more packets: really terminates parsing */
946 st = s->streams[s->cur_pkt.stream_index];
947 if(st->codec->debug & FF_DEBUG_PTS)
948 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%lld, dts=%lld, size=%d\n",
949 s->cur_pkt.stream_index,
955 s->cur_ptr = s->cur_pkt.data;
956 s->cur_len = s->cur_pkt.size;
957 if (st->need_parsing && !st->parser) {
958 st->parser = av_parser_init(st->codec->codec_id);
960 /* no parser available : just output the raw packets */
961 st->need_parsing = 0;
962 }else if(st->need_parsing == 2){
963 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
968 if(st->codec->debug & FF_DEBUG_PTS)
969 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%lld, dts=%lld, size=%d\n",
979 * Return the next frame of a stream.
981 * The returned packet is valid
982 * until the next av_read_frame() or until av_close_input_file() and
983 * must be freed with av_free_packet. For video, the packet contains
984 * exactly one frame. For audio, it contains an integer number of
985 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
986 * data). If the audio frames have a variable size (e.g. MPEG audio),
987 * then it contains one frame.
989 * pkt->pts, pkt->dts and pkt->duration are always set to correct
990 * values in AV_TIME_BASE unit (and guessed if the format cannot
991 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
992 * has B frames, so it is better to rely on pkt->dts if you do not
993 * decompress the payload.
995 * @return 0 if OK, < 0 if error or end of file.
997 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1001 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1004 pktl = s->packet_buffer;
1006 AVPacket *next_pkt= &pktl->pkt;
1008 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1009 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1010 if( pktl->pkt.stream_index == next_pkt->stream_index
1011 && next_pkt->dts < pktl->pkt.dts
1012 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1013 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1014 next_pkt->pts= pktl->pkt.dts;
1018 pktl = s->packet_buffer;
1021 if( next_pkt->pts != AV_NOPTS_VALUE
1022 || next_pkt->dts == AV_NOPTS_VALUE
1024 /* read packet from packet buffer, if there is data */
1026 s->packet_buffer = pktl->next;
1032 AVPacketList **plast_pktl= &s->packet_buffer;
1033 int ret= av_read_frame_internal(s, pkt);
1035 if(pktl && ret != -EAGAIN){
1042 /* duplicate the packet */
1043 if (av_dup_packet(pkt) < 0)
1044 return AVERROR_NOMEM;
1046 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
1048 pktl = av_mallocz(sizeof(AVPacketList));
1050 return AVERROR_NOMEM;
1052 /* add the packet in the buffered packet list */
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)
1085 if (s->nb_streams <= 0)
1087 for(i = 0; i < s->nb_streams; i++) {
1089 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1097 * Flush the frame reader.
1099 static void av_read_frame_flush(AVFormatContext *s)
1104 flush_packet_queue(s);
1106 /* free previous packet */
1108 if (s->cur_st->parser)
1109 av_free_packet(&s->cur_pkt);
1116 /* for each stream, reset read state */
1117 for(i = 0; i < s->nb_streams; i++) {
1121 av_parser_close(st->parser);
1124 st->last_IP_pts = AV_NOPTS_VALUE;
1125 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1130 * Updates cur_dts of all streams based on given timestamp and AVStream.
1132 * Stream ref_st unchanged, others set cur_dts in their native timebase
1133 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1134 * @param timestamp new dts expressed in time_base of param ref_st
1135 * @param ref_st reference stream giving time_base of param timestamp
1137 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1140 for(i = 0; i < s->nb_streams; i++) {
1141 AVStream *st = s->streams[i];
1143 st->cur_dts = av_rescale(timestamp,
1144 st->time_base.den * (int64_t)ref_st->time_base.num,
1145 st->time_base.num * (int64_t)ref_st->time_base.den);
1150 * Add a index entry into a sorted list updateing if it is already there.
1152 * @param timestamp timestamp in the timebase of the given stream
1154 int av_add_index_entry(AVStream *st,
1155 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1157 AVIndexEntry *entries, *ie;
1160 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1163 entries = av_fast_realloc(st->index_entries,
1164 &st->index_entries_allocated_size,
1165 (st->nb_index_entries + 1) *
1166 sizeof(AVIndexEntry));
1170 st->index_entries= entries;
1172 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1175 index= st->nb_index_entries++;
1176 ie= &entries[index];
1177 assert(index==0 || ie[-1].timestamp < timestamp);
1179 ie= &entries[index];
1180 if(ie->timestamp != timestamp){
1181 if(ie->timestamp <= timestamp)
1183 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1184 st->nb_index_entries++;
1185 }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1186 distance= ie->min_distance;
1190 ie->timestamp = timestamp;
1191 ie->min_distance= distance;
1199 * build an index for raw streams using a parser.
1201 static void av_build_index_raw(AVFormatContext *s)
1203 AVPacket pkt1, *pkt = &pkt1;
1208 av_read_frame_flush(s);
1209 url_fseek(&s->pb, s->data_offset, SEEK_SET);
1212 ret = av_read_frame(s, pkt);
1215 if (pkt->stream_index == 0 && st->parser &&
1216 (pkt->flags & PKT_FLAG_KEY)) {
1217 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1218 0, 0, AVINDEX_KEYFRAME);
1220 av_free_packet(pkt);
1225 * Returns TRUE if we deal with a raw stream.
1227 * Raw codec data and parsing needed.
1229 static int is_raw_stream(AVFormatContext *s)
1233 if (s->nb_streams != 1)
1236 if (!st->need_parsing)
1242 * Gets the index for a specific timestamp.
1243 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1244 * the timestamp which is <= the requested one, if backward is 0
1245 * then it will be >=
1246 * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1247 * @return < 0 if no such timestamp could be found
1249 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1252 AVIndexEntry *entries= st->index_entries;
1253 int nb_entries= st->nb_index_entries;
1262 timestamp = entries[m].timestamp;
1263 if(timestamp >= wanted_timestamp)
1265 if(timestamp <= wanted_timestamp)
1268 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1270 if(!(flags & AVSEEK_FLAG_ANY)){
1271 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1272 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1284 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1285 * this isnt supposed to be called directly by a user application, but by demuxers
1286 * @param target_ts target timestamp in the time base of the given stream
1287 * @param stream_index stream number
1289 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1290 AVInputFormat *avif= s->iformat;
1291 int64_t pos_min, pos_max, pos, pos_limit;
1292 int64_t ts_min, ts_max, ts;
1293 int64_t start_pos, filesize;
1294 int index, no_change;
1297 if (stream_index < 0)
1301 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1305 ts_min= AV_NOPTS_VALUE;
1306 pos_limit= -1; //gcc falsely says it may be uninitalized
1308 st= s->streams[stream_index];
1309 if(st->index_entries){
1312 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()
1313 index= FFMAX(index, 0);
1314 e= &st->index_entries[index];
1316 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1318 ts_min= e->timestamp;
1320 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1327 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1328 assert(index < st->nb_index_entries);
1330 e= &st->index_entries[index];
1331 assert(e->timestamp >= target_ts);
1333 ts_max= e->timestamp;
1334 pos_limit= pos_max - e->min_distance;
1336 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1337 pos_max,pos_limit, ts_max);
1342 if(ts_min == AV_NOPTS_VALUE){
1343 pos_min = s->data_offset;
1344 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1345 if (ts_min == AV_NOPTS_VALUE)
1349 if(ts_max == AV_NOPTS_VALUE){
1351 filesize = url_fsize(&s->pb);
1352 pos_max = filesize - 1;
1355 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1357 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1358 if (ts_max == AV_NOPTS_VALUE)
1362 int64_t tmp_pos= pos_max + 1;
1363 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1364 if(tmp_ts == AV_NOPTS_VALUE)
1368 if(tmp_pos >= filesize)
1374 if(ts_min > ts_max){
1376 }else if(ts_min == ts_max){
1381 while (pos_min < pos_limit) {
1383 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1387 assert(pos_limit <= pos_max);
1390 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1391 // interpolate position (better than dichotomy)
1392 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1393 + pos_min - approximate_keyframe_distance;
1394 }else if(no_change==1){
1395 // bisection, if interpolation failed to change min or max pos last time
1396 pos = (pos_min + pos_limit)>>1;
1398 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1403 else if(pos > pos_limit)
1407 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1413 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);
1415 assert(ts != AV_NOPTS_VALUE);
1416 if (target_ts <= ts) {
1417 pos_limit = start_pos - 1;
1421 if (target_ts >= ts) {
1427 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1428 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1431 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1433 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1434 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1435 pos, ts_min, target_ts, ts_max);
1438 url_fseek(&s->pb, pos, SEEK_SET);
1440 av_update_cur_dts(s, st, ts);
1445 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1446 int64_t pos_min, pos_max;
1450 if (stream_index < 0)
1453 st= s->streams[stream_index];
1456 pos_min = s->data_offset;
1457 pos_max = url_fsize(&s->pb) - 1;
1459 if (pos < pos_min) pos= pos_min;
1460 else if(pos > pos_max) pos= pos_max;
1462 url_fseek(&s->pb, pos, SEEK_SET);
1465 av_update_cur_dts(s, st, ts);
1470 static int av_seek_frame_generic(AVFormatContext *s,
1471 int stream_index, int64_t timestamp, int flags)
1477 if (!s->index_built) {
1478 if (is_raw_stream(s)) {
1479 av_build_index_raw(s);
1486 st = s->streams[stream_index];
1487 index = av_index_search_timestamp(st, timestamp, flags);
1491 /* now we have found the index, we can seek */
1492 ie = &st->index_entries[index];
1493 av_read_frame_flush(s);
1494 url_fseek(&s->pb, ie->pos, SEEK_SET);
1496 av_update_cur_dts(s, st, ie->timestamp);
1502 * Seek to the key frame at timestamp.
1503 * 'timestamp' in 'stream_index'.
1504 * @param stream_index If stream_index is (-1), a default
1505 * stream is selected, and timestamp is automatically converted
1506 * from AV_TIME_BASE units to the stream specific time_base.
1507 * @param timestamp timestamp in AVStream.time_base units
1508 * or if there is no stream specified then in AV_TIME_BASE units
1509 * @param flags flags which select direction and seeking mode
1510 * @return >= 0 on success
1512 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1517 av_read_frame_flush(s);
1519 if(flags & AVSEEK_FLAG_BYTE)
1520 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1522 if(stream_index < 0){
1523 stream_index= av_find_default_stream_index(s);
1524 if(stream_index < 0)
1527 st= s->streams[stream_index];
1528 /* timestamp for default must be expressed in AV_TIME_BASE units */
1529 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1531 st= s->streams[stream_index];
1533 /* first, we try the format specific seek */
1534 if (s->iformat->read_seek)
1535 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1542 if(s->iformat->read_timestamp)
1543 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1545 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1548 /*******************************************************/
1551 * Returns TRUE if the stream has accurate timings in any stream.
1553 * @return TRUE if the stream has accurate timings for at least one component.
1555 static int av_has_timings(AVFormatContext *ic)
1560 for(i = 0;i < ic->nb_streams; i++) {
1561 st = ic->streams[i];
1562 if (st->start_time != AV_NOPTS_VALUE &&
1563 st->duration != AV_NOPTS_VALUE)
1570 * Estimate the stream timings from the one of each components.
1572 * Also computes the global bitrate if possible.
1574 static void av_update_stream_timings(AVFormatContext *ic)
1576 int64_t start_time, start_time1, end_time, end_time1;
1580 start_time = MAXINT64;
1581 end_time = MININT64;
1582 for(i = 0;i < ic->nb_streams; i++) {
1583 st = ic->streams[i];
1584 if (st->start_time != AV_NOPTS_VALUE) {
1585 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1586 if (start_time1 < start_time)
1587 start_time = start_time1;
1588 if (st->duration != AV_NOPTS_VALUE) {
1589 end_time1 = start_time1
1590 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1591 if (end_time1 > end_time)
1592 end_time = end_time1;
1596 if (start_time != MAXINT64) {
1597 ic->start_time = start_time;
1598 if (end_time != MININT64) {
1599 ic->duration = end_time - start_time;
1600 if (ic->file_size > 0) {
1601 /* compute the bit rate */
1602 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1603 (double)ic->duration;
1610 static void fill_all_stream_timings(AVFormatContext *ic)
1615 av_update_stream_timings(ic);
1616 for(i = 0;i < ic->nb_streams; i++) {
1617 st = ic->streams[i];
1618 if (st->start_time == AV_NOPTS_VALUE) {
1619 if(ic->start_time != AV_NOPTS_VALUE)
1620 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1621 if(ic->duration != AV_NOPTS_VALUE)
1622 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1627 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1629 int64_t filesize, duration;
1633 /* if bit_rate is already set, we believe it */
1634 if (ic->bit_rate == 0) {
1636 for(i=0;i<ic->nb_streams;i++) {
1637 st = ic->streams[i];
1638 bit_rate += st->codec->bit_rate;
1640 ic->bit_rate = bit_rate;
1643 /* if duration is already set, we believe it */
1644 if (ic->duration == AV_NOPTS_VALUE &&
1645 ic->bit_rate != 0 &&
1646 ic->file_size != 0) {
1647 filesize = ic->file_size;
1649 for(i = 0; i < ic->nb_streams; i++) {
1650 st = ic->streams[i];
1651 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1652 if (st->start_time == AV_NOPTS_VALUE ||
1653 st->duration == AV_NOPTS_VALUE) {
1655 st->duration = duration;
1662 #define DURATION_MAX_READ_SIZE 250000
1664 /* only usable for MPEG-PS streams */
1665 static void av_estimate_timings_from_pts(AVFormatContext *ic)
1667 AVPacket pkt1, *pkt = &pkt1;
1669 int read_size, i, ret;
1671 int64_t filesize, offset, duration;
1673 /* free previous packet */
1674 if (ic->cur_st && ic->cur_st->parser)
1675 av_free_packet(&ic->cur_pkt);
1678 /* flush packet queue */
1679 flush_packet_queue(ic);
1681 for(i=0;i<ic->nb_streams;i++) {
1682 st = ic->streams[i];
1684 av_parser_close(st->parser);
1689 /* we read the first packets to get the first PTS (not fully
1690 accurate, but it is enough now) */
1691 url_fseek(&ic->pb, 0, SEEK_SET);
1694 if (read_size >= DURATION_MAX_READ_SIZE)
1696 /* if all info is available, we can stop */
1697 for(i = 0;i < ic->nb_streams; i++) {
1698 st = ic->streams[i];
1699 if (st->start_time == AV_NOPTS_VALUE)
1702 if (i == ic->nb_streams)
1705 ret = av_read_packet(ic, pkt);
1708 read_size += pkt->size;
1709 st = ic->streams[pkt->stream_index];
1710 if (pkt->pts != AV_NOPTS_VALUE) {
1711 if (st->start_time == AV_NOPTS_VALUE)
1712 st->start_time = pkt->pts;
1714 av_free_packet(pkt);
1717 /* estimate the end time (duration) */
1718 /* XXX: may need to support wrapping */
1719 filesize = ic->file_size;
1720 offset = filesize - DURATION_MAX_READ_SIZE;
1724 url_fseek(&ic->pb, offset, SEEK_SET);
1727 if (read_size >= DURATION_MAX_READ_SIZE)
1729 /* if all info is available, we can stop */
1730 for(i = 0;i < ic->nb_streams; i++) {
1731 st = ic->streams[i];
1732 if (st->duration == AV_NOPTS_VALUE)
1735 if (i == ic->nb_streams)
1738 ret = av_read_packet(ic, pkt);
1741 read_size += pkt->size;
1742 st = ic->streams[pkt->stream_index];
1743 if (pkt->pts != AV_NOPTS_VALUE) {
1744 end_time = pkt->pts;
1745 duration = end_time - st->start_time;
1747 if (st->duration == AV_NOPTS_VALUE ||
1748 st->duration < duration)
1749 st->duration = duration;
1752 av_free_packet(pkt);
1755 fill_all_stream_timings(ic);
1757 url_fseek(&ic->pb, 0, SEEK_SET);
1760 static void av_estimate_timings(AVFormatContext *ic)
1764 /* get the file size, if possible */
1765 if (ic->iformat->flags & AVFMT_NOFILE) {
1768 file_size = url_fsize(&ic->pb);
1772 ic->file_size = file_size;
1774 if ((!strcmp(ic->iformat->name, "mpeg") ||
1775 !strcmp(ic->iformat->name, "mpegts")) &&
1776 file_size && !ic->pb.is_streamed) {
1777 /* get accurate estimate from the PTSes */
1778 av_estimate_timings_from_pts(ic);
1779 } else if (av_has_timings(ic)) {
1780 /* at least one components has timings - we use them for all
1782 fill_all_stream_timings(ic);
1784 /* less precise: use bit rate info */
1785 av_estimate_timings_from_bit_rate(ic);
1787 av_update_stream_timings(ic);
1793 for(i = 0;i < ic->nb_streams; i++) {
1794 st = ic->streams[i];
1795 printf("%d: start_time: %0.3f duration: %0.3f\n",
1796 i, (double)st->start_time / AV_TIME_BASE,
1797 (double)st->duration / AV_TIME_BASE);
1799 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1800 (double)ic->start_time / AV_TIME_BASE,
1801 (double)ic->duration / AV_TIME_BASE,
1802 ic->bit_rate / 1000);
1807 static int has_codec_parameters(AVCodecContext *enc)
1810 switch(enc->codec_type) {
1811 case CODEC_TYPE_AUDIO:
1812 val = enc->sample_rate;
1814 case CODEC_TYPE_VIDEO:
1815 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1824 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1828 int got_picture, ret=0;
1831 if(!st->codec->codec){
1832 codec = avcodec_find_decoder(st->codec->codec_id);
1835 ret = avcodec_open(st->codec, codec);
1840 if(!has_codec_parameters(st->codec)){
1841 switch(st->codec->codec_type) {
1842 case CODEC_TYPE_VIDEO:
1843 ret = avcodec_decode_video(st->codec, &picture,
1844 &got_picture, (uint8_t *)data, size);
1846 case CODEC_TYPE_AUDIO:
1847 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1850 ret = avcodec_decode_audio(st->codec, samples,
1851 &got_picture, (uint8_t *)data, size);
1862 /* absolute maximum size we read until we abort */
1863 #define MAX_READ_SIZE 5000000
1865 /* maximum duration until we stop analysing the stream */
1866 #define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 3.0))
1869 * Read the beginning of a media file to get stream information. This
1870 * is useful for file formats with no headers such as MPEG. This
1871 * function also compute the real frame rate in case of mpeg2 repeat
1874 * @param ic media file handle
1875 * @return >=0 if OK. AVERROR_xxx if error.
1876 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
1878 int av_find_stream_info(AVFormatContext *ic)
1880 int i, count, ret, read_size, j;
1882 AVPacket pkt1, *pkt;
1883 AVPacketList *pktl=NULL, **ppktl;
1884 int64_t last_dts[MAX_STREAMS];
1885 int64_t duration_sum[MAX_STREAMS];
1886 int duration_count[MAX_STREAMS]={0};
1888 for(i=0;i<ic->nb_streams;i++) {
1889 st = ic->streams[i];
1890 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1891 /* if(!st->time_base.num)
1893 if(!st->codec->time_base.num)
1894 st->codec->time_base= st->time_base;
1896 //only for the split stuff
1898 st->parser = av_parser_init(st->codec->codec_id);
1899 if(st->need_parsing == 2 && st->parser){
1900 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1905 for(i=0;i<MAX_STREAMS;i++){
1906 last_dts[i]= AV_NOPTS_VALUE;
1907 duration_sum[i]= INT64_MAX;
1912 ppktl = &ic->packet_buffer;
1914 /* check if one codec still needs to be handled */
1915 for(i=0;i<ic->nb_streams;i++) {
1916 st = ic->streams[i];
1917 if (!has_codec_parameters(st->codec))
1919 /* variable fps and no guess at the real fps */
1920 if( st->codec->time_base.den >= 101LL*st->codec->time_base.num
1921 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1923 if(st->parser && st->parser->parser->split && !st->codec->extradata)
1926 if (i == ic->nb_streams) {
1927 /* NOTE: if the format has no header, then we need to read
1928 some packets to get most of the streams, so we cannot
1930 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1931 /* if we found the info for all the codecs, we can stop */
1936 /* we did not get all the codec info, but we read too much data */
1937 if (read_size >= MAX_READ_SIZE) {
1943 /* NOTE: a new stream can be added there if no header in file
1944 (AVFMTCTX_NOHEADER) */
1945 ret = av_read_frame_internal(ic, &pkt1);
1948 ret = -1; /* we could not have all the codec parameters before EOF */
1949 for(i=0;i<ic->nb_streams;i++) {
1950 st = ic->streams[i];
1951 if (!has_codec_parameters(st->codec)){
1953 avcodec_string(buf, sizeof(buf), st->codec, 0);
1954 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
1962 pktl = av_mallocz(sizeof(AVPacketList));
1964 ret = AVERROR_NOMEM;
1968 /* add the packet in the buffered packet list */
1970 ppktl = &pktl->next;
1975 /* duplicate the packet */
1976 if (av_dup_packet(pkt) < 0) {
1977 ret = AVERROR_NOMEM;
1981 read_size += pkt->size;
1983 st = ic->streams[pkt->stream_index];
1984 st->codec_info_duration += pkt->duration;
1985 if (pkt->duration != 0)
1986 st->codec_info_nb_frames++;
1989 int index= pkt->stream_index;
1990 int64_t last= last_dts[index];
1991 int64_t duration= pkt->dts - last;
1993 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
1994 if(duration*duration_count[index]*10/9 < duration_sum[index]){
1995 duration_sum[index]= duration;
1996 duration_count[index]=1;
1998 int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
1999 duration_sum[index] += duration;
2000 duration_count[index]+= factor;
2002 if(st->codec_info_nb_frames == 0 && 0)
2003 st->codec_info_duration += duration;
2005 last_dts[pkt->stream_index]= pkt->dts;
2007 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2008 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2010 st->codec->extradata_size= i;
2011 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2012 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2013 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2017 /* if still no information, we try to open the codec and to
2018 decompress the frame. We try to avoid that in most cases as
2019 it takes longer and uses more memory. For MPEG4, we need to
2020 decompress for Quicktime. */
2021 if (!has_codec_parameters(st->codec) /*&&
2022 (st->codec->codec_id == CODEC_ID_FLV1 ||
2023 st->codec->codec_id == CODEC_ID_H264 ||
2024 st->codec->codec_id == CODEC_ID_H263 ||
2025 st->codec->codec_id == CODEC_ID_H261 ||
2026 st->codec->codec_id == CODEC_ID_VORBIS ||
2027 st->codec->codec_id == CODEC_ID_MJPEG ||
2028 st->codec->codec_id == CODEC_ID_PNG ||
2029 st->codec->codec_id == CODEC_ID_PAM ||
2030 st->codec->codec_id == CODEC_ID_PGM ||
2031 st->codec->codec_id == CODEC_ID_PGMYUV ||
2032 st->codec->codec_id == CODEC_ID_PBM ||
2033 st->codec->codec_id == CODEC_ID_PPM ||
2034 st->codec->codec_id == CODEC_ID_SHORTEN ||
2035 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2036 try_decode_frame(st, pkt->data, pkt->size);
2038 if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2044 // close codecs which where opened in try_decode_frame()
2045 for(i=0;i<ic->nb_streams;i++) {
2046 st = ic->streams[i];
2047 if(st->codec->codec)
2048 avcodec_close(st->codec);
2050 for(i=0;i<ic->nb_streams;i++) {
2051 st = ic->streams[i];
2052 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2053 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2054 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2056 if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2057 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2058 int64_t num, den, error, best_error;
2060 num= st->time_base.den*duration_count[i];
2061 den= st->time_base.num*duration_sum[i];
2063 best_error= INT64_MAX;
2064 for(j=1; j<60*12; j++){
2065 error= ABS(1001*12*num - 1001*j*den);
2066 if(error < best_error){
2068 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2071 for(j=24; j<=30; j+=6){
2072 error= ABS(1001*12*num - 1000*12*j*den);
2073 if(error < best_error){
2075 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2080 /* set real frame rate info */
2081 /* compute the real frame rate for telecine */
2082 if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2083 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2084 st->codec->sub_id == 2) {
2085 if (st->codec_info_nb_frames >= 20) {
2086 float coded_frame_rate, est_frame_rate;
2087 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2088 (double)st->codec_info_duration ;
2089 coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2091 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2092 coded_frame_rate, est_frame_rate);
2094 /* if we detect that it could be a telecine, we
2095 signal it. It would be better to do it at a
2096 higher level as it can change in a film */
2097 if (coded_frame_rate >= 24.97 &&
2098 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2099 st->r_frame_rate = (AVRational){24000, 1001};
2103 /* if no real frame rate, use the codec one */
2104 if (!st->r_frame_rate.num){
2105 st->r_frame_rate.num = st->codec->time_base.den;
2106 st->r_frame_rate.den = st->codec->time_base.num;
2111 av_estimate_timings(ic);
2113 /* correct DTS for b frame streams with no timestamps */
2114 for(i=0;i<ic->nb_streams;i++) {
2115 st = ic->streams[i];
2116 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2118 ppktl = &ic->packet_buffer;
2120 if(ppkt1->stream_index != i)
2122 if(ppkt1->pkt->dts < 0)
2124 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2126 ppkt1->pkt->dts -= delta;
2131 st->cur_dts -= delta;
2139 /*******************************************************/
2142 * start playing a network based stream (e.g. RTSP stream) at the
2145 int av_read_play(AVFormatContext *s)
2147 if (!s->iformat->read_play)
2148 return AVERROR_NOTSUPP;
2149 return s->iformat->read_play(s);
2153 * Pause a network based stream (e.g. RTSP stream).
2155 * Use av_read_play() to resume it.
2157 int av_read_pause(AVFormatContext *s)
2159 if (!s->iformat->read_pause)
2160 return AVERROR_NOTSUPP;
2161 return s->iformat->read_pause(s);
2165 * Close a media file (but not its codecs).
2167 * @param s media file handle
2169 void av_close_input_file(AVFormatContext *s)
2171 int i, must_open_file;
2174 /* free previous packet */
2175 if (s->cur_st && s->cur_st->parser)
2176 av_free_packet(&s->cur_pkt);
2178 if (s->iformat->read_close)
2179 s->iformat->read_close(s);
2180 for(i=0;i<s->nb_streams;i++) {
2181 /* free all data in a stream component */
2184 av_parser_close(st->parser);
2186 av_free(st->index_entries);
2187 av_free(st->codec->extradata);
2191 flush_packet_queue(s);
2193 if (s->iformat->flags & AVFMT_NOFILE) {
2196 if (must_open_file) {
2199 av_freep(&s->priv_data);
2204 * Add a new stream to a media file.
2206 * Can only be called in the read_header() function. If the flag
2207 * AVFMTCTX_NOHEADER is in the format context, then new streams
2208 * can be added in read_packet too.
2210 * @param s media file handle
2211 * @param id file format dependent stream id
2213 AVStream *av_new_stream(AVFormatContext *s, int id)
2217 if (s->nb_streams >= MAX_STREAMS)
2220 st = av_mallocz(sizeof(AVStream));
2224 st->codec= avcodec_alloc_context();
2226 /* no default bitrate if decoding */
2227 st->codec->bit_rate = 0;
2229 st->index = s->nb_streams;
2231 st->start_time = AV_NOPTS_VALUE;
2232 st->duration = AV_NOPTS_VALUE;
2233 st->cur_dts = AV_NOPTS_VALUE;
2235 /* default pts settings is MPEG like */
2236 av_set_pts_info(st, 33, 1, 90000);
2237 st->last_IP_pts = AV_NOPTS_VALUE;
2239 s->streams[s->nb_streams++] = st;
2243 /************************************************************/
2244 /* output media file */
2246 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2250 if (s->oformat->priv_data_size > 0) {
2251 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2253 return AVERROR_NOMEM;
2255 s->priv_data = NULL;
2257 if (s->oformat->set_parameters) {
2258 ret = s->oformat->set_parameters(s, ap);
2266 * allocate the stream private data and write the stream header to an
2269 * @param s media file handle
2270 * @return 0 if OK. AVERROR_xxx if error.
2272 int av_write_header(AVFormatContext *s)
2277 // some sanity checks
2278 for(i=0;i<s->nb_streams;i++) {
2281 switch (st->codec->codec_type) {
2282 case CODEC_TYPE_AUDIO:
2283 if(st->codec->sample_rate<=0){
2284 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2288 case CODEC_TYPE_VIDEO:
2289 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2290 av_log(s, AV_LOG_ERROR, "time base not set\n");
2293 if(st->codec->width<=0 || st->codec->height<=0){
2294 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2301 if(s->oformat->write_header){
2302 ret = s->oformat->write_header(s);
2307 /* init PTS generation */
2308 for(i=0;i<s->nb_streams;i++) {
2309 int64_t den = AV_NOPTS_VALUE;
2312 switch (st->codec->codec_type) {
2313 case CODEC_TYPE_AUDIO:
2314 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2316 case CODEC_TYPE_VIDEO:
2317 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2322 if (den != AV_NOPTS_VALUE) {
2324 return AVERROR_INVALIDDATA;
2325 av_frac_init(&st->pts, 0, 0, den);
2331 //FIXME merge with compute_pkt_fields
2332 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2333 int b_frames = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames);
2334 int num, den, frame_size;
2336 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, b_frames, pkt->size, pkt->stream_index);
2338 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2341 /* duration field */
2342 if (pkt->duration == 0) {
2343 compute_frame_duration(&num, &den, st, NULL, pkt);
2345 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2349 //XXX/FIXME this is a temporary hack until all encoders output pts
2350 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
2352 // pkt->pts= st->cur_dts;
2353 pkt->pts= st->pts.val;
2356 //calculate dts from pts
2357 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2359 if(st->last_IP_pts == AV_NOPTS_VALUE){
2360 st->last_IP_pts= -pkt->duration;
2362 if(st->last_IP_pts < pkt->pts){
2363 pkt->dts= st->last_IP_pts;
2364 st->last_IP_pts= pkt->pts;
2371 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2372 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2375 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2376 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2380 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2381 st->cur_dts= pkt->dts;
2382 st->pts.val= pkt->dts;
2385 switch (st->codec->codec_type) {
2386 case CODEC_TYPE_AUDIO:
2387 frame_size = get_audio_frame_size(st->codec, pkt->size);
2389 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2390 but it would be better if we had the real timestamps from the encoder */
2391 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2392 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2395 case CODEC_TYPE_VIDEO:
2396 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2404 static void truncate_ts(AVStream *st, AVPacket *pkt){
2405 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2408 // pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2410 pkt->pts &= pts_mask;
2411 pkt->dts &= pts_mask;
2415 * Write a packet to an output media file.
2417 * The packet shall contain one audio or video frame.
2419 * @param s media file handle
2420 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2421 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2423 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2427 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2428 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2431 truncate_ts(s->streams[pkt->stream_index], pkt);
2433 ret= s->oformat->write_packet(s, pkt);
2435 ret= url_ferror(&s->pb);
2440 * Interleave a packet per DTS in an output media file.
2442 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2443 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2445 * @param s media file handle
2446 * @param out the interleaved packet will be output here
2447 * @param in the input packet
2448 * @param flush 1 if no further packets are available as input and all
2449 * remaining packets should be output
2450 * @return 1 if a packet was output, 0 if no packet could be output,
2451 * < 0 if an error occured
2453 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2454 AVPacketList *pktl, **next_point, *this_pktl;
2456 int streams[MAX_STREAMS];
2459 AVStream *st= s->streams[ pkt->stream_index];
2461 // assert(pkt->destruct != av_destruct_packet); //FIXME
2463 this_pktl = av_mallocz(sizeof(AVPacketList));
2464 this_pktl->pkt= *pkt;
2465 if(pkt->destruct == av_destruct_packet)
2466 pkt->destruct= NULL; // non shared -> must keep original from being freed
2468 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2470 next_point = &s->packet_buffer;
2472 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2473 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2474 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2475 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2477 next_point= &(*next_point)->next;
2479 this_pktl->next= *next_point;
2480 *next_point= this_pktl;
2483 memset(streams, 0, sizeof(streams));
2484 pktl= s->packet_buffer;
2486 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2487 if(streams[ pktl->pkt.stream_index ] == 0)
2489 streams[ pktl->pkt.stream_index ]++;
2493 if(s->nb_streams == stream_count || (flush && stream_count)){
2494 pktl= s->packet_buffer;
2497 s->packet_buffer= pktl->next;
2501 av_init_packet(out);
2507 * Interleaves a AVPacket correctly so it can be muxed.
2508 * @param out the interleaved packet will be output here
2509 * @param in the input packet
2510 * @param flush 1 if no further packets are available as input and all
2511 * remaining packets should be output
2512 * @return 1 if a packet was output, 0 if no packet could be output,
2513 * < 0 if an error occured
2515 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2516 if(s->oformat->interleave_packet)
2517 return s->oformat->interleave_packet(s, out, in, flush);
2519 return av_interleave_packet_per_dts(s, out, in, flush);
2523 * Writes a packet to an output media file ensuring correct interleaving.
2525 * The packet must contain one audio or video frame.
2526 * If the packets are already correctly interleaved the application should
2527 * call av_write_frame() instead as its slightly faster, its also important
2528 * to keep in mind that completly non interleaved input will need huge amounts
2529 * of memory to interleave with this, so its prefereable to interleave at the
2532 * @param s media file handle
2533 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2534 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2536 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2537 AVStream *st= s->streams[ pkt->stream_index];
2539 //FIXME/XXX/HACK drop zero sized packets
2540 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2543 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2544 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2547 if(pkt->dts == AV_NOPTS_VALUE)
2552 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2553 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2556 truncate_ts(s->streams[opkt.stream_index], &opkt);
2557 ret= s->oformat->write_packet(s, &opkt);
2559 av_free_packet(&opkt);
2564 if(url_ferror(&s->pb))
2565 return url_ferror(&s->pb);
2570 * @brief Write the stream trailer to an output media file and
2571 * free the file private data.
2573 * @param s media file handle
2574 * @return 0 if OK. AVERROR_xxx if error.
2576 int av_write_trailer(AVFormatContext *s)
2582 ret= av_interleave_packet(s, &pkt, NULL, 1);
2583 if(ret<0) //FIXME cleanup needed for ret<0 ?
2588 truncate_ts(s->streams[pkt.stream_index], &pkt);
2589 ret= s->oformat->write_packet(s, &pkt);
2591 av_free_packet(&pkt);
2595 if(url_ferror(&s->pb))
2599 if(s->oformat->write_trailer)
2600 ret = s->oformat->write_trailer(s);
2603 ret=url_ferror(&s->pb);
2604 for(i=0;i<s->nb_streams;i++)
2605 av_freep(&s->streams[i]->priv_data);
2606 av_freep(&s->priv_data);
2610 /* "user interface" functions */
2612 void dump_format(AVFormatContext *ic,
2620 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2621 is_output ? "Output" : "Input",
2623 is_output ? ic->oformat->name : ic->iformat->name,
2624 is_output ? "to" : "from", url);
2626 av_log(NULL, AV_LOG_INFO, " Duration: ");
2627 if (ic->duration != AV_NOPTS_VALUE) {
2628 int hours, mins, secs, us;
2629 secs = ic->duration / AV_TIME_BASE;
2630 us = ic->duration % AV_TIME_BASE;
2635 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2636 (10 * us) / AV_TIME_BASE);
2638 av_log(NULL, AV_LOG_INFO, "N/A");
2640 if (ic->start_time != AV_NOPTS_VALUE) {
2642 av_log(NULL, AV_LOG_INFO, ", start: ");
2643 secs = ic->start_time / AV_TIME_BASE;
2644 us = ic->start_time % AV_TIME_BASE;
2645 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2646 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2648 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2650 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2652 av_log(NULL, AV_LOG_INFO, "N/A");
2654 av_log(NULL, AV_LOG_INFO, "\n");
2656 for(i=0;i<ic->nb_streams;i++) {
2657 AVStream *st = ic->streams[i];
2658 int g= ff_gcd(st->time_base.num, st->time_base.den);
2659 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2660 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2661 /* the pid is an important information, so we display it */
2662 /* XXX: add a generic system */
2664 flags = ic->oformat->flags;
2666 flags = ic->iformat->flags;
2667 if (flags & AVFMT_SHOW_IDS) {
2668 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2670 if (strlen(st->language) > 0) {
2671 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2673 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2674 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2675 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2676 if(st->r_frame_rate.den && st->r_frame_rate.num)
2677 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2678 /* else if(st->time_base.den && st->time_base.num)
2679 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2681 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2683 av_log(NULL, AV_LOG_INFO, "\n");
2690 int frame_rate, frame_rate_base;
2693 static AbvEntry frame_abvs[] = {
2694 { "ntsc", 720, 480, 30000, 1001 },
2695 { "pal", 720, 576, 25, 1 },
2696 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2697 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
2698 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2699 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
2700 { "film", 352, 240, 24, 1 },
2701 { "ntsc-film", 352, 240, 24000, 1001 },
2702 { "sqcif", 128, 96, 0, 0 },
2703 { "qcif", 176, 144, 0, 0 },
2704 { "cif", 352, 288, 0, 0 },
2705 { "4cif", 704, 576, 0, 0 },
2709 * parses width and height out of string str.
2711 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2714 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2716 int frame_width = 0, frame_height = 0;
2719 if (!strcmp(frame_abvs[i].abv, str)) {
2720 frame_width = frame_abvs[i].width;
2721 frame_height = frame_abvs[i].height;
2727 frame_width = strtol(p, (char **)&p, 10);
2730 frame_height = strtol(p, (char **)&p, 10);
2732 if (frame_width <= 0 || frame_height <= 0)
2734 *width_ptr = frame_width;
2735 *height_ptr = frame_height;
2740 * Converts frame rate from string to a fraction.
2742 * First we try to get an exact integer or fractional frame rate.
2743 * If this fails we convert the frame rate to a double and return
2744 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2746 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2751 /* First, we check our abbreviation table */
2752 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2753 if (!strcmp(frame_abvs[i].abv, arg)) {
2754 *frame_rate = frame_abvs[i].frame_rate;
2755 *frame_rate_base = frame_abvs[i].frame_rate_base;
2759 /* Then, we try to parse it as fraction */
2760 cp = strchr(arg, '/');
2762 cp = strchr(arg, ':');
2765 *frame_rate = strtol(arg, &cpp, 10);
2766 if (cpp != arg || cpp == cp)
2767 *frame_rate_base = strtol(cp+1, &cpp, 10);
2772 /* Finally we give up and parse it as double */
2773 AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2774 *frame_rate_base = time_base.den;
2775 *frame_rate = time_base.num;
2777 if (!*frame_rate || !*frame_rate_base)
2784 * Converts date string to number of seconds since Jan 1st, 1970.
2788 * - If not a duration:
2789 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2790 * Time is localtime unless Z is suffixed to the end. In this case GMT
2791 * Return the date in micro seconds since 1970
2794 * HH[:MM[:SS[.m...]]]
2798 #ifndef CONFIG_WINCE
2799 int64_t parse_date(const char *datestr, int duration)
2805 static const char *date_fmt[] = {
2809 static const char *time_fmt[] = {
2819 time_t now = time(0);
2821 len = strlen(datestr);
2823 lastch = datestr[len - 1];
2826 is_utc = (lastch == 'z' || lastch == 'Z');
2828 memset(&dt, 0, sizeof(dt));
2833 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2834 q = small_strptime(p, date_fmt[i], &dt);
2844 dt = *localtime(&now);
2846 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2851 if (*p == 'T' || *p == 't' || *p == ' ')
2854 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2855 q = small_strptime(p, time_fmt[i], &dt);
2865 q = small_strptime(p, time_fmt[0], &dt);
2867 dt.tm_sec = strtol(p, (char **)&q, 10);
2873 /* Now we have all the fields that we can get */
2878 return now * int64_t_C(1000000);
2882 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2884 dt.tm_isdst = -1; /* unknown */
2897 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2900 val += n * (*q - '0');
2904 return negative ? -t : t;
2906 #endif /* CONFIG_WINCE */
2909 * Attempts to find a specific tag in a URL.
2911 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2912 * Return 1 if found.
2914 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2924 while (*p != '\0' && *p != '=' && *p != '&') {
2925 if ((q - tag) < sizeof(tag) - 1)
2933 while (*p != '&' && *p != '\0') {
2934 if ((q - arg) < arg_size - 1) {
2944 if (!strcmp(tag, tag1))
2954 * Returns in 'buf' the path with '%d' replaced by number.
2956 * Also handles the '%0nd' format where 'n' is the total number
2957 * of digits and '%%'. Return 0 if OK, and -1 if format error.
2959 int get_frame_filename(char *buf, int buf_size,
2960 const char *path, int number)
2963 char *q, buf1[20], c;
2964 int nd, len, percentd_found;
2976 while (isdigit(*p)) {
2977 nd = nd * 10 + *p++ - '0';
2980 } while (isdigit(c));
2989 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2991 if ((q - buf + len) > buf_size - 1)
2993 memcpy(q, buf1, len);
3001 if ((q - buf) < buf_size - 1)
3005 if (!percentd_found)
3015 * Print nice hexa dump of a buffer
3016 * @param f stream for output
3018 * @param size buffer size
3020 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3024 for(i=0;i<size;i+=16) {
3028 fprintf(f, "%08x ", i);
3031 fprintf(f, " %02x", buf[i+j]);
3036 for(j=0;j<len;j++) {
3038 if (c < ' ' || c > '~')
3040 fprintf(f, "%c", c);
3047 * Print on 'f' a nice dump of a packet
3048 * @param f stream for output
3049 * @param pkt packet to dump
3050 * @param dump_payload true if the payload must be displayed too
3052 //FIXME needs to know the time_base
3053 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3055 fprintf(f, "stream #%d:\n", pkt->stream_index);
3056 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3057 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3058 /* DTS is _always_ valid after av_read_frame() */
3059 fprintf(f, " dts=");
3060 if (pkt->dts == AV_NOPTS_VALUE)
3063 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3064 /* PTS may be not known if B frames are present */
3065 fprintf(f, " pts=");
3066 if (pkt->pts == AV_NOPTS_VALUE)
3069 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3071 fprintf(f, " size=%d\n", pkt->size);
3073 av_hex_dump(f, pkt->data, pkt->size);
3076 void url_split(char *proto, int proto_size,
3077 char *authorization, int authorization_size,
3078 char *hostname, int hostname_size,
3080 char *path, int path_size,
3091 while (*p != ':' && *p != '\0') {
3092 if ((q - proto) < proto_size - 1)
3098 if (authorization_size > 0)
3099 authorization[0] = '\0';
3103 if (hostname_size > 0)
3107 char *at,*slash; // PETR: position of '@' character and '/' character
3114 at = strchr(p,'@'); // PETR: get the position of '@'
3115 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
3116 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3118 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
3120 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3121 if (*p == '@') { // PETR: passed '@'
3122 if (authorization_size > 0)
3126 } else if (!at) { // PETR: hostname
3127 if ((q - hostname) < hostname_size - 1)
3130 if ((q - authorization) < authorization_size - 1)
3135 if (hostname_size > 0)
3139 port = strtoul(p, (char **)&p, 10);
3144 pstrcpy(path, path_size, p);
3148 * Set the pts for a given stream.
3151 * @param pts_wrap_bits number of bits effectively used by the pts
3152 * (used for wrap control, 33 is the value for MPEG)
3153 * @param pts_num numerator to convert to seconds (MPEG: 1)
3154 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3156 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3157 int pts_num, int pts_den)
3159 s->pts_wrap_bits = pts_wrap_bits;
3160 s->time_base.num = pts_num;
3161 s->time_base.den = pts_den;
3164 /* fraction handling */
3167 * f = val + (num / den) + 0.5.
3169 * 'num' is normalized so that it is such as 0 <= num < den.
3171 * @param f fractional number
3172 * @param val integer value
3173 * @param num must be >= 0
3174 * @param den must be >= 1
3176 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3189 * Set f to (val + 0.5).
3191 static void av_frac_set(AVFrac *f, int64_t val)
3194 f->num = f->den >> 1;
3198 * Fractionnal addition to f: f = f + (incr / f->den).
3200 * @param f fractional number
3201 * @param incr increment, can be positive or negative
3203 static void av_frac_add(AVFrac *f, int64_t incr)
3207 num = f->num + incr;
3210 f->val += num / den;
3216 } else if (num >= den) {
3217 f->val += num / den;
3224 * register a new image format
3225 * @param img_fmt Image format descriptor
3227 void av_register_image_format(AVImageFormat *img_fmt)
3231 p = &first_image_format;
3232 while (*p != NULL) p = &(*p)->next;
3234 img_fmt->next = NULL;
3238 * Guesses image format based on data in the image.
3240 AVImageFormat *av_probe_image_format(AVProbeData *pd)
3242 AVImageFormat *fmt1, *fmt;
3243 int score, score_max;
3247 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3248 if (fmt1->img_probe) {
3249 score = fmt1->img_probe(pd);
3250 if (score > score_max) {
3260 * Guesses image format based on file name extensions.
3262 AVImageFormat *guess_image_format(const char *filename)
3264 AVImageFormat *fmt1;
3266 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3267 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3274 * Read an image from a stream.
3275 * @param gb byte stream containing the image
3276 * @param fmt image format, NULL if probing is required
3278 int av_read_image(ByteIOContext *pb, const char *filename,
3280 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3282 uint8_t buf[PROBE_BUF_MIN];
3283 AVProbeData probe_data, *pd = &probe_data;
3288 pd->filename = filename;
3290 pos = url_ftell(pb);
3291 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
3292 url_fseek(pb, pos, SEEK_SET);
3293 fmt = av_probe_image_format(pd);
3296 return AVERROR_NOFMT;
3297 ret = fmt->img_read(pb, alloc_cb, opaque);
3302 * Write an image to a stream.
3303 * @param pb byte stream for the image output
3304 * @param fmt image format
3305 * @param img image data and informations
3307 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3309 return fmt->img_write(pb, img);