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 av_filename_number_test(filename) &&
97 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
98 return guess_format("image2", NULL, NULL);
101 if (!short_name && filename &&
102 av_filename_number_test(filename) &&
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);
407 * Allocate the payload of a packet and intialized its fields to default values.
409 * @param filename possible numbered sequence string
410 * @return 1 if a valid numbered sequence string, 0 otherwise.
412 int av_filename_number_test(const char *filename)
415 return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
421 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
423 AVInputFormat *fmt1, *fmt;
424 int score, score_max;
428 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
429 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
432 if (fmt1->read_probe) {
433 score = fmt1->read_probe(pd);
434 } else if (fmt1->extensions) {
435 if (match_ext(pd->filename, fmt1->extensions)) {
439 if (score > score_max) {
447 /************************************************************/
448 /* input media file */
451 * Open a media file from an IO stream. 'fmt' must be specified.
453 static const char* format_to_name(void* ptr)
455 AVFormatContext* fc = (AVFormatContext*) ptr;
456 if(fc->iformat) return fc->iformat->name;
457 else if(fc->oformat) return fc->oformat->name;
461 #define OFFSET(x) (int)&((AVFormatContext*)0)->x
462 #define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
463 //these names are too long to be readable
464 #define E AV_OPT_FLAG_ENCODING_PARAM
465 #define D AV_OPT_FLAG_DECODING_PARAM
467 static const AVOption options[]={
468 {"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, DEFAULT, 32, INT_MAX, D},
469 {"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D, "fflags"},
470 {"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
471 {"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
472 {"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 1, INT_MAX, E},
473 {"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
481 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
483 #if LIBAVCODEC_VERSION_INT > ((52<<16)+(0<<8)+0)
486 void avformat_get_context_defaults(AVFormatContext *s){
487 memset(s, 0, sizeof(AVFormatContext));
489 /* from mpegts.c: 1.0 second at 24Mbit/s */
493 AVFormatContext *av_alloc_format_context(void)
496 ic = av_mallocz(sizeof(AVFormatContext));
498 avformat_get_context_defaults(ic);
499 ic->av_class = &av_format_context_class;
504 * Allocates all the structures needed to read an input stream.
505 * This does not open the needed codecs for decoding the stream[s].
507 int av_open_input_stream(AVFormatContext **ic_ptr,
508 ByteIOContext *pb, const char *filename,
509 AVInputFormat *fmt, AVFormatParameters *ap)
513 AVFormatParameters default_ap;
517 memset(ap, 0, sizeof(default_ap));
520 if(!ap->prealloced_context)
521 ic = av_alloc_format_context();
531 ic->duration = AV_NOPTS_VALUE;
532 ic->start_time = AV_NOPTS_VALUE;
533 pstrcpy(ic->filename, sizeof(ic->filename), filename);
535 /* allocate private data */
536 if (fmt->priv_data_size > 0) {
537 ic->priv_data = av_mallocz(fmt->priv_data_size);
538 if (!ic->priv_data) {
543 ic->priv_data = NULL;
546 err = ic->iformat->read_header(ic, ap);
551 ic->data_offset = url_ftell(&ic->pb);
557 av_freep(&ic->priv_data);
564 /** Size of probe buffer, for guessing file type from file contents. */
565 #define PROBE_BUF_MIN 2048
566 #define PROBE_BUF_MAX (1<<20)
569 * Open a media file as input. The codec are not opened. Only the file
570 * header (if present) is read.
572 * @param ic_ptr the opened media file handle is put here
573 * @param filename filename to open.
574 * @param fmt if non NULL, force the file format to use
575 * @param buf_size optional buffer size (zero if default is OK)
576 * @param ap additionnal parameters needed when opening the file (NULL if default)
577 * @return 0 if OK. AVERROR_xxx otherwise.
579 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
582 AVFormatParameters *ap)
584 int err, must_open_file, file_opened, probe_size;
585 AVProbeData probe_data, *pd = &probe_data;
586 ByteIOContext pb1, *pb = &pb1;
591 pd->filename = filename;
596 /* guess format if no file can be opened */
597 fmt = av_probe_input_format(pd, 0);
600 /* do not open file if the format does not need it. XXX: specific
601 hack needed to handle RTSP/TCP */
603 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
605 pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
608 if (!fmt || must_open_file) {
609 /* if no file needed do not try to open one */
610 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
616 url_setbufsize(pb, buf_size);
619 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
620 /* read probe data */
621 pd->buf= av_realloc(pd->buf, probe_size);
622 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
623 if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
625 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
631 /* guess file format */
632 fmt = av_probe_input_format(pd, 1);
637 /* if still no format found, error */
643 /* XXX: suppress this hack for redirectors */
644 #ifdef CONFIG_NETWORK
645 if (fmt == &redir_demuxer) {
646 err = redir_open(ic_ptr, pb);
652 /* check filename in case of an image number is expected */
653 if (fmt->flags & AVFMT_NEEDNUMBER) {
654 if (!av_filename_number_test(filename)) {
655 err = AVERROR_NUMEXPECTED;
659 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
672 /*******************************************************/
675 * Read a transport packet from a media file.
677 * This function is absolete and should never be used.
678 * Use av_read_frame() instead.
680 * @param s media file handle
681 * @param pkt is filled
682 * @return 0 if OK. AVERROR_xxx if error.
684 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
686 return s->iformat->read_packet(s, pkt);
689 /**********************************************************/
692 * Get the number of samples of an audio frame. Return (-1) if error.
694 static int get_audio_frame_size(AVCodecContext *enc, int size)
698 if (enc->frame_size <= 1) {
699 int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
701 if (bits_per_sample) {
702 if (enc->channels == 0)
704 frame_size = (size << 3) / (bits_per_sample * enc->channels);
706 /* used for example by ADPCM codecs */
707 if (enc->bit_rate == 0)
709 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
712 frame_size = enc->frame_size;
719 * Return the frame duration in seconds, return 0 if not available.
721 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
722 AVCodecParserContext *pc, AVPacket *pkt)
728 switch(st->codec->codec_type) {
729 case CODEC_TYPE_VIDEO:
730 if(st->time_base.num*1000LL > st->time_base.den){
731 *pnum = st->time_base.num;
732 *pden = st->time_base.den;
733 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
734 *pnum = st->codec->time_base.num;
735 *pden = st->codec->time_base.den;
736 if (pc && pc->repeat_pict) {
738 *pnum = (*pnum) * (2 + pc->repeat_pict);
742 case CODEC_TYPE_AUDIO:
743 frame_size = get_audio_frame_size(st->codec, pkt->size);
747 *pden = st->codec->sample_rate;
754 static int is_intra_only(AVCodecContext *enc){
755 if(enc->codec_type == CODEC_TYPE_AUDIO){
757 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
758 switch(enc->codec_id){
760 case CODEC_ID_MJPEGB:
762 case CODEC_ID_RAWVIDEO:
763 case CODEC_ID_DVVIDEO:
764 case CODEC_ID_HUFFYUV:
765 case CODEC_ID_FFVHUFF:
776 static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
777 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
778 int64_t delta= last_ts - mask/2;
779 return ((lsb - delta)&mask) + delta;
782 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
783 AVCodecParserContext *pc, AVPacket *pkt)
785 int num, den, presentation_delayed;
786 /* handle wrapping */
787 if(st->cur_dts != AV_NOPTS_VALUE){
788 if(pkt->pts != AV_NOPTS_VALUE)
789 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
790 if(pkt->dts != AV_NOPTS_VALUE)
791 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
794 if (pkt->duration == 0) {
795 compute_frame_duration(&num, &den, st, pc, pkt);
797 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
801 if(is_intra_only(st->codec))
802 pkt->flags |= PKT_FLAG_KEY;
804 /* do we have a video B frame ? */
805 presentation_delayed = 0;
806 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
807 /* XXX: need has_b_frame, but cannot get it if the codec is
809 if (( st->codec->codec_id == CODEC_ID_H264
810 || st->codec->has_b_frames) &&
811 pc && pc->pict_type != FF_B_TYPE)
812 presentation_delayed = 1;
813 /* this may be redundant, but it shouldnt hurt */
814 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
815 presentation_delayed = 1;
818 if(st->cur_dts == AV_NOPTS_VALUE){
819 if(presentation_delayed) st->cur_dts = -pkt->duration;
820 else st->cur_dts = 0;
823 // 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);
824 /* interpolate PTS and DTS if they are not present */
825 if (presentation_delayed) {
826 /* DTS = decompression time stamp */
827 /* PTS = presentation time stamp */
828 if (pkt->dts == AV_NOPTS_VALUE) {
829 /* if we know the last pts, use it */
830 if(st->last_IP_pts != AV_NOPTS_VALUE)
831 st->cur_dts = pkt->dts = st->last_IP_pts;
833 pkt->dts = st->cur_dts;
835 st->cur_dts = pkt->dts;
837 /* this is tricky: the dts must be incremented by the duration
838 of the frame we are displaying, i.e. the last I or P frame */
839 if (st->last_IP_duration == 0)
840 st->cur_dts += pkt->duration;
842 st->cur_dts += st->last_IP_duration;
843 st->last_IP_duration = pkt->duration;
844 st->last_IP_pts= pkt->pts;
845 /* cannot compute PTS if not present (we can compute it only
846 by knowing the futur */
847 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
848 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
849 int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
850 int64_t new_diff= ABS(st->cur_dts - pkt->pts);
851 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
852 pkt->pts += pkt->duration;
853 // 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);
857 /* presentation is not delayed : PTS and DTS are the same */
858 if (pkt->pts == AV_NOPTS_VALUE) {
859 if (pkt->dts == AV_NOPTS_VALUE) {
860 pkt->pts = st->cur_dts;
861 pkt->dts = st->cur_dts;
864 st->cur_dts = pkt->dts;
868 st->cur_dts = pkt->pts;
871 st->cur_dts += pkt->duration;
873 // 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);
878 /* key frame computation */
879 switch(st->codec->codec_type) {
880 case CODEC_TYPE_VIDEO:
881 if (pc->pict_type == FF_I_TYPE)
882 pkt->flags |= PKT_FLAG_KEY;
884 case CODEC_TYPE_AUDIO:
885 pkt->flags |= PKT_FLAG_KEY;
893 void av_destruct_packet_nofree(AVPacket *pkt)
895 pkt->data = NULL; pkt->size = 0;
898 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
904 /* select current input stream component */
907 if (!st->need_parsing || !st->parser) {
908 /* no parsing needed: we just output the packet as is */
909 /* raw data support */
911 compute_pkt_fields(s, st, NULL, pkt);
914 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
915 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
916 s->cur_ptr, s->cur_len,
917 s->cur_pkt.pts, s->cur_pkt.dts);
918 s->cur_pkt.pts = AV_NOPTS_VALUE;
919 s->cur_pkt.dts = AV_NOPTS_VALUE;
920 /* increment read pointer */
924 /* return packet if any */
928 pkt->stream_index = st->index;
929 pkt->pts = st->parser->pts;
930 pkt->dts = st->parser->dts;
931 pkt->destruct = av_destruct_packet_nofree;
932 compute_pkt_fields(s, st, st->parser, pkt);
937 av_free_packet(&s->cur_pkt);
941 /* read next packet */
942 ret = av_read_packet(s, &s->cur_pkt);
946 /* return the last frames, if any */
947 for(i = 0; i < s->nb_streams; i++) {
949 if (st->parser && st->need_parsing) {
950 av_parser_parse(st->parser, st->codec,
951 &pkt->data, &pkt->size,
953 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
958 /* no more packets: really terminates parsing */
962 st = s->streams[s->cur_pkt.stream_index];
963 if(st->codec->debug & FF_DEBUG_PTS)
964 av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%lld, dts=%lld, size=%d\n",
965 s->cur_pkt.stream_index,
971 s->cur_ptr = s->cur_pkt.data;
972 s->cur_len = s->cur_pkt.size;
973 if (st->need_parsing && !st->parser) {
974 st->parser = av_parser_init(st->codec->codec_id);
976 /* no parser available : just output the raw packets */
977 st->need_parsing = 0;
978 }else if(st->need_parsing == 2){
979 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
984 if(st->codec->debug & FF_DEBUG_PTS)
985 av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%lld, dts=%lld, size=%d\n",
995 * Return the next frame of a stream.
997 * The returned packet is valid
998 * until the next av_read_frame() or until av_close_input_file() and
999 * must be freed with av_free_packet. For video, the packet contains
1000 * exactly one frame. For audio, it contains an integer number of
1001 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
1002 * data). If the audio frames have a variable size (e.g. MPEG audio),
1003 * then it contains one frame.
1005 * pkt->pts, pkt->dts and pkt->duration are always set to correct
1006 * values in AV_TIME_BASE unit (and guessed if the format cannot
1007 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
1008 * has B frames, so it is better to rely on pkt->dts if you do not
1009 * decompress the payload.
1011 * @return 0 if OK, < 0 if error or end of file.
1013 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1017 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1020 pktl = s->packet_buffer;
1022 AVPacket *next_pkt= &pktl->pkt;
1024 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1025 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1026 if( pktl->pkt.stream_index == next_pkt->stream_index
1027 && next_pkt->dts < pktl->pkt.dts
1028 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1029 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1030 next_pkt->pts= pktl->pkt.dts;
1034 pktl = s->packet_buffer;
1037 if( next_pkt->pts != AV_NOPTS_VALUE
1038 || next_pkt->dts == AV_NOPTS_VALUE
1040 /* read packet from packet buffer, if there is data */
1042 s->packet_buffer = pktl->next;
1048 AVPacketList **plast_pktl= &s->packet_buffer;
1049 int ret= av_read_frame_internal(s, pkt);
1051 if(pktl && ret != -EAGAIN){
1058 /* duplicate the packet */
1059 if (av_dup_packet(pkt) < 0)
1060 return AVERROR_NOMEM;
1062 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
1064 pktl = av_mallocz(sizeof(AVPacketList));
1066 return AVERROR_NOMEM;
1068 /* add the packet in the buffered packet list */
1072 assert(!s->packet_buffer);
1073 return av_read_frame_internal(s, pkt);
1078 /* XXX: suppress the packet queue */
1079 static void flush_packet_queue(AVFormatContext *s)
1084 pktl = s->packet_buffer;
1087 s->packet_buffer = pktl->next;
1088 av_free_packet(&pktl->pkt);
1093 /*******************************************************/
1096 int av_find_default_stream_index(AVFormatContext *s)
1101 if (s->nb_streams <= 0)
1103 for(i = 0; i < s->nb_streams; i++) {
1105 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1113 * Flush the frame reader.
1115 static void av_read_frame_flush(AVFormatContext *s)
1120 flush_packet_queue(s);
1122 /* free previous packet */
1124 if (s->cur_st->parser)
1125 av_free_packet(&s->cur_pkt);
1132 /* for each stream, reset read state */
1133 for(i = 0; i < s->nb_streams; i++) {
1137 av_parser_close(st->parser);
1140 st->last_IP_pts = AV_NOPTS_VALUE;
1141 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1146 * Updates cur_dts of all streams based on given timestamp and AVStream.
1148 * Stream ref_st unchanged, others set cur_dts in their native timebase
1149 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1150 * @param timestamp new dts expressed in time_base of param ref_st
1151 * @param ref_st reference stream giving time_base of param timestamp
1153 void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1156 for(i = 0; i < s->nb_streams; i++) {
1157 AVStream *st = s->streams[i];
1159 st->cur_dts = av_rescale(timestamp,
1160 st->time_base.den * (int64_t)ref_st->time_base.num,
1161 st->time_base.num * (int64_t)ref_st->time_base.den);
1166 * Add a index entry into a sorted list updateing if it is already there.
1168 * @param timestamp timestamp in the timebase of the given stream
1170 int av_add_index_entry(AVStream *st,
1171 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1173 AVIndexEntry *entries, *ie;
1176 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1179 entries = av_fast_realloc(st->index_entries,
1180 &st->index_entries_allocated_size,
1181 (st->nb_index_entries + 1) *
1182 sizeof(AVIndexEntry));
1186 st->index_entries= entries;
1188 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1191 index= st->nb_index_entries++;
1192 ie= &entries[index];
1193 assert(index==0 || ie[-1].timestamp < timestamp);
1195 ie= &entries[index];
1196 if(ie->timestamp != timestamp){
1197 if(ie->timestamp <= timestamp)
1199 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1200 st->nb_index_entries++;
1201 }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1202 distance= ie->min_distance;
1206 ie->timestamp = timestamp;
1207 ie->min_distance= distance;
1215 * build an index for raw streams using a parser.
1217 static void av_build_index_raw(AVFormatContext *s)
1219 AVPacket pkt1, *pkt = &pkt1;
1224 av_read_frame_flush(s);
1225 url_fseek(&s->pb, s->data_offset, SEEK_SET);
1228 ret = av_read_frame(s, pkt);
1231 if (pkt->stream_index == 0 && st->parser &&
1232 (pkt->flags & PKT_FLAG_KEY)) {
1233 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1234 0, 0, AVINDEX_KEYFRAME);
1236 av_free_packet(pkt);
1241 * Returns TRUE if we deal with a raw stream.
1243 * Raw codec data and parsing needed.
1245 static int is_raw_stream(AVFormatContext *s)
1249 if (s->nb_streams != 1)
1252 if (!st->need_parsing)
1258 * Gets the index for a specific timestamp.
1259 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1260 * the timestamp which is <= the requested one, if backward is 0
1261 * then it will be >=
1262 * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1263 * @return < 0 if no such timestamp could be found
1265 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1268 AVIndexEntry *entries= st->index_entries;
1269 int nb_entries= st->nb_index_entries;
1278 timestamp = entries[m].timestamp;
1279 if(timestamp >= wanted_timestamp)
1281 if(timestamp <= wanted_timestamp)
1284 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1286 if(!(flags & AVSEEK_FLAG_ANY)){
1287 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1288 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1300 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1301 * this isnt supposed to be called directly by a user application, but by demuxers
1302 * @param target_ts target timestamp in the time base of the given stream
1303 * @param stream_index stream number
1305 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1306 AVInputFormat *avif= s->iformat;
1307 int64_t pos_min, pos_max, pos, pos_limit;
1308 int64_t ts_min, ts_max, ts;
1309 int64_t start_pos, filesize;
1310 int index, no_change;
1313 if (stream_index < 0)
1317 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1321 ts_min= AV_NOPTS_VALUE;
1322 pos_limit= -1; //gcc falsely says it may be uninitalized
1324 st= s->streams[stream_index];
1325 if(st->index_entries){
1328 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()
1329 index= FFMAX(index, 0);
1330 e= &st->index_entries[index];
1332 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1334 ts_min= e->timestamp;
1336 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1343 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1344 assert(index < st->nb_index_entries);
1346 e= &st->index_entries[index];
1347 assert(e->timestamp >= target_ts);
1349 ts_max= e->timestamp;
1350 pos_limit= pos_max - e->min_distance;
1352 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1353 pos_max,pos_limit, ts_max);
1358 if(ts_min == AV_NOPTS_VALUE){
1359 pos_min = s->data_offset;
1360 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1361 if (ts_min == AV_NOPTS_VALUE)
1365 if(ts_max == AV_NOPTS_VALUE){
1367 filesize = url_fsize(&s->pb);
1368 pos_max = filesize - 1;
1371 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1373 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1374 if (ts_max == AV_NOPTS_VALUE)
1378 int64_t tmp_pos= pos_max + 1;
1379 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1380 if(tmp_ts == AV_NOPTS_VALUE)
1384 if(tmp_pos >= filesize)
1390 if(ts_min > ts_max){
1392 }else if(ts_min == ts_max){
1397 while (pos_min < pos_limit) {
1399 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1403 assert(pos_limit <= pos_max);
1406 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1407 // interpolate position (better than dichotomy)
1408 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1409 + pos_min - approximate_keyframe_distance;
1410 }else if(no_change==1){
1411 // bisection, if interpolation failed to change min or max pos last time
1412 pos = (pos_min + pos_limit)>>1;
1414 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1419 else if(pos > pos_limit)
1423 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1429 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);
1431 assert(ts != AV_NOPTS_VALUE);
1432 if (target_ts <= ts) {
1433 pos_limit = start_pos - 1;
1437 if (target_ts >= ts) {
1443 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1444 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1447 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1449 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1450 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1451 pos, ts_min, target_ts, ts_max);
1454 url_fseek(&s->pb, pos, SEEK_SET);
1456 av_update_cur_dts(s, st, ts);
1461 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1462 int64_t pos_min, pos_max;
1466 if (stream_index < 0)
1469 st= s->streams[stream_index];
1472 pos_min = s->data_offset;
1473 pos_max = url_fsize(&s->pb) - 1;
1475 if (pos < pos_min) pos= pos_min;
1476 else if(pos > pos_max) pos= pos_max;
1478 url_fseek(&s->pb, pos, SEEK_SET);
1481 av_update_cur_dts(s, st, ts);
1486 static int av_seek_frame_generic(AVFormatContext *s,
1487 int stream_index, int64_t timestamp, int flags)
1493 if (!s->index_built) {
1494 if (is_raw_stream(s)) {
1495 av_build_index_raw(s);
1502 st = s->streams[stream_index];
1503 index = av_index_search_timestamp(st, timestamp, flags);
1507 /* now we have found the index, we can seek */
1508 ie = &st->index_entries[index];
1509 av_read_frame_flush(s);
1510 url_fseek(&s->pb, ie->pos, SEEK_SET);
1512 av_update_cur_dts(s, st, ie->timestamp);
1518 * Seek to the key frame at timestamp.
1519 * 'timestamp' in 'stream_index'.
1520 * @param stream_index If stream_index is (-1), a default
1521 * stream is selected, and timestamp is automatically converted
1522 * from AV_TIME_BASE units to the stream specific time_base.
1523 * @param timestamp timestamp in AVStream.time_base units
1524 * or if there is no stream specified then in AV_TIME_BASE units
1525 * @param flags flags which select direction and seeking mode
1526 * @return >= 0 on success
1528 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1533 av_read_frame_flush(s);
1535 if(flags & AVSEEK_FLAG_BYTE)
1536 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1538 if(stream_index < 0){
1539 stream_index= av_find_default_stream_index(s);
1540 if(stream_index < 0)
1543 st= s->streams[stream_index];
1544 /* timestamp for default must be expressed in AV_TIME_BASE units */
1545 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1547 st= s->streams[stream_index];
1549 /* first, we try the format specific seek */
1550 if (s->iformat->read_seek)
1551 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1558 if(s->iformat->read_timestamp)
1559 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1561 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1564 /*******************************************************/
1567 * Returns TRUE if the stream has accurate timings in any stream.
1569 * @return TRUE if the stream has accurate timings for at least one component.
1571 static int av_has_timings(AVFormatContext *ic)
1576 for(i = 0;i < ic->nb_streams; i++) {
1577 st = ic->streams[i];
1578 if (st->start_time != AV_NOPTS_VALUE &&
1579 st->duration != AV_NOPTS_VALUE)
1586 * Estimate the stream timings from the one of each components.
1588 * Also computes the global bitrate if possible.
1590 static void av_update_stream_timings(AVFormatContext *ic)
1592 int64_t start_time, start_time1, end_time, end_time1;
1596 start_time = MAXINT64;
1597 end_time = MININT64;
1598 for(i = 0;i < ic->nb_streams; i++) {
1599 st = ic->streams[i];
1600 if (st->start_time != AV_NOPTS_VALUE) {
1601 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1602 if (start_time1 < start_time)
1603 start_time = start_time1;
1604 if (st->duration != AV_NOPTS_VALUE) {
1605 end_time1 = start_time1
1606 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1607 if (end_time1 > end_time)
1608 end_time = end_time1;
1612 if (start_time != MAXINT64) {
1613 ic->start_time = start_time;
1614 if (end_time != MININT64) {
1615 ic->duration = end_time - start_time;
1616 if (ic->file_size > 0) {
1617 /* compute the bit rate */
1618 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1619 (double)ic->duration;
1626 static void fill_all_stream_timings(AVFormatContext *ic)
1631 av_update_stream_timings(ic);
1632 for(i = 0;i < ic->nb_streams; i++) {
1633 st = ic->streams[i];
1634 if (st->start_time == AV_NOPTS_VALUE) {
1635 if(ic->start_time != AV_NOPTS_VALUE)
1636 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1637 if(ic->duration != AV_NOPTS_VALUE)
1638 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1643 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1645 int64_t filesize, duration;
1649 /* if bit_rate is already set, we believe it */
1650 if (ic->bit_rate == 0) {
1652 for(i=0;i<ic->nb_streams;i++) {
1653 st = ic->streams[i];
1654 bit_rate += st->codec->bit_rate;
1656 ic->bit_rate = bit_rate;
1659 /* if duration is already set, we believe it */
1660 if (ic->duration == AV_NOPTS_VALUE &&
1661 ic->bit_rate != 0 &&
1662 ic->file_size != 0) {
1663 filesize = ic->file_size;
1665 for(i = 0; i < ic->nb_streams; i++) {
1666 st = ic->streams[i];
1667 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1668 if (st->start_time == AV_NOPTS_VALUE ||
1669 st->duration == AV_NOPTS_VALUE) {
1671 st->duration = duration;
1678 #define DURATION_MAX_READ_SIZE 250000
1680 /* only usable for MPEG-PS streams */
1681 static void av_estimate_timings_from_pts(AVFormatContext *ic)
1683 AVPacket pkt1, *pkt = &pkt1;
1685 int read_size, i, ret;
1687 int64_t filesize, offset, duration;
1689 /* free previous packet */
1690 if (ic->cur_st && ic->cur_st->parser)
1691 av_free_packet(&ic->cur_pkt);
1694 /* flush packet queue */
1695 flush_packet_queue(ic);
1697 for(i=0;i<ic->nb_streams;i++) {
1698 st = ic->streams[i];
1700 av_parser_close(st->parser);
1705 /* we read the first packets to get the first PTS (not fully
1706 accurate, but it is enough now) */
1707 url_fseek(&ic->pb, 0, SEEK_SET);
1710 if (read_size >= DURATION_MAX_READ_SIZE)
1712 /* if all info is available, we can stop */
1713 for(i = 0;i < ic->nb_streams; i++) {
1714 st = ic->streams[i];
1715 if (st->start_time == AV_NOPTS_VALUE)
1718 if (i == ic->nb_streams)
1721 ret = av_read_packet(ic, pkt);
1724 read_size += pkt->size;
1725 st = ic->streams[pkt->stream_index];
1726 if (pkt->pts != AV_NOPTS_VALUE) {
1727 if (st->start_time == AV_NOPTS_VALUE)
1728 st->start_time = pkt->pts;
1730 av_free_packet(pkt);
1733 /* estimate the end time (duration) */
1734 /* XXX: may need to support wrapping */
1735 filesize = ic->file_size;
1736 offset = filesize - DURATION_MAX_READ_SIZE;
1740 url_fseek(&ic->pb, offset, SEEK_SET);
1743 if (read_size >= DURATION_MAX_READ_SIZE)
1745 /* if all info is available, we can stop */
1746 for(i = 0;i < ic->nb_streams; i++) {
1747 st = ic->streams[i];
1748 if (st->duration == AV_NOPTS_VALUE)
1751 if (i == ic->nb_streams)
1754 ret = av_read_packet(ic, pkt);
1757 read_size += pkt->size;
1758 st = ic->streams[pkt->stream_index];
1759 if (pkt->pts != AV_NOPTS_VALUE) {
1760 end_time = pkt->pts;
1761 duration = end_time - st->start_time;
1763 if (st->duration == AV_NOPTS_VALUE ||
1764 st->duration < duration)
1765 st->duration = duration;
1768 av_free_packet(pkt);
1771 fill_all_stream_timings(ic);
1773 url_fseek(&ic->pb, 0, SEEK_SET);
1776 static void av_estimate_timings(AVFormatContext *ic)
1780 /* get the file size, if possible */
1781 if (ic->iformat->flags & AVFMT_NOFILE) {
1784 file_size = url_fsize(&ic->pb);
1788 ic->file_size = file_size;
1790 if ((!strcmp(ic->iformat->name, "mpeg") ||
1791 !strcmp(ic->iformat->name, "mpegts")) &&
1792 file_size && !ic->pb.is_streamed) {
1793 /* get accurate estimate from the PTSes */
1794 av_estimate_timings_from_pts(ic);
1795 } else if (av_has_timings(ic)) {
1796 /* at least one components has timings - we use them for all
1798 fill_all_stream_timings(ic);
1800 /* less precise: use bit rate info */
1801 av_estimate_timings_from_bit_rate(ic);
1803 av_update_stream_timings(ic);
1809 for(i = 0;i < ic->nb_streams; i++) {
1810 st = ic->streams[i];
1811 printf("%d: start_time: %0.3f duration: %0.3f\n",
1812 i, (double)st->start_time / AV_TIME_BASE,
1813 (double)st->duration / AV_TIME_BASE);
1815 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1816 (double)ic->start_time / AV_TIME_BASE,
1817 (double)ic->duration / AV_TIME_BASE,
1818 ic->bit_rate / 1000);
1823 static int has_codec_parameters(AVCodecContext *enc)
1826 switch(enc->codec_type) {
1827 case CODEC_TYPE_AUDIO:
1828 val = enc->sample_rate;
1830 case CODEC_TYPE_VIDEO:
1831 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1840 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1844 int got_picture, ret=0;
1847 if(!st->codec->codec){
1848 codec = avcodec_find_decoder(st->codec->codec_id);
1851 ret = avcodec_open(st->codec, codec);
1856 if(!has_codec_parameters(st->codec)){
1857 switch(st->codec->codec_type) {
1858 case CODEC_TYPE_VIDEO:
1859 ret = avcodec_decode_video(st->codec, &picture,
1860 &got_picture, (uint8_t *)data, size);
1862 case CODEC_TYPE_AUDIO:
1863 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1866 ret = avcodec_decode_audio(st->codec, samples,
1867 &got_picture, (uint8_t *)data, size);
1878 /* absolute maximum size we read until we abort */
1879 #define MAX_READ_SIZE 5000000
1881 /* maximum duration until we stop analysing the stream */
1882 #define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 3.0))
1885 * Read the beginning of a media file to get stream information. This
1886 * is useful for file formats with no headers such as MPEG. This
1887 * function also compute the real frame rate in case of mpeg2 repeat
1890 * @param ic media file handle
1891 * @return >=0 if OK. AVERROR_xxx if error.
1892 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
1894 int av_find_stream_info(AVFormatContext *ic)
1896 int i, count, ret, read_size, j;
1898 AVPacket pkt1, *pkt;
1899 AVPacketList *pktl=NULL, **ppktl;
1900 int64_t last_dts[MAX_STREAMS];
1901 int64_t duration_sum[MAX_STREAMS];
1902 int duration_count[MAX_STREAMS]={0};
1904 for(i=0;i<ic->nb_streams;i++) {
1905 st = ic->streams[i];
1906 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1907 /* if(!st->time_base.num)
1909 if(!st->codec->time_base.num)
1910 st->codec->time_base= st->time_base;
1912 //only for the split stuff
1914 st->parser = av_parser_init(st->codec->codec_id);
1915 if(st->need_parsing == 2 && st->parser){
1916 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1921 for(i=0;i<MAX_STREAMS;i++){
1922 last_dts[i]= AV_NOPTS_VALUE;
1923 duration_sum[i]= INT64_MAX;
1928 ppktl = &ic->packet_buffer;
1930 /* check if one codec still needs to be handled */
1931 for(i=0;i<ic->nb_streams;i++) {
1932 st = ic->streams[i];
1933 if (!has_codec_parameters(st->codec))
1935 /* variable fps and no guess at the real fps */
1936 if( st->codec->time_base.den >= 101LL*st->codec->time_base.num
1937 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1939 if(st->parser && st->parser->parser->split && !st->codec->extradata)
1942 if (i == ic->nb_streams) {
1943 /* NOTE: if the format has no header, then we need to read
1944 some packets to get most of the streams, so we cannot
1946 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1947 /* if we found the info for all the codecs, we can stop */
1952 /* we did not get all the codec info, but we read too much data */
1953 if (read_size >= MAX_READ_SIZE) {
1959 /* NOTE: a new stream can be added there if no header in file
1960 (AVFMTCTX_NOHEADER) */
1961 ret = av_read_frame_internal(ic, &pkt1);
1964 ret = -1; /* we could not have all the codec parameters before EOF */
1965 for(i=0;i<ic->nb_streams;i++) {
1966 st = ic->streams[i];
1967 if (!has_codec_parameters(st->codec)){
1969 avcodec_string(buf, sizeof(buf), st->codec, 0);
1970 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
1978 pktl = av_mallocz(sizeof(AVPacketList));
1980 ret = AVERROR_NOMEM;
1984 /* add the packet in the buffered packet list */
1986 ppktl = &pktl->next;
1991 /* duplicate the packet */
1992 if (av_dup_packet(pkt) < 0) {
1993 ret = AVERROR_NOMEM;
1997 read_size += pkt->size;
1999 st = ic->streams[pkt->stream_index];
2000 st->codec_info_duration += pkt->duration;
2001 if (pkt->duration != 0)
2002 st->codec_info_nb_frames++;
2005 int index= pkt->stream_index;
2006 int64_t last= last_dts[index];
2007 int64_t duration= pkt->dts - last;
2009 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2010 if(duration*duration_count[index]*10/9 < duration_sum[index]){
2011 duration_sum[index]= duration;
2012 duration_count[index]=1;
2014 int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
2015 duration_sum[index] += duration;
2016 duration_count[index]+= factor;
2018 if(st->codec_info_nb_frames == 0 && 0)
2019 st->codec_info_duration += duration;
2021 last_dts[pkt->stream_index]= pkt->dts;
2023 if(st->parser && st->parser->parser->split && !st->codec->extradata){
2024 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2026 st->codec->extradata_size= i;
2027 st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2028 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2029 memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2033 /* if still no information, we try to open the codec and to
2034 decompress the frame. We try to avoid that in most cases as
2035 it takes longer and uses more memory. For MPEG4, we need to
2036 decompress for Quicktime. */
2037 if (!has_codec_parameters(st->codec) /*&&
2038 (st->codec->codec_id == CODEC_ID_FLV1 ||
2039 st->codec->codec_id == CODEC_ID_H264 ||
2040 st->codec->codec_id == CODEC_ID_H263 ||
2041 st->codec->codec_id == CODEC_ID_H261 ||
2042 st->codec->codec_id == CODEC_ID_VORBIS ||
2043 st->codec->codec_id == CODEC_ID_MJPEG ||
2044 st->codec->codec_id == CODEC_ID_PNG ||
2045 st->codec->codec_id == CODEC_ID_PAM ||
2046 st->codec->codec_id == CODEC_ID_PGM ||
2047 st->codec->codec_id == CODEC_ID_PGMYUV ||
2048 st->codec->codec_id == CODEC_ID_PBM ||
2049 st->codec->codec_id == CODEC_ID_PPM ||
2050 st->codec->codec_id == CODEC_ID_SHORTEN ||
2051 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2052 try_decode_frame(st, pkt->data, pkt->size);
2054 if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2060 // close codecs which where opened in try_decode_frame()
2061 for(i=0;i<ic->nb_streams;i++) {
2062 st = ic->streams[i];
2063 if(st->codec->codec)
2064 avcodec_close(st->codec);
2066 for(i=0;i<ic->nb_streams;i++) {
2067 st = ic->streams[i];
2068 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2069 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2070 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2072 if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2073 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2074 int64_t num, den, error, best_error;
2076 num= st->time_base.den*duration_count[i];
2077 den= st->time_base.num*duration_sum[i];
2079 best_error= INT64_MAX;
2080 for(j=1; j<60*12; j++){
2081 error= ABS(1001*12*num - 1001*j*den);
2082 if(error < best_error){
2084 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2087 for(j=24; j<=30; j+=6){
2088 error= ABS(1001*12*num - 1000*12*j*den);
2089 if(error < best_error){
2091 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2096 /* set real frame rate info */
2097 /* compute the real frame rate for telecine */
2098 if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2099 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2100 st->codec->sub_id == 2) {
2101 if (st->codec_info_nb_frames >= 20) {
2102 float coded_frame_rate, est_frame_rate;
2103 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2104 (double)st->codec_info_duration ;
2105 coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2107 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2108 coded_frame_rate, est_frame_rate);
2110 /* if we detect that it could be a telecine, we
2111 signal it. It would be better to do it at a
2112 higher level as it can change in a film */
2113 if (coded_frame_rate >= 24.97 &&
2114 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2115 st->r_frame_rate = (AVRational){24000, 1001};
2119 /* if no real frame rate, use the codec one */
2120 if (!st->r_frame_rate.num){
2121 st->r_frame_rate.num = st->codec->time_base.den;
2122 st->r_frame_rate.den = st->codec->time_base.num;
2127 av_estimate_timings(ic);
2129 /* correct DTS for b frame streams with no timestamps */
2130 for(i=0;i<ic->nb_streams;i++) {
2131 st = ic->streams[i];
2132 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2134 ppktl = &ic->packet_buffer;
2136 if(ppkt1->stream_index != i)
2138 if(ppkt1->pkt->dts < 0)
2140 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2142 ppkt1->pkt->dts -= delta;
2147 st->cur_dts -= delta;
2155 /*******************************************************/
2158 * start playing a network based stream (e.g. RTSP stream) at the
2161 int av_read_play(AVFormatContext *s)
2163 if (!s->iformat->read_play)
2164 return AVERROR_NOTSUPP;
2165 return s->iformat->read_play(s);
2169 * Pause a network based stream (e.g. RTSP stream).
2171 * Use av_read_play() to resume it.
2173 int av_read_pause(AVFormatContext *s)
2175 if (!s->iformat->read_pause)
2176 return AVERROR_NOTSUPP;
2177 return s->iformat->read_pause(s);
2181 * Close a media file (but not its codecs).
2183 * @param s media file handle
2185 void av_close_input_file(AVFormatContext *s)
2187 int i, must_open_file;
2190 /* free previous packet */
2191 if (s->cur_st && s->cur_st->parser)
2192 av_free_packet(&s->cur_pkt);
2194 if (s->iformat->read_close)
2195 s->iformat->read_close(s);
2196 for(i=0;i<s->nb_streams;i++) {
2197 /* free all data in a stream component */
2200 av_parser_close(st->parser);
2202 av_free(st->index_entries);
2203 av_free(st->codec->extradata);
2207 flush_packet_queue(s);
2209 if (s->iformat->flags & AVFMT_NOFILE) {
2212 if (must_open_file) {
2215 av_freep(&s->priv_data);
2220 * Add a new stream to a media file.
2222 * Can only be called in the read_header() function. If the flag
2223 * AVFMTCTX_NOHEADER is in the format context, then new streams
2224 * can be added in read_packet too.
2226 * @param s media file handle
2227 * @param id file format dependent stream id
2229 AVStream *av_new_stream(AVFormatContext *s, int id)
2234 if (s->nb_streams >= MAX_STREAMS)
2237 st = av_mallocz(sizeof(AVStream));
2241 st->codec= avcodec_alloc_context();
2243 /* no default bitrate if decoding */
2244 st->codec->bit_rate = 0;
2246 st->index = s->nb_streams;
2248 st->start_time = AV_NOPTS_VALUE;
2249 st->duration = AV_NOPTS_VALUE;
2250 st->cur_dts = AV_NOPTS_VALUE;
2252 /* default pts settings is MPEG like */
2253 av_set_pts_info(st, 33, 1, 90000);
2254 st->last_IP_pts = AV_NOPTS_VALUE;
2255 for(i=0; i<MAX_REORDER_DELAY+1; i++)
2256 st->pts_buffer[i]= AV_NOPTS_VALUE;
2258 s->streams[s->nb_streams++] = st;
2262 /************************************************************/
2263 /* output media file */
2265 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2269 if (s->oformat->priv_data_size > 0) {
2270 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2272 return AVERROR_NOMEM;
2274 s->priv_data = NULL;
2276 if (s->oformat->set_parameters) {
2277 ret = s->oformat->set_parameters(s, ap);
2285 * allocate the stream private data and write the stream header to an
2288 * @param s media file handle
2289 * @return 0 if OK. AVERROR_xxx if error.
2291 int av_write_header(AVFormatContext *s)
2296 // some sanity checks
2297 for(i=0;i<s->nb_streams;i++) {
2300 switch (st->codec->codec_type) {
2301 case CODEC_TYPE_AUDIO:
2302 if(st->codec->sample_rate<=0){
2303 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2307 case CODEC_TYPE_VIDEO:
2308 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2309 av_log(s, AV_LOG_ERROR, "time base not set\n");
2312 if(st->codec->width<=0 || st->codec->height<=0){
2313 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2320 if(s->oformat->write_header){
2321 ret = s->oformat->write_header(s);
2326 /* init PTS generation */
2327 for(i=0;i<s->nb_streams;i++) {
2328 int64_t den = AV_NOPTS_VALUE;
2331 switch (st->codec->codec_type) {
2332 case CODEC_TYPE_AUDIO:
2333 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2335 case CODEC_TYPE_VIDEO:
2336 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2341 if (den != AV_NOPTS_VALUE) {
2343 return AVERROR_INVALIDDATA;
2344 av_frac_init(&st->pts, 0, 0, den);
2350 //FIXME merge with compute_pkt_fields
2351 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2352 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2353 int num, den, frame_size, i;
2355 // 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, delay, pkt->size, pkt->stream_index);
2357 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2360 /* duration field */
2361 if (pkt->duration == 0) {
2362 compute_frame_duration(&num, &den, st, NULL, pkt);
2364 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2368 //XXX/FIXME this is a temporary hack until all encoders output pts
2369 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2371 // pkt->pts= st->cur_dts;
2372 pkt->pts= st->pts.val;
2375 //calculate dts from pts
2376 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2377 st->pts_buffer[0]= pkt->pts;
2378 for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2379 st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2380 for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2381 SWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2383 pkt->dts= st->pts_buffer[0];
2386 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2387 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2390 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2391 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2395 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2396 st->cur_dts= pkt->dts;
2397 st->pts.val= pkt->dts;
2400 switch (st->codec->codec_type) {
2401 case CODEC_TYPE_AUDIO:
2402 frame_size = get_audio_frame_size(st->codec, pkt->size);
2404 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2405 but it would be better if we had the real timestamps from the encoder */
2406 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2407 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2410 case CODEC_TYPE_VIDEO:
2411 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2419 static void truncate_ts(AVStream *st, AVPacket *pkt){
2420 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2423 // pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2425 pkt->pts &= pts_mask;
2426 pkt->dts &= pts_mask;
2430 * Write a packet to an output media file.
2432 * The packet shall contain one audio or video frame.
2434 * @param s media file handle
2435 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2436 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2438 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2442 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2443 if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2446 truncate_ts(s->streams[pkt->stream_index], pkt);
2448 ret= s->oformat->write_packet(s, pkt);
2450 ret= url_ferror(&s->pb);
2455 * Interleave a packet per DTS in an output media file.
2457 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2458 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2460 * @param s media file handle
2461 * @param out the interleaved packet will be output here
2462 * @param in the input packet
2463 * @param flush 1 if no further packets are available as input and all
2464 * remaining packets should be output
2465 * @return 1 if a packet was output, 0 if no packet could be output,
2466 * < 0 if an error occured
2468 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2469 AVPacketList *pktl, **next_point, *this_pktl;
2471 int streams[MAX_STREAMS];
2474 AVStream *st= s->streams[ pkt->stream_index];
2476 // assert(pkt->destruct != av_destruct_packet); //FIXME
2478 this_pktl = av_mallocz(sizeof(AVPacketList));
2479 this_pktl->pkt= *pkt;
2480 if(pkt->destruct == av_destruct_packet)
2481 pkt->destruct= NULL; // non shared -> must keep original from being freed
2483 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2485 next_point = &s->packet_buffer;
2487 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2488 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2489 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2490 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2492 next_point= &(*next_point)->next;
2494 this_pktl->next= *next_point;
2495 *next_point= this_pktl;
2498 memset(streams, 0, sizeof(streams));
2499 pktl= s->packet_buffer;
2501 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2502 if(streams[ pktl->pkt.stream_index ] == 0)
2504 streams[ pktl->pkt.stream_index ]++;
2508 if(s->nb_streams == stream_count || (flush && stream_count)){
2509 pktl= s->packet_buffer;
2512 s->packet_buffer= pktl->next;
2516 av_init_packet(out);
2522 * Interleaves a AVPacket correctly so it can be muxed.
2523 * @param out the interleaved packet will be output here
2524 * @param in the input packet
2525 * @param flush 1 if no further packets are available as input and all
2526 * remaining packets should be output
2527 * @return 1 if a packet was output, 0 if no packet could be output,
2528 * < 0 if an error occured
2530 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2531 if(s->oformat->interleave_packet)
2532 return s->oformat->interleave_packet(s, out, in, flush);
2534 return av_interleave_packet_per_dts(s, out, in, flush);
2538 * Writes a packet to an output media file ensuring correct interleaving.
2540 * The packet must contain one audio or video frame.
2541 * If the packets are already correctly interleaved the application should
2542 * call av_write_frame() instead as its slightly faster, its also important
2543 * to keep in mind that completly non interleaved input will need huge amounts
2544 * of memory to interleave with this, so its prefereable to interleave at the
2547 * @param s media file handle
2548 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2549 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2551 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2552 AVStream *st= s->streams[ pkt->stream_index];
2554 //FIXME/XXX/HACK drop zero sized packets
2555 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2558 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2559 if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2562 if(pkt->dts == AV_NOPTS_VALUE)
2567 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2568 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2571 truncate_ts(s->streams[opkt.stream_index], &opkt);
2572 ret= s->oformat->write_packet(s, &opkt);
2574 av_free_packet(&opkt);
2579 if(url_ferror(&s->pb))
2580 return url_ferror(&s->pb);
2585 * @brief Write the stream trailer to an output media file and
2586 * free the file private data.
2588 * @param s media file handle
2589 * @return 0 if OK. AVERROR_xxx if error.
2591 int av_write_trailer(AVFormatContext *s)
2597 ret= av_interleave_packet(s, &pkt, NULL, 1);
2598 if(ret<0) //FIXME cleanup needed for ret<0 ?
2603 truncate_ts(s->streams[pkt.stream_index], &pkt);
2604 ret= s->oformat->write_packet(s, &pkt);
2606 av_free_packet(&pkt);
2610 if(url_ferror(&s->pb))
2614 if(s->oformat->write_trailer)
2615 ret = s->oformat->write_trailer(s);
2618 ret=url_ferror(&s->pb);
2619 for(i=0;i<s->nb_streams;i++)
2620 av_freep(&s->streams[i]->priv_data);
2621 av_freep(&s->priv_data);
2625 /* "user interface" functions */
2627 void dump_format(AVFormatContext *ic,
2635 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2636 is_output ? "Output" : "Input",
2638 is_output ? ic->oformat->name : ic->iformat->name,
2639 is_output ? "to" : "from", url);
2641 av_log(NULL, AV_LOG_INFO, " Duration: ");
2642 if (ic->duration != AV_NOPTS_VALUE) {
2643 int hours, mins, secs, us;
2644 secs = ic->duration / AV_TIME_BASE;
2645 us = ic->duration % AV_TIME_BASE;
2650 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2651 (10 * us) / AV_TIME_BASE);
2653 av_log(NULL, AV_LOG_INFO, "N/A");
2655 if (ic->start_time != AV_NOPTS_VALUE) {
2657 av_log(NULL, AV_LOG_INFO, ", start: ");
2658 secs = ic->start_time / AV_TIME_BASE;
2659 us = ic->start_time % AV_TIME_BASE;
2660 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2661 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2663 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2665 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2667 av_log(NULL, AV_LOG_INFO, "N/A");
2669 av_log(NULL, AV_LOG_INFO, "\n");
2671 for(i=0;i<ic->nb_streams;i++) {
2672 AVStream *st = ic->streams[i];
2673 int g= ff_gcd(st->time_base.num, st->time_base.den);
2674 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2675 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2676 /* the pid is an important information, so we display it */
2677 /* XXX: add a generic system */
2679 flags = ic->oformat->flags;
2681 flags = ic->iformat->flags;
2682 if (flags & AVFMT_SHOW_IDS) {
2683 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2685 if (strlen(st->language) > 0) {
2686 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2688 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2689 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2690 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2691 if(st->r_frame_rate.den && st->r_frame_rate.num)
2692 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2693 /* else if(st->time_base.den && st->time_base.num)
2694 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2696 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2698 av_log(NULL, AV_LOG_INFO, "\n");
2705 int frame_rate, frame_rate_base;
2708 static AbvEntry frame_abvs[] = {
2709 { "ntsc", 720, 480, 30000, 1001 },
2710 { "pal", 720, 576, 25, 1 },
2711 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2712 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
2713 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2714 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
2715 { "film", 352, 240, 24, 1 },
2716 { "ntsc-film", 352, 240, 24000, 1001 },
2717 { "sqcif", 128, 96, 0, 0 },
2718 { "qcif", 176, 144, 0, 0 },
2719 { "cif", 352, 288, 0, 0 },
2720 { "4cif", 704, 576, 0, 0 },
2724 * parses width and height out of string str.
2726 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2729 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2731 int frame_width = 0, frame_height = 0;
2734 if (!strcmp(frame_abvs[i].abv, str)) {
2735 frame_width = frame_abvs[i].width;
2736 frame_height = frame_abvs[i].height;
2742 frame_width = strtol(p, (char **)&p, 10);
2745 frame_height = strtol(p, (char **)&p, 10);
2747 if (frame_width <= 0 || frame_height <= 0)
2749 *width_ptr = frame_width;
2750 *height_ptr = frame_height;
2755 * Converts frame rate from string to a fraction.
2757 * First we try to get an exact integer or fractional frame rate.
2758 * If this fails we convert the frame rate to a double and return
2759 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2761 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2766 /* First, we check our abbreviation table */
2767 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2768 if (!strcmp(frame_abvs[i].abv, arg)) {
2769 *frame_rate = frame_abvs[i].frame_rate;
2770 *frame_rate_base = frame_abvs[i].frame_rate_base;
2774 /* Then, we try to parse it as fraction */
2775 cp = strchr(arg, '/');
2777 cp = strchr(arg, ':');
2780 *frame_rate = strtol(arg, &cpp, 10);
2781 if (cpp != arg || cpp == cp)
2782 *frame_rate_base = strtol(cp+1, &cpp, 10);
2787 /* Finally we give up and parse it as double */
2788 AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2789 *frame_rate_base = time_base.den;
2790 *frame_rate = time_base.num;
2792 if (!*frame_rate || !*frame_rate_base)
2799 * Converts date string to number of seconds since Jan 1st, 1970.
2803 * - If not a duration:
2804 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2805 * Time is localtime unless Z is suffixed to the end. In this case GMT
2806 * Return the date in micro seconds since 1970
2809 * HH[:MM[:SS[.m...]]]
2813 #ifndef CONFIG_WINCE
2814 int64_t parse_date(const char *datestr, int duration)
2820 static const char *date_fmt[] = {
2824 static const char *time_fmt[] = {
2834 time_t now = time(0);
2836 len = strlen(datestr);
2838 lastch = datestr[len - 1];
2841 is_utc = (lastch == 'z' || lastch == 'Z');
2843 memset(&dt, 0, sizeof(dt));
2848 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2849 q = small_strptime(p, date_fmt[i], &dt);
2859 dt = *localtime(&now);
2861 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2866 if (*p == 'T' || *p == 't' || *p == ' ')
2869 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2870 q = small_strptime(p, time_fmt[i], &dt);
2880 q = small_strptime(p, time_fmt[0], &dt);
2882 dt.tm_sec = strtol(p, (char **)&q, 10);
2888 /* Now we have all the fields that we can get */
2893 return now * int64_t_C(1000000);
2897 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2899 dt.tm_isdst = -1; /* unknown */
2912 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2915 val += n * (*q - '0');
2919 return negative ? -t : t;
2921 #endif /* CONFIG_WINCE */
2924 * Attempts to find a specific tag in a URL.
2926 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2927 * Return 1 if found.
2929 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2939 while (*p != '\0' && *p != '=' && *p != '&') {
2940 if ((q - tag) < sizeof(tag) - 1)
2948 while (*p != '&' && *p != '\0') {
2949 if ((q - arg) < arg_size - 1) {
2959 if (!strcmp(tag, tag1))
2969 * Returns in 'buf' the path with '%d' replaced by number.
2971 * Also handles the '%0nd' format where 'n' is the total number
2972 * of digits and '%%'.
2974 * @param buf destination buffer
2975 * @param buf_size destination buffer size
2976 * @param path numbered sequence string
2977 * @number frame number
2978 * @return 0 if OK, -1 if format error.
2980 int av_get_frame_filename(char *buf, int buf_size,
2981 const char *path, int number)
2984 char *q, buf1[20], c;
2985 int nd, len, percentd_found;
2997 while (isdigit(*p)) {
2998 nd = nd * 10 + *p++ - '0';
3001 } while (isdigit(c));
3010 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3012 if ((q - buf + len) > buf_size - 1)
3014 memcpy(q, buf1, len);
3022 if ((q - buf) < buf_size - 1)
3026 if (!percentd_found)
3036 * Print nice hexa dump of a buffer
3037 * @param f stream for output
3039 * @param size buffer size
3041 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3045 for(i=0;i<size;i+=16) {
3049 fprintf(f, "%08x ", i);
3052 fprintf(f, " %02x", buf[i+j]);
3057 for(j=0;j<len;j++) {
3059 if (c < ' ' || c > '~')
3061 fprintf(f, "%c", c);
3068 * Print on 'f' a nice dump of a packet
3069 * @param f stream for output
3070 * @param pkt packet to dump
3071 * @param dump_payload true if the payload must be displayed too
3073 //FIXME needs to know the time_base
3074 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3076 fprintf(f, "stream #%d:\n", pkt->stream_index);
3077 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3078 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3079 /* DTS is _always_ valid after av_read_frame() */
3080 fprintf(f, " dts=");
3081 if (pkt->dts == AV_NOPTS_VALUE)
3084 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3085 /* PTS may be not known if B frames are present */
3086 fprintf(f, " pts=");
3087 if (pkt->pts == AV_NOPTS_VALUE)
3090 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3092 fprintf(f, " size=%d\n", pkt->size);
3094 av_hex_dump(f, pkt->data, pkt->size);
3097 void url_split(char *proto, int proto_size,
3098 char *authorization, int authorization_size,
3099 char *hostname, int hostname_size,
3101 char *path, int path_size,
3112 while (*p != ':' && *p != '\0') {
3113 if ((q - proto) < proto_size - 1)
3119 if (authorization_size > 0)
3120 authorization[0] = '\0';
3124 if (hostname_size > 0)
3128 char *at,*slash; // PETR: position of '@' character and '/' character
3135 at = strchr(p,'@'); // PETR: get the position of '@'
3136 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
3137 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3139 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
3141 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3142 if (*p == '@') { // PETR: passed '@'
3143 if (authorization_size > 0)
3147 } else if (!at) { // PETR: hostname
3148 if ((q - hostname) < hostname_size - 1)
3151 if ((q - authorization) < authorization_size - 1)
3156 if (hostname_size > 0)
3160 port = strtoul(p, (char **)&p, 10);
3165 pstrcpy(path, path_size, p);
3169 * Set the pts for a given stream.
3172 * @param pts_wrap_bits number of bits effectively used by the pts
3173 * (used for wrap control, 33 is the value for MPEG)
3174 * @param pts_num numerator to convert to seconds (MPEG: 1)
3175 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3177 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3178 int pts_num, int pts_den)
3180 s->pts_wrap_bits = pts_wrap_bits;
3181 s->time_base.num = pts_num;
3182 s->time_base.den = pts_den;
3185 /* fraction handling */
3188 * f = val + (num / den) + 0.5.
3190 * 'num' is normalized so that it is such as 0 <= num < den.
3192 * @param f fractional number
3193 * @param val integer value
3194 * @param num must be >= 0
3195 * @param den must be >= 1
3197 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3210 * Set f to (val + 0.5).
3212 static void av_frac_set(AVFrac *f, int64_t val)
3215 f->num = f->den >> 1;
3219 * Fractionnal addition to f: f = f + (incr / f->den).
3221 * @param f fractional number
3222 * @param incr increment, can be positive or negative
3224 static void av_frac_add(AVFrac *f, int64_t incr)
3228 num = f->num + incr;
3231 f->val += num / den;
3237 } else if (num >= den) {
3238 f->val += num / den;
3245 * register a new image format
3246 * @param img_fmt Image format descriptor
3248 void av_register_image_format(AVImageFormat *img_fmt)
3252 p = &first_image_format;
3253 while (*p != NULL) p = &(*p)->next;
3255 img_fmt->next = NULL;
3259 * Guesses image format based on data in the image.
3261 AVImageFormat *av_probe_image_format(AVProbeData *pd)
3263 AVImageFormat *fmt1, *fmt;
3264 int score, score_max;
3268 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3269 if (fmt1->img_probe) {
3270 score = fmt1->img_probe(pd);
3271 if (score > score_max) {
3281 * Guesses image format based on file name extensions.
3283 AVImageFormat *guess_image_format(const char *filename)
3285 AVImageFormat *fmt1;
3287 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3288 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3295 * Read an image from a stream.
3296 * @param gb byte stream containing the image
3297 * @param fmt image format, NULL if probing is required
3299 int av_read_image(ByteIOContext *pb, const char *filename,
3301 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3303 uint8_t buf[PROBE_BUF_MIN];
3304 AVProbeData probe_data, *pd = &probe_data;
3309 pd->filename = filename;
3311 pos = url_ftell(pb);
3312 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
3313 url_fseek(pb, pos, SEEK_SET);
3314 fmt = av_probe_image_format(pd);
3317 return AVERROR_NOFMT;
3318 ret = fmt->img_read(pb, alloc_cb, opaque);
3323 * Write an image to a stream.
3324 * @param pb byte stream for the image output
3325 * @param fmt image format
3326 * @param img image data and informations
3328 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3330 return fmt->img_write(pb, img);