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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #define strcasecmp _stricmp
23 #include <sys/types.h>
24 #include <sys/timeb.h>
25 #elif defined(CONFIG_OS2)
27 #define strcasecmp stricmp
40 AVInputFormat *first_iformat;
41 AVOutputFormat *first_oformat;
42 AVImageFormat *first_image_format;
44 void av_register_input_format(AVInputFormat *format)
48 while (*p != NULL) p = &(*p)->next;
53 void av_register_output_format(AVOutputFormat *format)
57 while (*p != NULL) p = &(*p)->next;
62 int match_ext(const char *filename, const char *extensions)
67 ext = strrchr(filename, '.');
73 while (*p != '\0' && *p != ',')
76 if (!strcasecmp(ext1, ext))
86 AVOutputFormat *guess_format(const char *short_name, const char *filename,
87 const char *mime_type)
89 AVOutputFormat *fmt, *fmt_found;
92 /* specific test for image sequences */
93 if (!short_name && filename &&
94 filename_number_test(filename) >= 0 &&
95 guess_image_format(filename)) {
96 return guess_format("image", NULL, NULL);
99 /* find the proper file type */
103 while (fmt != NULL) {
105 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
107 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
109 if (filename && fmt->extensions &&
110 match_ext(filename, fmt->extensions)) {
113 if (score > score_max) {
122 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
123 const char *mime_type)
125 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
128 AVOutputFormat *stream_fmt;
129 char stream_format_name[64];
131 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
132 stream_fmt = guess_format(stream_format_name, NULL, NULL);
141 AVInputFormat *av_find_input_format(const char *short_name)
144 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
145 if (!strcmp(fmt->name, short_name))
151 /* memory handling */
154 * Default packet destructor
156 static void av_destruct_packet(AVPacket *pkt)
159 pkt->data = NULL; pkt->size = 0;
163 * Allocate the payload of a packet and intialized its fields to default values.
166 * @param size wanted payload size
167 * @return 0 if OK. AVERROR_xxx otherwise.
169 int av_new_packet(AVPacket *pkt, int size)
171 void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
173 return AVERROR_NOMEM;
174 memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
179 pkt->destruct = av_destruct_packet;
185 int fifo_init(FifoBuffer *f, int size)
187 f->buffer = av_malloc(size);
190 f->end = f->buffer + size;
191 f->wptr = f->rptr = f->buffer;
195 void fifo_free(FifoBuffer *f)
200 int fifo_size(FifoBuffer *f, uint8_t *rptr)
204 if (f->wptr >= rptr) {
205 size = f->wptr - rptr;
207 size = (f->end - rptr) + (f->wptr - f->buffer);
212 /* get data from the fifo (return -1 if not enough data) */
213 int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
215 uint8_t *rptr = *rptr_ptr;
218 if (f->wptr >= rptr) {
219 size = f->wptr - rptr;
221 size = (f->end - rptr) + (f->wptr - f->buffer);
226 while (buf_size > 0) {
230 memcpy(buf, rptr, len);
241 void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
250 memcpy(wptr, buf, len);
260 int filename_number_test(const char *filename)
263 return get_frame_filename(buf, sizeof(buf), filename, 1);
266 /* guess file format */
267 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
269 AVInputFormat *fmt1, *fmt;
270 int score, score_max;
274 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
275 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
278 if (fmt1->read_probe) {
279 score = fmt1->read_probe(pd);
280 } else if (fmt1->extensions) {
281 if (match_ext(pd->filename, fmt1->extensions)) {
285 if (score > score_max) {
293 /************************************************************/
294 /* input media file */
296 #define PROBE_BUF_SIZE 2048
299 * Open a media file as input. The codec are not opened. Only the file
300 * header (if present) is read.
302 * @param ic_ptr the opened media file handle is put here
303 * @param filename filename to open.
304 * @param fmt if non NULL, force the file format to use
305 * @param buf_size optional buffer size (zero if default is OK)
306 * @param ap additionnal parameters needed when opening the file (NULL if default)
307 * @return 0 if OK. AVERROR_xxx otherwise.
309 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
312 AVFormatParameters *ap)
314 AVFormatContext *ic = NULL;
315 int err, must_open_file;
316 char buf[PROBE_BUF_SIZE];
317 AVProbeData probe_data, *pd = &probe_data;
319 ic = av_mallocz(sizeof(AVFormatContext));
324 ic->duration = AV_NOPTS_VALUE;
325 ic->start_time = AV_NOPTS_VALUE;
326 pstrcpy(ic->filename, sizeof(ic->filename), filename);
327 pd->filename = ic->filename;
332 /* guess format if no file can be opened */
333 fmt = av_probe_input_format(pd, 0);
336 /* do not open file if the format does not need it. XXX: specific
337 hack needed to handle RTSP/TCP */
339 if ((fmt && (fmt->flags & AVFMT_NOFILE))
340 #ifdef CONFIG_NETWORK
341 || (fmt == &rtp_demux && !strcmp(filename, "null"))
347 if (!fmt || must_open_file) {
348 /* if no file needed do not try to open one */
349 if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
354 url_setbufsize(&ic->pb, buf_size);
357 /* read probe data */
358 pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
359 url_fseek(&ic->pb, 0, SEEK_SET);
363 /* guess file format */
365 fmt = av_probe_input_format(pd, 1);
368 /* if still no format found, error */
374 /* XXX: suppress this hack for redirectors */
375 #ifdef CONFIG_NETWORK
376 if (fmt == &redir_demux) {
377 err = redir_open(ic_ptr, &ic->pb);
386 /* check filename in case of an image number is expected */
387 if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
388 if (filename_number_test(ic->filename) < 0) {
389 err = AVERROR_NUMEXPECTED;
394 /* allocate private data */
395 if (fmt->priv_data_size > 0) {
396 ic->priv_data = av_mallocz(fmt->priv_data_size);
397 if (!ic->priv_data) {
402 ic->priv_data = NULL;
404 /* default pts settings is MPEG like */
405 av_set_pts_info(ic, 33, 1, 90000);
407 err = ic->iformat->read_header(ic, ap);
413 if (!fmt || must_open_file) {
418 av_freep(&ic->priv_data);
426 * Read a packet from a media file
427 * @param s media file handle
428 * @param pkt is filled
429 * @return 0 if OK. AVERROR_xxx if error.
431 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
435 pktl = s->packet_buffer;
437 /* read packet from packet buffer, if there is data */
439 s->packet_buffer = pktl->next;
443 return s->iformat->read_packet(s, pkt);
448 /* return TRUE if the stream has accurate timings for at least one component */
449 static int av_has_timings(AVFormatContext *ic)
454 for(i = 0;i < ic->nb_streams; i++) {
456 if (st->start_time != AV_NOPTS_VALUE &&
457 st->duration != AV_NOPTS_VALUE)
463 /* estimate the stream timings from the one of each components. Also
464 compute the global bitrate if possible */
465 static void av_update_stream_timings(AVFormatContext *ic)
467 int64_t start_time, end_time, end_time1;
471 start_time = MAXINT64;
473 for(i = 0;i < ic->nb_streams; i++) {
475 if (st->start_time != AV_NOPTS_VALUE) {
476 if (st->start_time < start_time)
477 start_time = st->start_time;
478 if (st->duration != AV_NOPTS_VALUE) {
479 end_time1 = st->start_time + st->duration;
480 if (end_time1 > end_time)
481 end_time = end_time1;
485 if (start_time != MAXINT64) {
486 ic->start_time = start_time;
487 if (end_time != MAXINT64) {
488 ic->duration = end_time - start_time;
489 if (ic->file_size > 0) {
490 /* compute the bit rate */
491 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
492 (double)ic->duration;
499 static void fill_all_stream_timings(AVFormatContext *ic)
504 av_update_stream_timings(ic);
505 for(i = 0;i < ic->nb_streams; i++) {
507 if (st->start_time == AV_NOPTS_VALUE) {
508 st->start_time = ic->start_time;
509 st->duration = ic->duration;
514 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
516 int64_t filesize, duration;
520 /* if bit_rate is already set, we believe it */
521 if (ic->bit_rate == 0) {
523 for(i=0;i<ic->nb_streams;i++) {
525 bit_rate += st->codec.bit_rate;
527 ic->bit_rate = bit_rate;
530 /* if duration is already set, we believe it */
531 if (ic->duration == AV_NOPTS_VALUE &&
533 ic->file_size != 0) {
534 filesize = ic->file_size;
536 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
537 for(i = 0; i < ic->nb_streams; i++) {
539 if (st->start_time == AV_NOPTS_VALUE ||
540 st->duration == AV_NOPTS_VALUE) {
542 st->duration = duration;
549 static void flush_packet_queue(AVFormatContext *s)
554 pktl = s->packet_buffer;
557 s->packet_buffer = pktl->next;
562 #define DURATION_MAX_READ_SIZE 250000
564 /* only usable for MPEG-PS streams */
565 static void av_estimate_timings_from_pts(AVFormatContext *ic)
567 AVPacket pkt1, *pkt = &pkt1;
569 int read_size, i, ret;
570 int64_t start_time, end_time, end_time1;
571 int64_t filesize, offset, duration;
573 /* we read the first packets to get the first PTS (not fully
574 accurate, but it is enough now) */
575 url_fseek(&ic->pb, 0, SEEK_SET);
578 if (read_size >= DURATION_MAX_READ_SIZE)
580 /* if all info is available, we can stop */
581 for(i = 0;i < ic->nb_streams; i++) {
583 if (st->start_time == AV_NOPTS_VALUE)
586 if (i == ic->nb_streams)
589 ret = av_read_packet(ic, pkt);
592 read_size += pkt->size;
593 st = ic->streams[pkt->stream_index];
594 if (pkt->pts != AV_NOPTS_VALUE) {
595 if (st->start_time == AV_NOPTS_VALUE)
596 st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
601 /* we compute the minimum start_time and use it as default */
602 start_time = MAXINT64;
603 for(i = 0; i < ic->nb_streams; i++) {
605 if (st->start_time != AV_NOPTS_VALUE &&
606 st->start_time < start_time)
607 start_time = st->start_time;
609 if (start_time != MAXINT64)
610 ic->start_time = start_time;
612 /* estimate the end time (duration) */
613 /* XXX: may need to support wrapping */
614 filesize = ic->file_size;
615 offset = filesize - DURATION_MAX_READ_SIZE;
619 /* flush packet queue */
620 flush_packet_queue(ic);
622 url_fseek(&ic->pb, offset, SEEK_SET);
625 if (read_size >= DURATION_MAX_READ_SIZE)
627 /* if all info is available, we can stop */
628 for(i = 0;i < ic->nb_streams; i++) {
630 if (st->duration == AV_NOPTS_VALUE)
633 if (i == ic->nb_streams)
636 ret = av_read_packet(ic, pkt);
639 read_size += pkt->size;
640 st = ic->streams[pkt->stream_index];
641 if (pkt->pts != AV_NOPTS_VALUE) {
642 end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
643 duration = end_time - st->start_time;
645 if (st->duration == AV_NOPTS_VALUE ||
646 st->duration < duration)
647 st->duration = duration;
653 /* estimate total duration */
655 for(i = 0;i < ic->nb_streams; i++) {
657 if (st->duration != AV_NOPTS_VALUE) {
658 end_time1 = st->start_time + st->duration;
659 if (end_time1 > end_time)
660 end_time = end_time1;
664 /* update start_time (new stream may have been created, so we do
666 if (ic->start_time != AV_NOPTS_VALUE) {
667 for(i = 0; i < ic->nb_streams; i++) {
669 if (st->start_time == AV_NOPTS_VALUE)
670 st->start_time = ic->start_time;
674 if (end_time != MININT64) {
675 /* put dummy values for duration if needed */
676 for(i = 0;i < ic->nb_streams; i++) {
678 if (st->duration == AV_NOPTS_VALUE &&
679 st->start_time != AV_NOPTS_VALUE)
680 st->duration = end_time - st->start_time;
682 ic->duration = end_time - ic->start_time;
685 url_fseek(&ic->pb, 0, SEEK_SET);
688 static void av_estimate_timings(AVFormatContext *ic)
693 /* get the file size, if possible */
694 if (ic->iformat->flags & AVFMT_NOFILE) {
697 h = url_fileno(&ic->pb);
698 file_size = url_filesize(h);
702 ic->file_size = file_size;
704 if (ic->iformat == &mpegps_demux) {
705 /* get accurate estimate from the PTSes */
706 av_estimate_timings_from_pts(ic);
707 } else if (av_has_timings(ic)) {
708 /* at least one components has timings - we use them for all
710 fill_all_stream_timings(ic);
712 /* less precise: use bit rate info */
713 av_estimate_timings_from_bit_rate(ic);
715 av_update_stream_timings(ic);
721 for(i = 0;i < ic->nb_streams; i++) {
723 printf("%d: start_time: %0.3f duration: %0.3f\n",
724 i, (double)st->start_time / AV_TIME_BASE,
725 (double)st->duration / AV_TIME_BASE);
727 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
728 (double)ic->start_time / AV_TIME_BASE,
729 (double)ic->duration / AV_TIME_BASE,
730 ic->bit_rate / 1000);
735 /* state for codec information */
736 #define CSTATE_NOTFOUND 0
737 #define CSTATE_DECODING 1
738 #define CSTATE_FOUND 2
740 static int has_codec_parameters(AVCodecContext *enc)
743 switch(enc->codec_type) {
744 case CODEC_TYPE_AUDIO:
745 val = enc->sample_rate;
747 case CODEC_TYPE_VIDEO:
758 * Read the beginning of a media file to get stream information. This
759 * is useful for file formats with no headers such as MPEG. This
760 * function also compute the real frame rate in case of mpeg2 repeat
763 * @param ic media file handle
764 * @return >=0 if OK. AVERROR_xxx if error.
766 int av_find_stream_info(AVFormatContext *ic)
768 int i, count, ret, got_picture, size, read_size;
773 AVPacketList *pktl=NULL, **ppktl;
774 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
776 int min_read_size, max_read_size;
778 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
779 Mbits. We read at most 0.2 second of file to find all streams */
781 /* XXX: base it on stream bitrate when possible */
782 if (ic->iformat == &mpegts_demux) {
783 /* maximum number of bytes we accept to read to find all the streams
785 min_read_size = 6000000;
787 min_read_size = 250000;
789 /* max read size is 2 seconds of video max */
790 max_read_size = min_read_size * 10;
792 /* set initial codec state */
793 for(i=0;i<ic->nb_streams;i++) {
795 if (has_codec_parameters(&st->codec))
796 st->codec_info_state = CSTATE_FOUND;
798 st->codec_info_state = CSTATE_NOTFOUND;
799 st->codec_info_nb_repeat_frames = 0;
800 st->codec_info_nb_real_frames = 0;
805 ppktl = &ic->packet_buffer;
807 /* check if one codec still needs to be handled */
808 for(i=0;i<ic->nb_streams;i++) {
810 if (st->codec_info_state != CSTATE_FOUND)
813 if (i == ic->nb_streams) {
814 /* NOTE: if the format has no header, then we need to read
815 some packets to get most of the streams, so we cannot
817 if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
818 read_size >= min_read_size) {
819 /* if we found the info for all the codecs, we can stop */
824 /* we did not get all the codec info, but we read too much data */
825 if (read_size >= max_read_size) {
831 pktl = av_mallocz(sizeof(AVPacketList));
837 /* add the packet in the buffered packet list */
841 /* NOTE: a new stream can be added there if no header in file
844 if (ic->iformat->read_packet(ic, pkt) < 0) {
846 ret = -1; /* we could not have all the codec parameters before EOF */
847 if ((ic->iformat->flags & AVFMT_NOHEADER) &&
852 read_size += pkt->size;
854 /* open new codecs */
855 for(i=0;i<ic->nb_streams;i++) {
857 if (st->codec_info_state == CSTATE_NOTFOUND) {
858 /* set to found in case of error */
859 st->codec_info_state = CSTATE_FOUND;
860 codec = avcodec_find_decoder(st->codec.codec_id);
862 if(codec->capabilities & CODEC_CAP_TRUNCATED)
863 st->codec.flags |= CODEC_FLAG_TRUNCATED;
865 ret = avcodec_open(&st->codec, codec);
867 st->codec_info_state = CSTATE_DECODING;
872 st = ic->streams[pkt->stream_index];
873 if (st->codec_info_state == CSTATE_DECODING) {
874 /* decode the data and update codec parameters */
878 switch(st->codec.codec_type) {
879 case CODEC_TYPE_VIDEO:
880 ret = avcodec_decode_video(&st->codec, &picture,
881 &got_picture, ptr, size);
883 case CODEC_TYPE_AUDIO:
884 ret = avcodec_decode_audio(&st->codec, samples,
885 &got_picture, ptr, size);
892 /* if error, simply ignore because another packet
897 /* we got the parameters - now we can stop
898 examining this stream */
899 /* XXX: add a codec info so that we can decide if
900 the codec can repeat frames */
901 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
902 ic->iformat != &mpegts_demux &&
903 st->codec.sub_id == 2) {
904 /* for mpeg2 video, we want to know the real
905 frame rate, so we decode 40 frames. In mpeg
906 TS case we do not do it because it would be
908 st->codec_info_nb_real_frames++;
909 st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
912 if ((st->codec_info_nb_real_frames % 24) == 23) {
913 st->codec_info_nb_repeat_frames += 2;
916 /* stop after 40 frames */
917 if (st->codec_info_nb_real_frames >= 40) {
920 &st->r_frame_rate_base,
921 (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
922 (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
928 st->codec_info_state = CSTATE_FOUND;
929 avcodec_close(&st->codec);
940 /* close each codec if there are opened */
941 for(i=0;i<ic->nb_streams;i++) {
943 if (st->codec_info_state == CSTATE_DECODING)
944 avcodec_close(&st->codec);
947 /* set real frame rate info */
948 for(i=0;i<ic->nb_streams;i++) {
950 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
951 if (!st->r_frame_rate){
952 st->r_frame_rate = st->codec.frame_rate;
953 st->r_frame_rate_base = st->codec.frame_rate_base;
959 av_estimate_timings(ic);
964 * Close a media file (but not its codecs)
966 * @param s media file handle
968 void av_close_input_file(AVFormatContext *s)
970 int i, must_open_file;
972 if (s->iformat->read_close)
973 s->iformat->read_close(s);
974 for(i=0;i<s->nb_streams;i++) {
975 av_free(s->streams[i]);
977 if (s->packet_buffer) {
978 AVPacketList *p, *p1;
979 p = s->packet_buffer;
982 av_free_packet(&p->pkt);
986 s->packet_buffer = NULL;
989 if ((s->iformat->flags & AVFMT_NOFILE)
990 #ifdef CONFIG_NETWORK
991 || (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))
996 if (must_open_file) {
999 av_freep(&s->priv_data);
1004 * Add a new stream to a media file. Can only be called in the
1005 * read_header function. If the flag AVFMT_NOHEADER is in the format
1006 * description, then new streams can be added in read_packet too.
1009 * @param s media file handle
1010 * @param id file format dependent stream id
1012 AVStream *av_new_stream(AVFormatContext *s, int id)
1016 if (s->nb_streams >= MAX_STREAMS)
1019 st = av_mallocz(sizeof(AVStream));
1022 avcodec_get_context_defaults(&st->codec);
1024 /* no default bitrate if decoding */
1025 st->codec.bit_rate = 0;
1027 st->index = s->nb_streams;
1029 st->start_time = AV_NOPTS_VALUE;
1030 st->duration = AV_NOPTS_VALUE;
1031 s->streams[s->nb_streams++] = st;
1035 /************************************************************/
1036 /* output media file */
1038 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1042 if (s->oformat->priv_data_size > 0) {
1043 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1045 return AVERROR_NOMEM;
1047 s->priv_data = NULL;
1049 if (s->oformat->set_parameters) {
1050 ret = s->oformat->set_parameters(s, ap);
1058 * allocate the stream private data and write the stream header to an
1061 * @param s media file handle
1062 * @return 0 if OK. AVERROR_xxx if error.
1064 int av_write_header(AVFormatContext *s)
1069 /* default pts settings is MPEG like */
1070 av_set_pts_info(s, 33, 1, 90000);
1071 ret = s->oformat->write_header(s);
1075 /* init PTS generation */
1076 for(i=0;i<s->nb_streams;i++) {
1079 switch (st->codec.codec_type) {
1080 case CODEC_TYPE_AUDIO:
1081 av_frac_init(&st->pts, 0, 0,
1082 (int64_t)s->pts_num * st->codec.sample_rate);
1084 case CODEC_TYPE_VIDEO:
1085 av_frac_init(&st->pts, 0, 0,
1086 (int64_t)s->pts_num * st->codec.frame_rate);
1096 * Write a packet to an output media file. The packet shall contain
1097 * one audio or video frame.
1099 * @param s media file handle
1100 * @param stream_index stream index
1101 * @param buf buffer containing the frame data
1102 * @param size size of buffer
1103 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1105 int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
1110 int ret, frame_size;
1112 st = s->streams[stream_index];
1113 pts_mask = (1LL << s->pts_wrap_bits) - 1;
1114 ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
1115 st->pts.val & pts_mask);
1120 switch (st->codec.codec_type) {
1121 case CODEC_TYPE_AUDIO:
1122 if (st->codec.frame_size <= 1) {
1123 frame_size = size / st->codec.channels;
1124 /* specific hack for pcm codecs because no frame size is provided */
1125 switch(st->codec.codec_id) {
1126 case CODEC_ID_PCM_S16LE:
1127 case CODEC_ID_PCM_S16BE:
1128 case CODEC_ID_PCM_U16LE:
1129 case CODEC_ID_PCM_U16BE:
1136 frame_size = st->codec.frame_size;
1138 av_frac_add(&st->pts,
1139 (int64_t)s->pts_den * frame_size);
1141 case CODEC_TYPE_VIDEO:
1142 av_frac_add(&st->pts,
1143 (int64_t)s->pts_den * st->codec.frame_rate_base);
1152 * write the stream trailer to an output media file and and free the
1153 * file private data.
1155 * @param s media file handle
1156 * @return 0 if OK. AVERROR_xxx if error. */
1157 int av_write_trailer(AVFormatContext *s)
1160 ret = s->oformat->write_trailer(s);
1161 av_freep(&s->priv_data);
1165 /* "user interface" functions */
1167 void dump_format(AVFormatContext *ic,
1175 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
1176 is_output ? "Output" : "Input",
1178 is_output ? ic->oformat->name : ic->iformat->name,
1179 is_output ? "to" : "from", url);
1181 fprintf(stderr, " Duration: ");
1182 if (ic->duration != AV_NOPTS_VALUE) {
1183 int hours, mins, secs, us;
1184 secs = ic->duration / AV_TIME_BASE;
1185 us = ic->duration % AV_TIME_BASE;
1190 fprintf(stderr, "%02d:%02d:%02d.%01d", hours, mins, secs,
1191 (10 * us) / AV_TIME_BASE);
1193 fprintf(stderr, "N/A");
1195 fprintf(stderr, ", bitrate: ");
1197 fprintf(stderr,"%d kb/s", ic->bit_rate / 1000);
1199 fprintf(stderr, "N/A");
1201 fprintf(stderr, "\n");
1203 for(i=0;i<ic->nb_streams;i++) {
1204 AVStream *st = ic->streams[i];
1205 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
1206 fprintf(stderr, " Stream #%d.%d", index, i);
1207 /* the pid is an important information, so we display it */
1208 /* XXX: add a generic system */
1210 flags = ic->oformat->flags;
1212 flags = ic->iformat->flags;
1213 if (flags & AVFMT_SHOW_IDS) {
1214 fprintf(stderr, "[0x%x]", st->id);
1216 fprintf(stderr, ": %s\n", buf);
1223 int frame_rate, frame_rate_base;
1226 static AbvEntry frame_abvs[] = {
1227 { "ntsc", 352, 240, 30000, 1001 },
1228 { "pal", 352, 288, 25, 1 },
1229 { "film", 352, 240, 24, 1 },
1230 { "ntsc-film", 352, 240, 24000, 1001 },
1231 { "sqcif", 128, 96, 0, 0 },
1232 { "qcif", 176, 144, 0, 0 },
1233 { "cif", 352, 288, 0, 0 },
1234 { "4cif", 704, 576, 0, 0 },
1237 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1240 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1242 int frame_width = 0, frame_height = 0;
1245 if (!strcmp(frame_abvs[i].abv, str)) {
1246 frame_width = frame_abvs[i].width;
1247 frame_height = frame_abvs[i].height;
1253 frame_width = strtol(p, (char **)&p, 10);
1256 frame_height = strtol(p, (char **)&p, 10);
1258 if (frame_width <= 0 || frame_height <= 0)
1260 *width_ptr = frame_width;
1261 *height_ptr = frame_height;
1265 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1270 /* First, we check our abbreviation table */
1271 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1272 if (!strcmp(frame_abvs[i].abv, arg)) {
1273 *frame_rate = frame_abvs[i].frame_rate;
1274 *frame_rate_base = frame_abvs[i].frame_rate_base;
1278 /* Then, we try to parse it as fraction */
1279 cp = strchr(arg, '/');
1282 *frame_rate = strtol(arg, &cpp, 10);
1283 if (cpp != arg || cpp == cp)
1284 *frame_rate_base = strtol(cp+1, &cpp, 10);
1289 /* Finally we give up and parse it as double */
1290 *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1291 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1293 if (!*frame_rate || !*frame_rate_base)
1299 int64_t av_gettime(void)
1304 return ((int64_t)tb.time * int64_t_C(1000) + (int64_t)tb.millitm) * int64_t_C(1000);
1307 gettimeofday(&tv,NULL);
1308 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
1312 static time_t mktimegm(struct tm *tm)
1316 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
1324 (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
1326 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
1332 * - If not a duration:
1333 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1334 * Time is localtime unless Z is suffixed to the end. In this case GMT
1335 * Return the date in micro seconds since 1970
1337 * HH[:MM[:SS[.m...]]]
1340 int64_t parse_date(const char *datestr, int duration)
1346 static const char *date_fmt[] = {
1350 static const char *time_fmt[] = {
1357 time_t now = time(0);
1359 len = strlen(datestr);
1361 lastch = datestr[len - 1];
1364 is_utc = (lastch == 'z' || lastch == 'Z');
1366 memset(&dt, 0, sizeof(dt));
1371 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1372 q = strptime(p, date_fmt[i], &dt);
1382 dt = *localtime(&now);
1384 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1389 if (*p == 'T' || *p == 't' || *p == ' ')
1392 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1393 q = strptime(p, time_fmt[i], &dt);
1399 q = strptime(p, time_fmt[0], &dt);
1401 dt.tm_sec = strtol(p, (char **)&q, 10);
1407 /* Now we have all the fields that we can get */
1412 return now * int64_t_C(1000000);
1416 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1418 dt.tm_isdst = -1; /* unknown */
1431 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1434 val += n * (*q - '0');
1441 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1443 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1453 while (*p != '\0' && *p != '=' && *p != '&') {
1454 if ((q - tag) < sizeof(tag) - 1)
1462 while (*p != '&' && *p != '\0') {
1463 if ((q - arg) < arg_size - 1) {
1473 if (!strcmp(tag, tag1))
1482 /* Return in 'buf' the path with '%d' replaced by number. Also handles
1483 the '%0nd' format where 'n' is the total number of digits and
1484 '%%'. Return 0 if OK, and -1 if format error */
1485 int get_frame_filename(char *buf, int buf_size,
1486 const char *path, int number)
1490 int nd, len, c, percentd_found;
1502 while (isdigit(*p)) {
1503 nd = nd * 10 + *p++ - '0';
1506 } while (isdigit(c));
1515 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1517 if ((q - buf + len) > buf_size - 1)
1519 memcpy(q, buf1, len);
1527 if ((q - buf) < buf_size - 1)
1531 if (!percentd_found)
1542 * Print on stdout a nice hexa dump of a buffer
1544 * @param size buffer size
1546 void av_hex_dump(uint8_t *buf, int size)
1550 for(i=0;i<size;i+=16) {
1557 printf(" %02x", buf[i+j]);
1562 for(j=0;j<len;j++) {
1564 if (c < ' ' || c > '~')
1572 void url_split(char *proto, int proto_size,
1573 char *hostname, int hostname_size,
1575 char *path, int path_size,
1586 while (*p != ':' && *p != '\0') {
1587 if ((q - proto) < proto_size - 1)
1596 if (hostname_size > 0)
1606 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1607 if ((q - hostname) < hostname_size - 1)
1611 if (hostname_size > 0)
1615 port = strtoul(p, (char **)&p, 10);
1620 pstrcpy(path, path_size, p);
1624 * Set the pts for a given stream
1626 * @param pts_wrap_bits number of bits effectively used by the pts
1627 * (used for wrap control, 33 is the value for MPEG)
1628 * @param pts_num numerator to convert to seconds (MPEG: 1)
1629 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1631 void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1632 int pts_num, int pts_den)
1634 s->pts_wrap_bits = pts_wrap_bits;
1635 s->pts_num = pts_num;
1636 s->pts_den = pts_den;
1639 /* fraction handling */
1642 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1643 * as 0 <= num < den.
1645 * @param f fractional number
1646 * @param val integer value
1647 * @param num must be >= 0
1648 * @param den must be >= 1
1650 void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1662 /* set f to (val + 0.5) */
1663 void av_frac_set(AVFrac *f, int64_t val)
1666 f->num = f->den >> 1;
1670 * Fractionnal addition to f: f = f + (incr / f->den)
1672 * @param f fractional number
1673 * @param incr increment, can be positive or negative
1675 void av_frac_add(AVFrac *f, int64_t incr)
1679 num = f->num + incr;
1682 f->val += num / den;
1688 } else if (num >= den) {
1689 f->val += num / den;
1696 * register a new image format
1697 * @param img_fmt Image format descriptor
1699 void av_register_image_format(AVImageFormat *img_fmt)
1703 p = &first_image_format;
1704 while (*p != NULL) p = &(*p)->next;
1706 img_fmt->next = NULL;
1709 /* guess image format */
1710 AVImageFormat *av_probe_image_format(AVProbeData *pd)
1712 AVImageFormat *fmt1, *fmt;
1713 int score, score_max;
1717 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1718 if (fmt1->img_probe) {
1719 score = fmt1->img_probe(pd);
1720 if (score > score_max) {
1729 AVImageFormat *guess_image_format(const char *filename)
1731 AVImageFormat *fmt1;
1733 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1734 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1741 * Read an image from a stream.
1742 * @param gb byte stream containing the image
1743 * @param fmt image format, NULL if probing is required
1745 int av_read_image(ByteIOContext *pb, const char *filename,
1747 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1749 char buf[PROBE_BUF_SIZE];
1750 AVProbeData probe_data, *pd = &probe_data;
1755 pd->filename = filename;
1757 pos = url_ftell(pb);
1758 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1759 url_fseek(pb, pos, SEEK_SET);
1760 fmt = av_probe_image_format(pd);
1763 return AVERROR_NOFMT;
1764 ret = fmt->img_read(pb, alloc_cb, opaque);
1769 * Write an image to a stream.
1770 * @param pb byte stream for the image output
1771 * @param fmt image format
1772 * @param img image data and informations
1774 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1776 return fmt->img_write(pb, img);