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
25 * @file libavformat/utils.c
26 * Various utility functions for using ffmpeg library.
29 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
30 static void av_frac_add(AVFrac *f, int64_t incr);
31 static void av_frac_set(AVFrac *f, int64_t val);
33 /** head of registered input format linked list. */
34 AVInputFormat *first_iformat = NULL;
35 /** head of registered output format linked list. */
36 AVOutputFormat *first_oformat = NULL;
37 /** head of registered image format linked list. */
38 AVImageFormat *first_image_format = NULL;
40 void av_register_input_format(AVInputFormat *format)
44 while (*p != NULL) p = &(*p)->next;
49 void av_register_output_format(AVOutputFormat *format)
53 while (*p != NULL) p = &(*p)->next;
58 int match_ext(const char *filename, const char *extensions)
66 ext = strrchr(filename, '.');
72 while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
75 if (!strcasecmp(ext1, ext))
85 AVOutputFormat *guess_format(const char *short_name, const char *filename,
86 const char *mime_type)
88 AVOutputFormat *fmt, *fmt_found;
91 /* specific test for image sequences */
92 if (!short_name && filename &&
93 filename_number_test(filename) >= 0 &&
94 av_guess_image2_codec(filename) != CODEC_ID_NONE) {
95 return guess_format("image2", NULL, NULL);
97 if (!short_name && filename &&
98 filename_number_test(filename) >= 0 &&
99 guess_image_format(filename)) {
100 return guess_format("image", NULL, NULL);
103 /* find the proper file type */
107 while (fmt != NULL) {
109 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
111 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
113 if (filename && fmt->extensions &&
114 match_ext(filename, fmt->extensions)) {
117 if (score > score_max) {
126 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
127 const char *mime_type)
129 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
132 AVOutputFormat *stream_fmt;
133 char stream_format_name[64];
135 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
136 stream_fmt = guess_format(stream_format_name, NULL, NULL);
146 * Guesses the codec id based upon muxer and filename.
148 enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
149 const char *filename, const char *mime_type, enum CodecType type){
150 if(type == CODEC_TYPE_VIDEO){
151 enum CodecID codec_id= CODEC_ID_NONE;
153 if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
154 codec_id= av_guess_image2_codec(filename);
156 if(codec_id == CODEC_ID_NONE)
157 codec_id= fmt->video_codec;
159 }else if(type == CODEC_TYPE_AUDIO)
160 return fmt->audio_codec;
162 return CODEC_ID_NONE;
166 * finds AVInputFormat based on input format's short name.
168 AVInputFormat *av_find_input_format(const char *short_name)
171 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
172 if (!strcmp(fmt->name, short_name))
178 /* memory handling */
181 * Default packet destructor.
183 void av_destruct_packet(AVPacket *pkt)
186 pkt->data = NULL; pkt->size = 0;
190 * Allocate the payload of a packet and intialized its fields to default values.
193 * @param size wanted payload size
194 * @return 0 if OK. AVERROR_xxx otherwise.
196 int av_new_packet(AVPacket *pkt, int size)
199 if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
200 return AVERROR_NOMEM;
201 data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
203 return AVERROR_NOMEM;
204 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
209 pkt->destruct = av_destruct_packet;
214 * Allocate and read the payload of a packet and intialized its fields to default values.
217 * @param size wanted payload size
218 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
220 int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
222 int ret= av_new_packet(pkt, size);
227 pkt->pos= url_ftell(s);
229 ret= get_buffer(s, pkt->data, size);
238 /* This is a hack - the packet memory allocation stuff is broken. The
239 packet is allocated if it was not really allocated */
240 int av_dup_packet(AVPacket *pkt)
242 if (pkt->destruct != av_destruct_packet) {
244 /* we duplicate the packet and don't forget to put the padding
246 if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
247 return AVERROR_NOMEM;
248 data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
250 return AVERROR_NOMEM;
252 memcpy(data, pkt->data, pkt->size);
253 memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
255 pkt->destruct = av_destruct_packet;
262 int fifo_init(FifoBuffer *f, int size)
264 f->buffer = av_malloc(size);
267 f->end = f->buffer + size;
268 f->wptr = f->rptr = f->buffer;
272 void fifo_free(FifoBuffer *f)
277 int fifo_size(FifoBuffer *f, uint8_t *rptr)
284 if (f->wptr >= rptr) {
285 size = f->wptr - rptr;
287 size = (f->end - rptr) + (f->wptr - f->buffer);
293 * Get data from the fifo (returns -1 if not enough data).
295 int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
304 if (f->wptr >= rptr) {
305 size = f->wptr - rptr;
307 size = (f->end - rptr) + (f->wptr - f->buffer);
312 while (buf_size > 0) {
316 memcpy(buf, rptr, len);
330 void fifo_realloc(FifoBuffer *f, unsigned int new_size){
331 unsigned int old_size= f->end - f->buffer;
333 if(old_size < new_size){
334 uint8_t *old= f->buffer;
336 f->buffer= av_realloc(f->buffer, new_size);
338 f->rptr += f->buffer - old;
339 f->wptr += f->buffer - old;
341 if(f->wptr < f->rptr){
342 memmove(f->rptr + new_size - old_size, f->rptr, f->buffer + old_size - f->rptr);
343 f->rptr += new_size - old_size;
345 f->end= f->buffer + new_size;
349 void fifo_write(FifoBuffer *f, const uint8_t *buf, int size, uint8_t **wptr_ptr)
362 memcpy(wptr, buf, len);
372 /* get data from the fifo (return -1 if not enough data) */
373 int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
375 uint8_t *rptr = *rptr_ptr;
378 if (f->wptr >= rptr) {
379 size = f->wptr - rptr;
381 size = (f->end - rptr) + (f->wptr - f->buffer);
386 while (buf_size > 0) {
390 put_buffer(pb, rptr, len);
400 int filename_number_test(const char *filename)
405 return get_frame_filename(buf, sizeof(buf), filename, 1);
411 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
413 AVInputFormat *fmt1, *fmt;
414 int score, score_max;
418 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
419 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
422 if (fmt1->read_probe) {
423 score = fmt1->read_probe(pd);
424 } else if (fmt1->extensions) {
425 if (match_ext(pd->filename, fmt1->extensions)) {
429 if (score > score_max) {
437 /************************************************************/
438 /* input media file */
441 * Open a media file from an IO stream. 'fmt' must be specified.
443 static const char* format_to_name(void* ptr)
445 AVFormatContext* fc = (AVFormatContext*) ptr;
446 if(fc->iformat) return fc->iformat->name;
447 else if(fc->oformat) return fc->oformat->name;
451 static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
453 AVFormatContext *av_alloc_format_context(void)
456 ic = av_mallocz(sizeof(AVFormatContext));
458 ic->av_class = &av_format_context_class;
463 * Allocates all the structures needed to read an input stream.
464 * This does not open the needed codecs for decoding the stream[s].
466 int av_open_input_stream(AVFormatContext **ic_ptr,
467 ByteIOContext *pb, const char *filename,
468 AVInputFormat *fmt, AVFormatParameters *ap)
472 AVFormatParameters default_ap;
476 memset(ap, 0, sizeof(default_ap));
479 ic = av_alloc_format_context();
487 ic->duration = AV_NOPTS_VALUE;
488 ic->start_time = AV_NOPTS_VALUE;
489 pstrcpy(ic->filename, sizeof(ic->filename), filename);
491 /* allocate private data */
492 if (fmt->priv_data_size > 0) {
493 ic->priv_data = av_mallocz(fmt->priv_data_size);
494 if (!ic->priv_data) {
499 ic->priv_data = NULL;
502 err = ic->iformat->read_header(ic, ap);
507 ic->data_offset = url_ftell(&ic->pb);
513 av_freep(&ic->priv_data);
520 /** Size of probe buffer, for guessing file type from file contents. */
521 #define PROBE_BUF_MIN 2048
522 #define PROBE_BUF_MAX (1<<20)
525 * Open a media file as input. The codec are not opened. Only the file
526 * header (if present) is read.
528 * @param ic_ptr the opened media file handle is put here
529 * @param filename filename to open.
530 * @param fmt if non NULL, force the file format to use
531 * @param buf_size optional buffer size (zero if default is OK)
532 * @param ap additionnal parameters needed when opening the file (NULL if default)
533 * @return 0 if OK. AVERROR_xxx otherwise.
535 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
538 AVFormatParameters *ap)
540 int err, must_open_file, file_opened, probe_size;
541 AVProbeData probe_data, *pd = &probe_data;
542 ByteIOContext pb1, *pb = &pb1;
547 pd->filename = filename;
552 /* guess format if no file can be opened */
553 fmt = av_probe_input_format(pd, 0);
556 /* do not open file if the format does not need it. XXX: specific
557 hack needed to handle RTSP/TCP */
559 if (fmt && (fmt->flags & AVFMT_NOFILE)) {
561 pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
564 if (!fmt || must_open_file) {
565 /* if no file needed do not try to open one */
566 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
572 url_setbufsize(pb, buf_size);
575 for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
576 /* read probe data */
577 pd->buf= av_realloc(pd->buf, probe_size);
578 pd->buf_size = get_buffer(pb, pd->buf, probe_size);
579 if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
581 if (url_fopen(pb, filename, URL_RDONLY) < 0) {
587 /* guess file format */
588 fmt = av_probe_input_format(pd, 1);
593 /* if still no format found, error */
599 /* XXX: suppress this hack for redirectors */
600 #ifdef CONFIG_NETWORK
601 if (fmt == &redir_demux) {
602 err = redir_open(ic_ptr, pb);
608 /* check filename in case of an image number is expected */
609 if (fmt->flags & AVFMT_NEEDNUMBER) {
610 if (filename_number_test(filename) < 0) {
611 err = AVERROR_NUMEXPECTED;
615 err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
628 /*******************************************************/
631 * Read a transport packet from a media file.
633 * This function is absolete and should never be used.
634 * Use av_read_frame() instead.
636 * @param s media file handle
637 * @param pkt is filled
638 * @return 0 if OK. AVERROR_xxx if error.
640 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
642 return s->iformat->read_packet(s, pkt);
645 /**********************************************************/
648 * Get the number of samples of an audio frame. Return (-1) if error.
650 static int get_audio_frame_size(AVCodecContext *enc, int size)
654 if (enc->frame_size <= 1) {
655 /* specific hack for pcm codecs because no frame size is
657 switch(enc->codec_id) {
658 case CODEC_ID_PCM_S32LE:
659 case CODEC_ID_PCM_S32BE:
660 case CODEC_ID_PCM_U32LE:
661 case CODEC_ID_PCM_U32BE:
662 if (enc->channels == 0)
664 frame_size = size / (4 * enc->channels);
666 case CODEC_ID_PCM_S24LE:
667 case CODEC_ID_PCM_S24BE:
668 case CODEC_ID_PCM_U24LE:
669 case CODEC_ID_PCM_U24BE:
670 case CODEC_ID_PCM_S24DAUD:
671 if (enc->channels == 0)
673 frame_size = size / (3 * enc->channels);
675 case CODEC_ID_PCM_S16LE:
676 case CODEC_ID_PCM_S16BE:
677 case CODEC_ID_PCM_U16LE:
678 case CODEC_ID_PCM_U16BE:
679 if (enc->channels == 0)
681 frame_size = size / (2 * enc->channels);
683 case CODEC_ID_PCM_S8:
684 case CODEC_ID_PCM_U8:
685 case CODEC_ID_PCM_MULAW:
686 case CODEC_ID_PCM_ALAW:
687 if (enc->channels == 0)
689 frame_size = size / (enc->channels);
692 /* used for example by ADPCM codecs */
693 if (enc->bit_rate == 0)
695 frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
699 frame_size = enc->frame_size;
706 * Return the frame duration in seconds, return 0 if not available.
708 static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
709 AVCodecParserContext *pc, AVPacket *pkt)
715 switch(st->codec->codec_type) {
716 case CODEC_TYPE_VIDEO:
717 if(st->time_base.num*1000LL > st->time_base.den){
718 *pnum = st->time_base.num;
719 *pden = st->time_base.den;
720 }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
721 *pnum = st->codec->time_base.num;
722 *pden = st->codec->time_base.den;
723 if (pc && pc->repeat_pict) {
725 *pnum = (*pnum) * (2 + pc->repeat_pict);
729 case CODEC_TYPE_AUDIO:
730 frame_size = get_audio_frame_size(st->codec, pkt->size);
734 *pden = st->codec->sample_rate;
741 static int is_intra_only(AVCodecContext *enc){
742 if(enc->codec_type == CODEC_TYPE_AUDIO){
744 }else if(enc->codec_type == CODEC_TYPE_VIDEO){
745 switch(enc->codec_id){
747 case CODEC_ID_MJPEGB:
749 case CODEC_ID_RAWVIDEO:
750 case CODEC_ID_DVVIDEO:
751 case CODEC_ID_HUFFYUV:
752 case CODEC_ID_FFVHUFF:
763 static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
764 int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
765 int64_t delta= last_ts - mask/2;
766 return ((lsb - delta)&mask) + delta;
769 static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
770 AVCodecParserContext *pc, AVPacket *pkt)
772 int num, den, presentation_delayed;
773 /* handle wrapping */
774 if(st->cur_dts != AV_NOPTS_VALUE){
775 if(pkt->pts != AV_NOPTS_VALUE)
776 pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
777 if(pkt->dts != AV_NOPTS_VALUE)
778 pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
781 if (pkt->duration == 0) {
782 compute_frame_duration(&num, &den, st, pc, pkt);
784 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
788 if(is_intra_only(st->codec))
789 pkt->flags |= PKT_FLAG_KEY;
791 /* do we have a video B frame ? */
792 presentation_delayed = 0;
793 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
794 /* XXX: need has_b_frame, but cannot get it if the codec is
796 if (( st->codec->codec_id == CODEC_ID_H264
797 || st->codec->has_b_frames) &&
798 pc && pc->pict_type != FF_B_TYPE)
799 presentation_delayed = 1;
800 /* this may be redundant, but it shouldnt hurt */
801 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
802 presentation_delayed = 1;
805 if(st->cur_dts == AV_NOPTS_VALUE){
806 if(presentation_delayed) st->cur_dts = -pkt->duration;
807 else st->cur_dts = 0;
810 // 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);
811 /* interpolate PTS and DTS if they are not present */
812 if (presentation_delayed) {
813 /* DTS = decompression time stamp */
814 /* PTS = presentation time stamp */
815 if (pkt->dts == AV_NOPTS_VALUE) {
816 /* if we know the last pts, use it */
817 if(st->last_IP_pts != AV_NOPTS_VALUE)
818 st->cur_dts = pkt->dts = st->last_IP_pts;
820 pkt->dts = st->cur_dts;
822 st->cur_dts = pkt->dts;
824 /* this is tricky: the dts must be incremented by the duration
825 of the frame we are displaying, i.e. the last I or P frame */
826 if (st->last_IP_duration == 0)
827 st->cur_dts += pkt->duration;
829 st->cur_dts += st->last_IP_duration;
830 st->last_IP_duration = pkt->duration;
831 st->last_IP_pts= pkt->pts;
832 /* cannot compute PTS if not present (we can compute it only
833 by knowing the futur */
834 } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
835 if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
836 int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
837 int64_t new_diff= ABS(st->cur_dts - pkt->pts);
838 if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
839 pkt->pts += pkt->duration;
840 // 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);
844 /* presentation is not delayed : PTS and DTS are the same */
845 if (pkt->pts == AV_NOPTS_VALUE) {
846 if (pkt->dts == AV_NOPTS_VALUE) {
847 pkt->pts = st->cur_dts;
848 pkt->dts = st->cur_dts;
851 st->cur_dts = pkt->dts;
855 st->cur_dts = pkt->pts;
858 st->cur_dts += pkt->duration;
860 // 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);
865 /* key frame computation */
866 switch(st->codec->codec_type) {
867 case CODEC_TYPE_VIDEO:
868 if (pc->pict_type == FF_I_TYPE)
869 pkt->flags |= PKT_FLAG_KEY;
871 case CODEC_TYPE_AUDIO:
872 pkt->flags |= PKT_FLAG_KEY;
880 void av_destruct_packet_nofree(AVPacket *pkt)
882 pkt->data = NULL; pkt->size = 0;
885 static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
891 /* select current input stream component */
894 if (!st->need_parsing || !st->parser) {
895 /* no parsing needed: we just output the packet as is */
896 /* raw data support */
898 compute_pkt_fields(s, st, NULL, pkt);
901 } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
902 len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
903 s->cur_ptr, s->cur_len,
904 s->cur_pkt.pts, s->cur_pkt.dts);
905 s->cur_pkt.pts = AV_NOPTS_VALUE;
906 s->cur_pkt.dts = AV_NOPTS_VALUE;
907 /* increment read pointer */
911 /* return packet if any */
915 pkt->stream_index = st->index;
916 pkt->pts = st->parser->pts;
917 pkt->dts = st->parser->dts;
918 pkt->destruct = av_destruct_packet_nofree;
919 compute_pkt_fields(s, st, st->parser, pkt);
924 av_free_packet(&s->cur_pkt);
928 /* read next packet */
929 ret = av_read_packet(s, &s->cur_pkt);
933 /* return the last frames, if any */
934 for(i = 0; i < s->nb_streams; i++) {
936 if (st->parser && st->need_parsing) {
937 av_parser_parse(st->parser, st->codec,
938 &pkt->data, &pkt->size,
940 AV_NOPTS_VALUE, AV_NOPTS_VALUE);
945 /* no more packets: really terminates parsing */
949 st = s->streams[s->cur_pkt.stream_index];
952 s->cur_ptr = s->cur_pkt.data;
953 s->cur_len = s->cur_pkt.size;
954 if (st->need_parsing && !st->parser) {
955 st->parser = av_parser_init(st->codec->codec_id);
957 /* no parser available : just output the raw packets */
958 st->need_parsing = 0;
959 }else if(st->need_parsing == 2){
960 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
968 * Return the next frame of a stream.
970 * The returned packet is valid
971 * until the next av_read_frame() or until av_close_input_file() and
972 * must be freed with av_free_packet. For video, the packet contains
973 * exactly one frame. For audio, it contains an integer number of
974 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
975 * data). If the audio frames have a variable size (e.g. MPEG audio),
976 * then it contains one frame.
978 * pkt->pts, pkt->dts and pkt->duration are always set to correct
979 * values in AV_TIME_BASE unit (and guessed if the format cannot
980 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
981 * has B frames, so it is better to rely on pkt->dts if you do not
982 * decompress the payload.
984 * @return 0 if OK, < 0 if error or end of file.
986 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
990 const int genpts= s->flags & AVFMT_FLAG_GENPTS;
993 pktl = s->packet_buffer;
995 AVPacket *next_pkt= &pktl->pkt;
997 if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
998 while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
999 if( pktl->pkt.stream_index == next_pkt->stream_index
1000 && next_pkt->dts < pktl->pkt.dts
1001 && pktl->pkt.pts != pktl->pkt.dts //not b frame
1002 /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1003 next_pkt->pts= pktl->pkt.dts;
1007 pktl = s->packet_buffer;
1010 if( next_pkt->pts != AV_NOPTS_VALUE
1011 || next_pkt->dts == AV_NOPTS_VALUE
1013 /* read packet from packet buffer, if there is data */
1015 s->packet_buffer = pktl->next;
1021 AVPacketList **plast_pktl= &s->packet_buffer;
1022 int ret= av_read_frame_internal(s, pkt);
1024 if(pktl && ret != -EAGAIN){
1031 /* duplicate the packet */
1032 if (av_dup_packet(pkt) < 0)
1033 return AVERROR_NOMEM;
1035 while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
1037 pktl = av_mallocz(sizeof(AVPacketList));
1039 return AVERROR_NOMEM;
1041 /* add the packet in the buffered packet list */
1045 assert(!s->packet_buffer);
1046 return av_read_frame_internal(s, pkt);
1051 /* XXX: suppress the packet queue */
1052 static void flush_packet_queue(AVFormatContext *s)
1057 pktl = s->packet_buffer;
1060 s->packet_buffer = pktl->next;
1061 av_free_packet(&pktl->pkt);
1066 /*******************************************************/
1069 int av_find_default_stream_index(AVFormatContext *s)
1074 if (s->nb_streams <= 0)
1076 for(i = 0; i < s->nb_streams; i++) {
1078 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1086 * Flush the frame reader.
1088 static void av_read_frame_flush(AVFormatContext *s)
1093 flush_packet_queue(s);
1095 /* free previous packet */
1097 if (s->cur_st->parser)
1098 av_free_packet(&s->cur_pkt);
1105 /* for each stream, reset read state */
1106 for(i = 0; i < s->nb_streams; i++) {
1110 av_parser_close(st->parser);
1113 st->last_IP_pts = AV_NOPTS_VALUE;
1114 st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1119 * Updates cur_dts of all streams based on given timestamp and AVStream.
1121 * Stream ref_st unchanged, others set cur_dts in their native timebase
1122 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1123 * @param timestamp new dts expressed in time_base of param ref_st
1124 * @param ref_st reference stream giving time_base of param timestamp
1126 static void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1129 for(i = 0; i < s->nb_streams; i++) {
1130 AVStream *st = s->streams[i];
1132 st->cur_dts = av_rescale(timestamp,
1133 st->time_base.den * (int64_t)ref_st->time_base.num,
1134 st->time_base.num * (int64_t)ref_st->time_base.den);
1139 * Add a index entry into a sorted list updateing if it is already there.
1141 * @param timestamp timestamp in the timebase of the given stream
1143 int av_add_index_entry(AVStream *st,
1144 int64_t pos, int64_t timestamp, int size, int distance, int flags)
1146 AVIndexEntry *entries, *ie;
1149 if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1152 entries = av_fast_realloc(st->index_entries,
1153 &st->index_entries_allocated_size,
1154 (st->nb_index_entries + 1) *
1155 sizeof(AVIndexEntry));
1159 st->index_entries= entries;
1161 index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1164 index= st->nb_index_entries++;
1165 ie= &entries[index];
1166 assert(index==0 || ie[-1].timestamp < timestamp);
1168 ie= &entries[index];
1169 if(ie->timestamp != timestamp){
1170 if(ie->timestamp <= timestamp)
1172 memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1173 st->nb_index_entries++;
1174 }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1175 distance= ie->min_distance;
1179 ie->timestamp = timestamp;
1180 ie->min_distance= distance;
1188 * build an index for raw streams using a parser.
1190 static void av_build_index_raw(AVFormatContext *s)
1192 AVPacket pkt1, *pkt = &pkt1;
1197 av_read_frame_flush(s);
1198 url_fseek(&s->pb, s->data_offset, SEEK_SET);
1201 ret = av_read_frame(s, pkt);
1204 if (pkt->stream_index == 0 && st->parser &&
1205 (pkt->flags & PKT_FLAG_KEY)) {
1206 av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1207 0, 0, AVINDEX_KEYFRAME);
1209 av_free_packet(pkt);
1214 * Returns TRUE if we deal with a raw stream.
1216 * Raw codec data and parsing needed.
1218 static int is_raw_stream(AVFormatContext *s)
1222 if (s->nb_streams != 1)
1225 if (!st->need_parsing)
1231 * Gets the index for a specific timestamp.
1232 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1233 * the timestamp which is <= the requested one, if backward is 0
1234 * then it will be >=
1235 * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1236 * @return < 0 if no such timestamp could be found
1238 int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1241 AVIndexEntry *entries= st->index_entries;
1242 int nb_entries= st->nb_index_entries;
1251 timestamp = entries[m].timestamp;
1252 if(timestamp >= wanted_timestamp)
1254 if(timestamp <= wanted_timestamp)
1257 m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1259 if(!(flags & AVSEEK_FLAG_ANY)){
1260 while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1261 m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1273 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1274 * this isnt supposed to be called directly by a user application, but by demuxers
1275 * @param target_ts target timestamp in the time base of the given stream
1276 * @param stream_index stream number
1278 int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1279 AVInputFormat *avif= s->iformat;
1280 int64_t pos_min, pos_max, pos, pos_limit;
1281 int64_t ts_min, ts_max, ts;
1282 int64_t start_pos, filesize;
1283 int index, no_change;
1286 if (stream_index < 0)
1290 av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1294 ts_min= AV_NOPTS_VALUE;
1295 pos_limit= -1; //gcc falsely says it may be uninitalized
1297 st= s->streams[stream_index];
1298 if(st->index_entries){
1301 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()
1302 index= FFMAX(index, 0);
1303 e= &st->index_entries[index];
1305 if(e->timestamp <= target_ts || e->pos == e->min_distance){
1307 ts_min= e->timestamp;
1309 av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1316 index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1317 assert(index < st->nb_index_entries);
1319 e= &st->index_entries[index];
1320 assert(e->timestamp >= target_ts);
1322 ts_max= e->timestamp;
1323 pos_limit= pos_max - e->min_distance;
1325 av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1326 pos_max,pos_limit, ts_max);
1331 if(ts_min == AV_NOPTS_VALUE){
1332 pos_min = s->data_offset;
1333 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1334 if (ts_min == AV_NOPTS_VALUE)
1338 if(ts_max == AV_NOPTS_VALUE){
1340 filesize = url_fsize(&s->pb);
1341 pos_max = filesize - 1;
1344 ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1346 }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1347 if (ts_max == AV_NOPTS_VALUE)
1351 int64_t tmp_pos= pos_max + 1;
1352 int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1353 if(tmp_ts == AV_NOPTS_VALUE)
1357 if(tmp_pos >= filesize)
1363 if(ts_min > ts_max){
1365 }else if(ts_min == ts_max){
1370 while (pos_min < pos_limit) {
1372 av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1376 assert(pos_limit <= pos_max);
1379 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1380 // interpolate position (better than dichotomy)
1381 pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1382 + pos_min - approximate_keyframe_distance;
1383 }else if(no_change==1){
1384 // bisection, if interpolation failed to change min or max pos last time
1385 pos = (pos_min + pos_limit)>>1;
1387 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1392 else if(pos > pos_limit)
1396 ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1402 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);
1404 assert(ts != AV_NOPTS_VALUE);
1405 if (target_ts <= ts) {
1406 pos_limit = start_pos - 1;
1410 if (target_ts >= ts) {
1416 pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1417 ts = (flags & AVSEEK_FLAG_BACKWARD) ? ts_min : ts_max;
1420 ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1422 ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1423 av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1424 pos, ts_min, target_ts, ts_max);
1427 url_fseek(&s->pb, pos, SEEK_SET);
1429 av_update_cur_dts(s, st, ts);
1434 static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1435 int64_t pos_min, pos_max;
1439 if (stream_index < 0)
1442 st= s->streams[stream_index];
1445 pos_min = s->data_offset;
1446 pos_max = url_fsize(&s->pb) - 1;
1448 if (pos < pos_min) pos= pos_min;
1449 else if(pos > pos_max) pos= pos_max;
1451 url_fseek(&s->pb, pos, SEEK_SET);
1454 av_update_cur_dts(s, st, ts);
1459 static int av_seek_frame_generic(AVFormatContext *s,
1460 int stream_index, int64_t timestamp, int flags)
1466 if (!s->index_built) {
1467 if (is_raw_stream(s)) {
1468 av_build_index_raw(s);
1475 st = s->streams[stream_index];
1476 index = av_index_search_timestamp(st, timestamp, flags);
1480 /* now we have found the index, we can seek */
1481 ie = &st->index_entries[index];
1482 av_read_frame_flush(s);
1483 url_fseek(&s->pb, ie->pos, SEEK_SET);
1485 av_update_cur_dts(s, st, ie->timestamp);
1491 * Seek to the key frame at timestamp.
1492 * 'timestamp' in 'stream_index'.
1493 * @param stream_index If stream_index is (-1), a default
1494 * stream is selected, and timestamp is automatically converted
1495 * from AV_TIME_BASE units to the stream specific time_base.
1496 * @param timestamp timestamp in AVStream.time_base units
1497 * or if there is no stream specified then in AV_TIME_BASE units
1498 * @param flags flags which select direction and seeking mode
1499 * @return >= 0 on success
1501 int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1506 av_read_frame_flush(s);
1508 if(flags & AVSEEK_FLAG_BYTE)
1509 return av_seek_frame_byte(s, stream_index, timestamp, flags);
1511 if(stream_index < 0){
1512 stream_index= av_find_default_stream_index(s);
1513 if(stream_index < 0)
1516 st= s->streams[stream_index];
1517 /* timestamp for default must be expressed in AV_TIME_BASE units */
1518 timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1520 st= s->streams[stream_index];
1522 /* first, we try the format specific seek */
1523 if (s->iformat->read_seek)
1524 ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1531 if(s->iformat->read_timestamp)
1532 return av_seek_frame_binary(s, stream_index, timestamp, flags);
1534 return av_seek_frame_generic(s, stream_index, timestamp, flags);
1537 /*******************************************************/
1540 * Returns TRUE if the stream has accurate timings in any stream.
1542 * @return TRUE if the stream has accurate timings for at least one component.
1544 static int av_has_timings(AVFormatContext *ic)
1549 for(i = 0;i < ic->nb_streams; i++) {
1550 st = ic->streams[i];
1551 if (st->start_time != AV_NOPTS_VALUE &&
1552 st->duration != AV_NOPTS_VALUE)
1559 * Estimate the stream timings from the one of each components.
1561 * Also computes the global bitrate if possible.
1563 static void av_update_stream_timings(AVFormatContext *ic)
1565 int64_t start_time, start_time1, end_time, end_time1;
1569 start_time = MAXINT64;
1570 end_time = MININT64;
1571 for(i = 0;i < ic->nb_streams; i++) {
1572 st = ic->streams[i];
1573 if (st->start_time != AV_NOPTS_VALUE) {
1574 start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1575 if (start_time1 < start_time)
1576 start_time = start_time1;
1577 if (st->duration != AV_NOPTS_VALUE) {
1578 end_time1 = start_time1
1579 + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1580 if (end_time1 > end_time)
1581 end_time = end_time1;
1585 if (start_time != MAXINT64) {
1586 ic->start_time = start_time;
1587 if (end_time != MININT64) {
1588 ic->duration = end_time - start_time;
1589 if (ic->file_size > 0) {
1590 /* compute the bit rate */
1591 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1592 (double)ic->duration;
1599 static void fill_all_stream_timings(AVFormatContext *ic)
1604 av_update_stream_timings(ic);
1605 for(i = 0;i < ic->nb_streams; i++) {
1606 st = ic->streams[i];
1607 if (st->start_time == AV_NOPTS_VALUE) {
1608 if(ic->start_time != AV_NOPTS_VALUE)
1609 st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1610 if(ic->duration != AV_NOPTS_VALUE)
1611 st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1616 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1618 int64_t filesize, duration;
1622 /* if bit_rate is already set, we believe it */
1623 if (ic->bit_rate == 0) {
1625 for(i=0;i<ic->nb_streams;i++) {
1626 st = ic->streams[i];
1627 bit_rate += st->codec->bit_rate;
1629 ic->bit_rate = bit_rate;
1632 /* if duration is already set, we believe it */
1633 if (ic->duration == AV_NOPTS_VALUE &&
1634 ic->bit_rate != 0 &&
1635 ic->file_size != 0) {
1636 filesize = ic->file_size;
1638 for(i = 0; i < ic->nb_streams; i++) {
1639 st = ic->streams[i];
1640 duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1641 if (st->start_time == AV_NOPTS_VALUE ||
1642 st->duration == AV_NOPTS_VALUE) {
1644 st->duration = duration;
1651 #define DURATION_MAX_READ_SIZE 250000
1653 /* only usable for MPEG-PS streams */
1654 static void av_estimate_timings_from_pts(AVFormatContext *ic)
1656 AVPacket pkt1, *pkt = &pkt1;
1658 int read_size, i, ret;
1660 int64_t filesize, offset, duration;
1662 /* free previous packet */
1663 if (ic->cur_st && ic->cur_st->parser)
1664 av_free_packet(&ic->cur_pkt);
1667 /* flush packet queue */
1668 flush_packet_queue(ic);
1670 for(i=0;i<ic->nb_streams;i++) {
1671 st = ic->streams[i];
1673 av_parser_close(st->parser);
1678 /* we read the first packets to get the first PTS (not fully
1679 accurate, but it is enough now) */
1680 url_fseek(&ic->pb, 0, SEEK_SET);
1683 if (read_size >= DURATION_MAX_READ_SIZE)
1685 /* if all info is available, we can stop */
1686 for(i = 0;i < ic->nb_streams; i++) {
1687 st = ic->streams[i];
1688 if (st->start_time == AV_NOPTS_VALUE)
1691 if (i == ic->nb_streams)
1694 ret = av_read_packet(ic, pkt);
1697 read_size += pkt->size;
1698 st = ic->streams[pkt->stream_index];
1699 if (pkt->pts != AV_NOPTS_VALUE) {
1700 if (st->start_time == AV_NOPTS_VALUE)
1701 st->start_time = pkt->pts;
1703 av_free_packet(pkt);
1706 /* estimate the end time (duration) */
1707 /* XXX: may need to support wrapping */
1708 filesize = ic->file_size;
1709 offset = filesize - DURATION_MAX_READ_SIZE;
1713 url_fseek(&ic->pb, offset, SEEK_SET);
1716 if (read_size >= DURATION_MAX_READ_SIZE)
1718 /* if all info is available, we can stop */
1719 for(i = 0;i < ic->nb_streams; i++) {
1720 st = ic->streams[i];
1721 if (st->duration == AV_NOPTS_VALUE)
1724 if (i == ic->nb_streams)
1727 ret = av_read_packet(ic, pkt);
1730 read_size += pkt->size;
1731 st = ic->streams[pkt->stream_index];
1732 if (pkt->pts != AV_NOPTS_VALUE) {
1733 end_time = pkt->pts;
1734 duration = end_time - st->start_time;
1736 if (st->duration == AV_NOPTS_VALUE ||
1737 st->duration < duration)
1738 st->duration = duration;
1741 av_free_packet(pkt);
1744 fill_all_stream_timings(ic);
1746 url_fseek(&ic->pb, 0, SEEK_SET);
1749 static void av_estimate_timings(AVFormatContext *ic)
1753 /* get the file size, if possible */
1754 if (ic->iformat->flags & AVFMT_NOFILE) {
1757 file_size = url_fsize(&ic->pb);
1761 ic->file_size = file_size;
1763 if ((ic->iformat == &mpegps_demux || ic->iformat == &mpegts_demux) && file_size && !ic->pb.is_streamed) {
1764 /* get accurate estimate from the PTSes */
1765 av_estimate_timings_from_pts(ic);
1766 } else if (av_has_timings(ic)) {
1767 /* at least one components has timings - we use them for all
1769 fill_all_stream_timings(ic);
1771 /* less precise: use bit rate info */
1772 av_estimate_timings_from_bit_rate(ic);
1774 av_update_stream_timings(ic);
1780 for(i = 0;i < ic->nb_streams; i++) {
1781 st = ic->streams[i];
1782 printf("%d: start_time: %0.3f duration: %0.3f\n",
1783 i, (double)st->start_time / AV_TIME_BASE,
1784 (double)st->duration / AV_TIME_BASE);
1786 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1787 (double)ic->start_time / AV_TIME_BASE,
1788 (double)ic->duration / AV_TIME_BASE,
1789 ic->bit_rate / 1000);
1794 static int has_codec_parameters(AVCodecContext *enc)
1797 switch(enc->codec_type) {
1798 case CODEC_TYPE_AUDIO:
1799 val = enc->sample_rate;
1801 case CODEC_TYPE_VIDEO:
1802 val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1811 static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1815 int got_picture, ret=0;
1818 if(!st->codec->codec){
1819 codec = avcodec_find_decoder(st->codec->codec_id);
1822 ret = avcodec_open(st->codec, codec);
1827 if(!has_codec_parameters(st->codec)){
1828 switch(st->codec->codec_type) {
1829 case CODEC_TYPE_VIDEO:
1830 ret = avcodec_decode_video(st->codec, &picture,
1831 &got_picture, (uint8_t *)data, size);
1833 case CODEC_TYPE_AUDIO:
1834 samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1837 ret = avcodec_decode_audio(st->codec, samples,
1838 &got_picture, (uint8_t *)data, size);
1849 /* absolute maximum size we read until we abort */
1850 #define MAX_READ_SIZE 5000000
1852 /* maximum duration until we stop analysing the stream */
1853 #define MAX_STREAM_DURATION ((int)(AV_TIME_BASE * 3.0))
1856 * Read the beginning of a media file to get stream information. This
1857 * is useful for file formats with no headers such as MPEG. This
1858 * function also compute the real frame rate in case of mpeg2 repeat
1861 * @param ic media file handle
1862 * @return >=0 if OK. AVERROR_xxx if error.
1863 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
1865 int av_find_stream_info(AVFormatContext *ic)
1867 int i, count, ret, read_size, j;
1869 AVPacket pkt1, *pkt;
1870 AVPacketList *pktl=NULL, **ppktl;
1871 int64_t last_dts[MAX_STREAMS];
1872 int64_t duration_sum[MAX_STREAMS];
1873 int duration_count[MAX_STREAMS]={0};
1875 for(i=0;i<ic->nb_streams;i++) {
1876 st = ic->streams[i];
1877 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1878 /* if(!st->time_base.num)
1880 if(!st->codec->time_base.num)
1881 st->codec->time_base= st->time_base;
1883 //only for the split stuff
1885 st->parser = av_parser_init(st->codec->codec_id);
1886 if(st->need_parsing == 2 && st->parser){
1887 st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1892 for(i=0;i<MAX_STREAMS;i++){
1893 last_dts[i]= AV_NOPTS_VALUE;
1894 duration_sum[i]= INT64_MAX;
1899 ppktl = &ic->packet_buffer;
1901 /* check if one codec still needs to be handled */
1902 for(i=0;i<ic->nb_streams;i++) {
1903 st = ic->streams[i];
1904 if (!has_codec_parameters(st->codec))
1906 /* variable fps and no guess at the real fps */
1907 if( st->codec->time_base.den >= 101LL*st->codec->time_base.num
1908 && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1910 if(st->parser && st->parser->parser->split && !st->codec->extradata)
1913 if (i == ic->nb_streams) {
1914 /* NOTE: if the format has no header, then we need to read
1915 some packets to get most of the streams, so we cannot
1917 if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1918 /* if we found the info for all the codecs, we can stop */
1923 /* we did not get all the codec info, but we read too much data */
1924 if (read_size >= MAX_READ_SIZE) {
1930 /* NOTE: a new stream can be added there if no header in file
1931 (AVFMTCTX_NOHEADER) */
1932 ret = av_read_frame_internal(ic, &pkt1);
1935 ret = -1; /* we could not have all the codec parameters before EOF */
1936 for(i=0;i<ic->nb_streams;i++) {
1937 st = ic->streams[i];
1938 if (!has_codec_parameters(st->codec)){
1940 avcodec_string(buf, sizeof(buf), st->codec, 0);
1941 av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
1945 if (i == ic->nb_streams)
1950 pktl = av_mallocz(sizeof(AVPacketList));
1952 ret = AVERROR_NOMEM;
1956 /* add the packet in the buffered packet list */
1958 ppktl = &pktl->next;
1963 /* duplicate the packet */
1964 if (av_dup_packet(pkt) < 0) {
1965 ret = AVERROR_NOMEM;
1969 read_size += pkt->size;
1971 st = ic->streams[pkt->stream_index];
1972 st->codec_info_duration += pkt->duration;
1973 if (pkt->duration != 0)
1974 st->codec_info_nb_frames++;
1977 int index= pkt->stream_index;
1978 int64_t last= last_dts[index];
1979 int64_t duration= pkt->dts - last;
1981 if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
1982 if(duration*duration_count[index]*10/9 < duration_sum[index]){
1983 duration_sum[index]= duration;
1984 duration_count[index]=1;
1986 int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
1987 duration_sum[index] += duration;
1988 duration_count[index]+= factor;
1990 if(st->codec_info_nb_frames == 0 && 0)
1991 st->codec_info_duration += duration;
1993 last_dts[pkt->stream_index]= pkt->dts;
1995 if(st->parser && st->parser->parser->split && !st->codec->extradata){
1996 int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
1998 st->codec->extradata_size= i;
1999 st->codec->extradata= av_malloc(st->codec->extradata_size);
2000 memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2004 /* if still no information, we try to open the codec and to
2005 decompress the frame. We try to avoid that in most cases as
2006 it takes longer and uses more memory. For MPEG4, we need to
2007 decompress for Quicktime. */
2008 if (!has_codec_parameters(st->codec) /*&&
2009 (st->codec->codec_id == CODEC_ID_FLV1 ||
2010 st->codec->codec_id == CODEC_ID_H264 ||
2011 st->codec->codec_id == CODEC_ID_H263 ||
2012 st->codec->codec_id == CODEC_ID_H261 ||
2013 st->codec->codec_id == CODEC_ID_VORBIS ||
2014 st->codec->codec_id == CODEC_ID_MJPEG ||
2015 st->codec->codec_id == CODEC_ID_PNG ||
2016 st->codec->codec_id == CODEC_ID_PAM ||
2017 st->codec->codec_id == CODEC_ID_PGM ||
2018 st->codec->codec_id == CODEC_ID_PGMYUV ||
2019 st->codec->codec_id == CODEC_ID_PBM ||
2020 st->codec->codec_id == CODEC_ID_PPM ||
2021 st->codec->codec_id == CODEC_ID_SHORTEN ||
2022 (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2023 try_decode_frame(st, pkt->data, pkt->size);
2025 if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2031 // close codecs which where opened in try_decode_frame()
2032 for(i=0;i<ic->nb_streams;i++) {
2033 st = ic->streams[i];
2034 if(st->codec->codec)
2035 avcodec_close(st->codec);
2037 for(i=0;i<ic->nb_streams;i++) {
2038 st = ic->streams[i];
2039 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2040 if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2041 st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2043 if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2044 st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2045 int64_t num, den, error, best_error;
2047 num= st->time_base.den*duration_count[i];
2048 den= st->time_base.num*duration_sum[i];
2050 best_error= INT64_MAX;
2051 for(j=1; j<60*12; j++){
2052 error= ABS(1001*12*num - 1001*j*den);
2053 if(error < best_error){
2055 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2058 for(j=24; j<=30; j+=6){
2059 error= ABS(1001*12*num - 1000*12*j*den);
2060 if(error < best_error){
2062 av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2067 /* set real frame rate info */
2068 /* compute the real frame rate for telecine */
2069 if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2070 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2071 st->codec->sub_id == 2) {
2072 if (st->codec_info_nb_frames >= 20) {
2073 float coded_frame_rate, est_frame_rate;
2074 est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2075 (double)st->codec_info_duration ;
2076 coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2078 printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2079 coded_frame_rate, est_frame_rate);
2081 /* if we detect that it could be a telecine, we
2082 signal it. It would be better to do it at a
2083 higher level as it can change in a film */
2084 if (coded_frame_rate >= 24.97 &&
2085 (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2086 st->r_frame_rate = (AVRational){24000, 1001};
2090 /* if no real frame rate, use the codec one */
2091 if (!st->r_frame_rate.num){
2092 st->r_frame_rate.num = st->codec->time_base.den;
2093 st->r_frame_rate.den = st->codec->time_base.num;
2098 av_estimate_timings(ic);
2100 /* correct DTS for b frame streams with no timestamps */
2101 for(i=0;i<ic->nb_streams;i++) {
2102 st = ic->streams[i];
2103 if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2105 ppktl = &ic->packet_buffer;
2107 if(ppkt1->stream_index != i)
2109 if(ppkt1->pkt->dts < 0)
2111 if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2113 ppkt1->pkt->dts -= delta;
2118 st->cur_dts -= delta;
2126 /*******************************************************/
2129 * start playing a network based stream (e.g. RTSP stream) at the
2132 int av_read_play(AVFormatContext *s)
2134 if (!s->iformat->read_play)
2135 return AVERROR_NOTSUPP;
2136 return s->iformat->read_play(s);
2140 * Pause a network based stream (e.g. RTSP stream).
2142 * Use av_read_play() to resume it.
2144 int av_read_pause(AVFormatContext *s)
2146 if (!s->iformat->read_pause)
2147 return AVERROR_NOTSUPP;
2148 return s->iformat->read_pause(s);
2152 * Close a media file (but not its codecs).
2154 * @param s media file handle
2156 void av_close_input_file(AVFormatContext *s)
2158 int i, must_open_file;
2161 /* free previous packet */
2162 if (s->cur_st && s->cur_st->parser)
2163 av_free_packet(&s->cur_pkt);
2165 if (s->iformat->read_close)
2166 s->iformat->read_close(s);
2167 for(i=0;i<s->nb_streams;i++) {
2168 /* free all data in a stream component */
2171 av_parser_close(st->parser);
2173 av_free(st->index_entries);
2174 av_free(st->codec->extradata);
2178 flush_packet_queue(s);
2180 if (s->iformat->flags & AVFMT_NOFILE) {
2183 if (must_open_file) {
2186 av_freep(&s->priv_data);
2191 * Add a new stream to a media file.
2193 * Can only be called in the read_header() function. If the flag
2194 * AVFMTCTX_NOHEADER is in the format context, then new streams
2195 * can be added in read_packet too.
2197 * @param s media file handle
2198 * @param id file format dependent stream id
2200 AVStream *av_new_stream(AVFormatContext *s, int id)
2204 if (s->nb_streams >= MAX_STREAMS)
2207 st = av_mallocz(sizeof(AVStream));
2211 st->codec= avcodec_alloc_context();
2213 /* no default bitrate if decoding */
2214 st->codec->bit_rate = 0;
2216 st->index = s->nb_streams;
2218 st->start_time = AV_NOPTS_VALUE;
2219 st->duration = AV_NOPTS_VALUE;
2220 st->cur_dts = AV_NOPTS_VALUE;
2222 /* default pts settings is MPEG like */
2223 av_set_pts_info(st, 33, 1, 90000);
2224 st->last_IP_pts = AV_NOPTS_VALUE;
2226 s->streams[s->nb_streams++] = st;
2230 /************************************************************/
2231 /* output media file */
2233 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2237 if (s->oformat->priv_data_size > 0) {
2238 s->priv_data = av_mallocz(s->oformat->priv_data_size);
2240 return AVERROR_NOMEM;
2242 s->priv_data = NULL;
2244 if (s->oformat->set_parameters) {
2245 ret = s->oformat->set_parameters(s, ap);
2253 * allocate the stream private data and write the stream header to an
2256 * @param s media file handle
2257 * @return 0 if OK. AVERROR_xxx if error.
2259 int av_write_header(AVFormatContext *s)
2264 // some sanity checks
2265 for(i=0;i<s->nb_streams;i++) {
2268 switch (st->codec->codec_type) {
2269 case CODEC_TYPE_AUDIO:
2270 if(st->codec->sample_rate<=0){
2271 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2275 case CODEC_TYPE_VIDEO:
2276 if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2277 av_log(s, AV_LOG_ERROR, "time base not set\n");
2280 if(st->codec->width<=0 || st->codec->height<=0){
2281 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2288 if(s->oformat->write_header){
2289 ret = s->oformat->write_header(s);
2294 /* init PTS generation */
2295 for(i=0;i<s->nb_streams;i++) {
2296 int64_t den = AV_NOPTS_VALUE;
2299 switch (st->codec->codec_type) {
2300 case CODEC_TYPE_AUDIO:
2301 den = (int64_t)st->time_base.num * st->codec->sample_rate;
2303 case CODEC_TYPE_VIDEO:
2304 den = (int64_t)st->time_base.num * st->codec->time_base.den;
2309 if (den != AV_NOPTS_VALUE) {
2311 return AVERROR_INVALIDDATA;
2312 av_frac_init(&st->pts, 0, 0, den);
2318 //FIXME merge with compute_pkt_fields
2319 static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2320 int b_frames = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames);
2321 int num, den, frame_size;
2323 // 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);
2325 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2328 /* duration field */
2329 if (pkt->duration == 0) {
2330 compute_frame_duration(&num, &den, st, NULL, pkt);
2332 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2336 //XXX/FIXME this is a temporary hack until all encoders output pts
2337 if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
2339 // pkt->pts= st->cur_dts;
2340 pkt->pts= st->pts.val;
2343 //calculate dts from pts
2344 if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2346 if(st->last_IP_pts == AV_NOPTS_VALUE){
2347 st->last_IP_pts= -pkt->duration;
2349 if(st->last_IP_pts < pkt->pts){
2350 pkt->dts= st->last_IP_pts;
2351 st->last_IP_pts= pkt->pts;
2358 if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2359 av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2362 if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2363 av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2367 // av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2368 st->cur_dts= pkt->dts;
2369 st->pts.val= pkt->dts;
2372 switch (st->codec->codec_type) {
2373 case CODEC_TYPE_AUDIO:
2374 frame_size = get_audio_frame_size(st->codec, pkt->size);
2376 /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2377 but it would be better if we had the real timestamps from the encoder */
2378 if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2379 av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2382 case CODEC_TYPE_VIDEO:
2383 av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2391 static void truncate_ts(AVStream *st, AVPacket *pkt){
2392 int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2395 // pkt->dts= 0; //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2397 pkt->pts &= pts_mask;
2398 pkt->dts &= pts_mask;
2402 * Write a packet to an output media file.
2404 * The packet shall contain one audio or video frame.
2406 * @param s media file handle
2407 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2408 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2410 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2414 ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2418 truncate_ts(s->streams[pkt->stream_index], pkt);
2420 ret= s->oformat->write_packet(s, pkt);
2422 ret= url_ferror(&s->pb);
2427 * interleave_packet implementation which will interleave per DTS.
2428 * packets with pkt->destruct == av_destruct_packet will be freed inside this function.
2429 * so they cannot be used after it, note calling av_free_packet() on them is still safe
2431 static int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2432 AVPacketList *pktl, **next_point, *this_pktl;
2434 int streams[MAX_STREAMS];
2437 AVStream *st= s->streams[ pkt->stream_index];
2439 // assert(pkt->destruct != av_destruct_packet); //FIXME
2441 this_pktl = av_mallocz(sizeof(AVPacketList));
2442 this_pktl->pkt= *pkt;
2443 if(pkt->destruct == av_destruct_packet)
2444 pkt->destruct= NULL; // non shared -> must keep original from being freed
2446 av_dup_packet(&this_pktl->pkt); //shared -> must dup
2448 next_point = &s->packet_buffer;
2450 AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2451 int64_t left= st2->time_base.num * (int64_t)st ->time_base.den;
2452 int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2453 if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2455 next_point= &(*next_point)->next;
2457 this_pktl->next= *next_point;
2458 *next_point= this_pktl;
2461 memset(streams, 0, sizeof(streams));
2462 pktl= s->packet_buffer;
2464 //av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2465 if(streams[ pktl->pkt.stream_index ] == 0)
2467 streams[ pktl->pkt.stream_index ]++;
2471 if(s->nb_streams == stream_count || (flush && stream_count)){
2472 pktl= s->packet_buffer;
2475 s->packet_buffer= pktl->next;
2479 av_init_packet(out);
2485 * Interleaves a AVPacket correctly so it can be muxed.
2486 * @param out the interleaved packet will be output here
2487 * @param in the input packet
2488 * @param flush 1 if no further packets are available as input and all
2489 * remaining packets should be output
2490 * @return 1 if a packet was output, 0 if no packet could be output,
2491 * < 0 if an error occured
2493 static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2494 if(s->oformat->interleave_packet)
2495 return s->oformat->interleave_packet(s, out, in, flush);
2497 return av_interleave_packet_per_dts(s, out, in, flush);
2501 * Writes a packet to an output media file ensuring correct interleaving.
2503 * The packet must contain one audio or video frame.
2504 * If the packets are already correctly interleaved the application should
2505 * call av_write_frame() instead as its slightly faster, its also important
2506 * to keep in mind that completly non interleaved input will need huge amounts
2507 * of memory to interleave with this, so its prefereable to interleave at the
2510 * @param s media file handle
2511 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2512 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2514 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2515 AVStream *st= s->streams[ pkt->stream_index];
2517 //FIXME/XXX/HACK drop zero sized packets
2518 if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2521 //av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2522 if(compute_pkt_fields2(st, pkt) < 0)
2525 if(pkt->dts == AV_NOPTS_VALUE)
2530 int ret= av_interleave_packet(s, &opkt, pkt, 0);
2531 if(ret<=0) //FIXME cleanup needed for ret<0 ?
2534 truncate_ts(s->streams[opkt.stream_index], &opkt);
2535 ret= s->oformat->write_packet(s, &opkt);
2537 av_free_packet(&opkt);
2542 if(url_ferror(&s->pb))
2543 return url_ferror(&s->pb);
2548 * @brief Write the stream trailer to an output media file and
2549 * free the file private data.
2551 * @param s media file handle
2552 * @return 0 if OK. AVERROR_xxx if error.
2554 int av_write_trailer(AVFormatContext *s)
2560 ret= av_interleave_packet(s, &pkt, NULL, 1);
2561 if(ret<0) //FIXME cleanup needed for ret<0 ?
2566 truncate_ts(s->streams[pkt.stream_index], &pkt);
2567 ret= s->oformat->write_packet(s, &pkt);
2569 av_free_packet(&pkt);
2573 if(url_ferror(&s->pb))
2577 if(s->oformat->write_trailer)
2578 ret = s->oformat->write_trailer(s);
2581 ret=url_ferror(&s->pb);
2582 for(i=0;i<s->nb_streams;i++)
2583 av_freep(&s->streams[i]->priv_data);
2584 av_freep(&s->priv_data);
2588 /* "user interface" functions */
2590 void dump_format(AVFormatContext *ic,
2598 av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2599 is_output ? "Output" : "Input",
2601 is_output ? ic->oformat->name : ic->iformat->name,
2602 is_output ? "to" : "from", url);
2604 av_log(NULL, AV_LOG_INFO, " Duration: ");
2605 if (ic->duration != AV_NOPTS_VALUE) {
2606 int hours, mins, secs, us;
2607 secs = ic->duration / AV_TIME_BASE;
2608 us = ic->duration % AV_TIME_BASE;
2613 av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2614 (10 * us) / AV_TIME_BASE);
2616 av_log(NULL, AV_LOG_INFO, "N/A");
2618 if (ic->start_time != AV_NOPTS_VALUE) {
2620 av_log(NULL, AV_LOG_INFO, ", start: ");
2621 secs = ic->start_time / AV_TIME_BASE;
2622 us = ic->start_time % AV_TIME_BASE;
2623 av_log(NULL, AV_LOG_INFO, "%d.%06d",
2624 secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2626 av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2628 av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2630 av_log(NULL, AV_LOG_INFO, "N/A");
2632 av_log(NULL, AV_LOG_INFO, "\n");
2634 for(i=0;i<ic->nb_streams;i++) {
2635 AVStream *st = ic->streams[i];
2636 int g= ff_gcd(st->time_base.num, st->time_base.den);
2637 avcodec_string(buf, sizeof(buf), st->codec, is_output);
2638 av_log(NULL, AV_LOG_INFO, " Stream #%d.%d", index, i);
2639 /* the pid is an important information, so we display it */
2640 /* XXX: add a generic system */
2642 flags = ic->oformat->flags;
2644 flags = ic->iformat->flags;
2645 if (flags & AVFMT_SHOW_IDS) {
2646 av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2648 if (strlen(st->language) > 0) {
2649 av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2651 av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2652 av_log(NULL, AV_LOG_INFO, ": %s", buf);
2653 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2654 if(st->r_frame_rate.den && st->r_frame_rate.num)
2655 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2656 /* else if(st->time_base.den && st->time_base.num)
2657 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2659 av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2661 av_log(NULL, AV_LOG_INFO, "\n");
2668 int frame_rate, frame_rate_base;
2671 static AbvEntry frame_abvs[] = {
2672 { "ntsc", 720, 480, 30000, 1001 },
2673 { "pal", 720, 576, 25, 1 },
2674 { "qntsc", 352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2675 { "qpal", 352, 288, 25, 1 }, /* VCD compliant pal */
2676 { "sntsc", 640, 480, 30000, 1001 }, /* square pixel ntsc */
2677 { "spal", 768, 576, 25, 1 }, /* square pixel pal */
2678 { "film", 352, 240, 24, 1 },
2679 { "ntsc-film", 352, 240, 24000, 1001 },
2680 { "sqcif", 128, 96, 0, 0 },
2681 { "qcif", 176, 144, 0, 0 },
2682 { "cif", 352, 288, 0, 0 },
2683 { "4cif", 704, 576, 0, 0 },
2687 * parses width and height out of string str.
2689 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2692 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2694 int frame_width = 0, frame_height = 0;
2697 if (!strcmp(frame_abvs[i].abv, str)) {
2698 frame_width = frame_abvs[i].width;
2699 frame_height = frame_abvs[i].height;
2705 frame_width = strtol(p, (char **)&p, 10);
2708 frame_height = strtol(p, (char **)&p, 10);
2710 if (frame_width <= 0 || frame_height <= 0)
2712 *width_ptr = frame_width;
2713 *height_ptr = frame_height;
2718 * Converts frame rate from string to a fraction.
2720 * First we try to get an exact integer or fractional frame rate.
2721 * If this fails we convert the frame rate to a double and return
2722 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2724 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2729 /* First, we check our abbreviation table */
2730 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2731 if (!strcmp(frame_abvs[i].abv, arg)) {
2732 *frame_rate = frame_abvs[i].frame_rate;
2733 *frame_rate_base = frame_abvs[i].frame_rate_base;
2737 /* Then, we try to parse it as fraction */
2738 cp = strchr(arg, '/');
2740 cp = strchr(arg, ':');
2743 *frame_rate = strtol(arg, &cpp, 10);
2744 if (cpp != arg || cpp == cp)
2745 *frame_rate_base = strtol(cp+1, &cpp, 10);
2750 /* Finally we give up and parse it as double */
2751 AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2752 *frame_rate_base = time_base.den;
2753 *frame_rate = time_base.num;
2755 if (!*frame_rate || !*frame_rate_base)
2762 * Converts date string to number of seconds since Jan 1st, 1970.
2766 * - If not a duration:
2767 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2768 * Time is localtime unless Z is suffixed to the end. In this case GMT
2769 * Return the date in micro seconds since 1970
2772 * HH[:MM[:SS[.m...]]]
2776 #ifndef CONFIG_WINCE
2777 int64_t parse_date(const char *datestr, int duration)
2783 static const char *date_fmt[] = {
2787 static const char *time_fmt[] = {
2797 time_t now = time(0);
2799 len = strlen(datestr);
2801 lastch = datestr[len - 1];
2804 is_utc = (lastch == 'z' || lastch == 'Z');
2806 memset(&dt, 0, sizeof(dt));
2811 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2812 q = small_strptime(p, date_fmt[i], &dt);
2822 dt = *localtime(&now);
2824 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2829 if (*p == 'T' || *p == 't' || *p == ' ')
2832 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2833 q = small_strptime(p, time_fmt[i], &dt);
2843 q = small_strptime(p, time_fmt[0], &dt);
2845 dt.tm_sec = strtol(p, (char **)&q, 10);
2851 /* Now we have all the fields that we can get */
2856 return now * int64_t_C(1000000);
2860 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2862 dt.tm_isdst = -1; /* unknown */
2875 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2878 val += n * (*q - '0');
2882 return negative ? -t : t;
2884 #endif /* CONFIG_WINCE */
2887 * Attempts to find a specific tag in a URL.
2889 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2890 * Return 1 if found.
2892 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2902 while (*p != '\0' && *p != '=' && *p != '&') {
2903 if ((q - tag) < sizeof(tag) - 1)
2911 while (*p != '&' && *p != '\0') {
2912 if ((q - arg) < arg_size - 1) {
2922 if (!strcmp(tag, tag1))
2932 * Returns in 'buf' the path with '%d' replaced by number.
2934 * Also handles the '%0nd' format where 'n' is the total number
2935 * of digits and '%%'. Return 0 if OK, and -1 if format error.
2937 int get_frame_filename(char *buf, int buf_size,
2938 const char *path, int number)
2941 char *q, buf1[20], c;
2942 int nd, len, percentd_found;
2954 while (isdigit(*p)) {
2955 nd = nd * 10 + *p++ - '0';
2958 } while (isdigit(c));
2967 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2969 if ((q - buf + len) > buf_size - 1)
2971 memcpy(q, buf1, len);
2979 if ((q - buf) < buf_size - 1)
2983 if (!percentd_found)
2993 * Print nice hexa dump of a buffer
2994 * @param f stream for output
2996 * @param size buffer size
2998 void av_hex_dump(FILE *f, uint8_t *buf, int size)
3002 for(i=0;i<size;i+=16) {
3006 fprintf(f, "%08x ", i);
3009 fprintf(f, " %02x", buf[i+j]);
3014 for(j=0;j<len;j++) {
3016 if (c < ' ' || c > '~')
3018 fprintf(f, "%c", c);
3025 * Print on 'f' a nice dump of a packet
3026 * @param f stream for output
3027 * @param pkt packet to dump
3028 * @param dump_payload true if the payload must be displayed too
3030 //FIXME needs to know the time_base
3031 void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3033 fprintf(f, "stream #%d:\n", pkt->stream_index);
3034 fprintf(f, " keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3035 fprintf(f, " duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3036 /* DTS is _always_ valid after av_read_frame() */
3037 fprintf(f, " dts=");
3038 if (pkt->dts == AV_NOPTS_VALUE)
3041 fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3042 /* PTS may be not known if B frames are present */
3043 fprintf(f, " pts=");
3044 if (pkt->pts == AV_NOPTS_VALUE)
3047 fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3049 fprintf(f, " size=%d\n", pkt->size);
3051 av_hex_dump(f, pkt->data, pkt->size);
3054 void url_split(char *proto, int proto_size,
3055 char *authorization, int authorization_size,
3056 char *hostname, int hostname_size,
3058 char *path, int path_size,
3069 while (*p != ':' && *p != '\0') {
3070 if ((q - proto) < proto_size - 1)
3076 if (authorization_size > 0)
3077 authorization[0] = '\0';
3081 if (hostname_size > 0)
3085 char *at,*slash; // PETR: position of '@' character and '/' character
3092 at = strchr(p,'@'); // PETR: get the position of '@'
3093 slash = strchr(p,'/'); // PETR: get position of '/' - end of hostname
3094 if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3096 q = at ? authorization : hostname; // PETR: if '@' exists starting with auth.
3098 while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3099 if (*p == '@') { // PETR: passed '@'
3100 if (authorization_size > 0)
3104 } else if (!at) { // PETR: hostname
3105 if ((q - hostname) < hostname_size - 1)
3108 if ((q - authorization) < authorization_size - 1)
3113 if (hostname_size > 0)
3117 port = strtoul(p, (char **)&p, 10);
3122 pstrcpy(path, path_size, p);
3126 * Set the pts for a given stream.
3129 * @param pts_wrap_bits number of bits effectively used by the pts
3130 * (used for wrap control, 33 is the value for MPEG)
3131 * @param pts_num numerator to convert to seconds (MPEG: 1)
3132 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3134 void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3135 int pts_num, int pts_den)
3137 s->pts_wrap_bits = pts_wrap_bits;
3138 s->time_base.num = pts_num;
3139 s->time_base.den = pts_den;
3142 /* fraction handling */
3145 * f = val + (num / den) + 0.5.
3147 * 'num' is normalized so that it is such as 0 <= num < den.
3149 * @param f fractional number
3150 * @param val integer value
3151 * @param num must be >= 0
3152 * @param den must be >= 1
3154 static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3167 * Set f to (val + 0.5).
3169 static void av_frac_set(AVFrac *f, int64_t val)
3172 f->num = f->den >> 1;
3176 * Fractionnal addition to f: f = f + (incr / f->den).
3178 * @param f fractional number
3179 * @param incr increment, can be positive or negative
3181 static void av_frac_add(AVFrac *f, int64_t incr)
3185 num = f->num + incr;
3188 f->val += num / den;
3194 } else if (num >= den) {
3195 f->val += num / den;
3202 * register a new image format
3203 * @param img_fmt Image format descriptor
3205 void av_register_image_format(AVImageFormat *img_fmt)
3209 p = &first_image_format;
3210 while (*p != NULL) p = &(*p)->next;
3212 img_fmt->next = NULL;
3216 * Guesses image format based on data in the image.
3218 AVImageFormat *av_probe_image_format(AVProbeData *pd)
3220 AVImageFormat *fmt1, *fmt;
3221 int score, score_max;
3225 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3226 if (fmt1->img_probe) {
3227 score = fmt1->img_probe(pd);
3228 if (score > score_max) {
3238 * Guesses image format based on file name extensions.
3240 AVImageFormat *guess_image_format(const char *filename)
3242 AVImageFormat *fmt1;
3244 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3245 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3252 * Read an image from a stream.
3253 * @param gb byte stream containing the image
3254 * @param fmt image format, NULL if probing is required
3256 int av_read_image(ByteIOContext *pb, const char *filename,
3258 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3260 uint8_t buf[PROBE_BUF_MIN];
3261 AVProbeData probe_data, *pd = &probe_data;
3266 pd->filename = filename;
3268 pos = url_ftell(pb);
3269 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
3270 url_fseek(pb, pos, SEEK_SET);
3271 fmt = av_probe_image_format(pd);
3274 return AVERROR_NOFMT;
3275 ret = fmt->img_read(pb, alloc_cb, opaque);
3280 * Write an image to a stream.
3281 * @param pb byte stream for the image output
3282 * @param fmt image format
3283 * @param img image data and informations
3285 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3287 return fmt->img_write(pb, img);