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
26 #define strcasecmp _stricmp
27 #include <sys/types.h>
28 #include <sys/timeb.h>
36 AVInputFormat *first_iformat;
37 AVOutputFormat *first_oformat;
39 void av_register_input_format(AVInputFormat *format)
43 while (*p != NULL) p = &(*p)->next;
48 void av_register_output_format(AVOutputFormat *format)
52 while (*p != NULL) p = &(*p)->next;
57 int match_ext(const char *filename, const char *extensions)
62 ext = strrchr(filename, '.');
68 while (*p != '\0' && *p != ',')
71 if (!strcasecmp(ext1, ext))
81 AVOutputFormat *guess_format(const char *short_name, const char *filename,
82 const char *mime_type)
84 AVOutputFormat *fmt, *fmt_found;
87 /* find the proper file type */
93 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
95 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
97 if (filename && fmt->extensions &&
98 match_ext(filename, fmt->extensions)) {
101 if (score > score_max) {
110 AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
111 const char *mime_type)
113 AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
116 AVOutputFormat *stream_fmt;
117 char stream_format_name[64];
119 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
120 stream_fmt = guess_format(stream_format_name, NULL, NULL);
129 AVInputFormat *av_find_input_format(const char *short_name)
132 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
133 if (!strcmp(fmt->name, short_name))
139 /* memory handling */
142 * Allocate the payload of a packet and intialized its fields to default values.
145 * @param size wanted payload size
146 * @return 0 if OK. AVERROR_xxx otherwise.
148 int av_new_packet(AVPacket *pkt, int size)
151 pkt->data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
153 return AVERROR_NOMEM;
156 pkt->pts = AV_NOPTS_VALUE;
157 pkt->stream_index = 0;
160 for(i=0; i<FF_INPUT_BUFFER_PADDING_SIZE; i++)
161 pkt->data[size+i]= 0;
169 * @param pkt packet to free
171 void av_free_packet(AVPacket *pkt)
173 av_freep(&pkt->data);
180 int fifo_init(FifoBuffer *f, int size)
182 f->buffer = av_malloc(size);
185 f->end = f->buffer + size;
186 f->wptr = f->rptr = f->buffer;
190 void fifo_free(FifoBuffer *f)
195 int fifo_size(FifoBuffer *f, UINT8 *rptr)
199 if (f->wptr >= rptr) {
200 size = f->wptr - rptr;
202 size = (f->end - rptr) + (f->wptr - f->buffer);
207 /* get data from the fifo (return -1 if not enough data) */
208 int fifo_read(FifoBuffer *f, UINT8 *buf, int buf_size, UINT8 **rptr_ptr)
210 UINT8 *rptr = *rptr_ptr;
213 if (f->wptr >= rptr) {
214 size = f->wptr - rptr;
216 size = (f->end - rptr) + (f->wptr - f->buffer);
221 while (buf_size > 0) {
225 memcpy(buf, rptr, len);
236 void fifo_write(FifoBuffer *f, UINT8 *buf, int size, UINT8 **wptr_ptr)
245 memcpy(wptr, buf, len);
255 int filename_number_test(const char *filename)
258 return get_frame_filename(buf, sizeof(buf), filename, 1);
261 /* guess file format */
262 AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
264 AVInputFormat *fmt1, *fmt;
265 int score, score_max;
269 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
270 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
273 if (fmt1->read_probe) {
274 score = fmt1->read_probe(pd);
275 } else if (fmt1->extensions) {
276 if (match_ext(pd->filename, fmt1->extensions)) {
280 if (score > score_max) {
288 /************************************************************/
289 /* input media file */
291 #define PROBE_BUF_SIZE 2048
294 * Open a media file as input. The codec are not opened. Only the file
295 * header (if present) is read.
297 * @param ic_ptr the opened media file handle is put here
298 * @param filename filename to open.
299 * @param fmt if non NULL, force the file format to use
300 * @param buf_size optional buffer size (zero if default is OK)
301 * @param ap additionnal parameters needed when opening the file (NULL if default)
302 * @return 0 if OK. AVERROR_xxx otherwise.
304 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
307 AVFormatParameters *ap)
309 AVFormatContext *ic = NULL;
311 char buf[PROBE_BUF_SIZE];
312 AVProbeData probe_data, *pd = &probe_data;
314 ic = av_mallocz(sizeof(AVFormatContext));
319 pstrcpy(ic->filename, sizeof(ic->filename), filename);
320 pd->filename = ic->filename;
325 /* guess format if no file can be opened */
326 fmt = av_probe_input_format(pd, 0);
329 /* if no file needed do not try to open one */
330 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
331 if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
336 url_setbufsize(&ic->pb, buf_size);
339 /* read probe data */
340 pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
341 url_fseek(&ic->pb, 0, SEEK_SET);
345 /* guess file format */
347 fmt = av_probe_input_format(pd, 1);
350 /* if still no format found, error */
358 /* allocate private data */
359 ic->priv_data = av_mallocz(fmt->priv_data_size);
360 if (!ic->priv_data) {
365 /* default pts settings is MPEG like */
366 av_set_pts_info(ic, 33, 1, 90000);
368 /* check filename in case of an image number is expected */
369 if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
370 if (filename_number_test(ic->filename) < 0) {
371 err = AVERROR_NUMEXPECTED;
376 err = ic->iformat->read_header(ic, ap);
382 if (!(fmt->flags & AVFMT_NOFILE)) {
387 av_freep(&ic->priv_data);
395 * Read a packet from a media file
396 * @param s media file handle
397 * @param pkt is filled
398 * @return 0 if OK. AVERROR_xxx if error.
400 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
404 pktl = s->packet_buffer;
406 /* read packet from packet buffer, if there is data */
408 s->packet_buffer = pktl->next;
412 return s->iformat->read_packet(s, pkt);
416 /* state for codec information */
417 #define CSTATE_NOTFOUND 0
418 #define CSTATE_DECODING 1
419 #define CSTATE_FOUND 2
421 static int has_codec_parameters(AVCodecContext *enc)
424 switch(enc->codec_type) {
425 case CODEC_TYPE_AUDIO:
426 val = enc->sample_rate;
428 case CODEC_TYPE_VIDEO:
439 * Read the beginning of a media file to get stream information. This
440 * is useful for file formats with no headers such as MPEG. This
441 * function also compute the real frame rate in case of mpeg2 repeat
444 * @param ic media file handle
445 * @return >=0 if OK. AVERROR_xxx if error.
447 int av_find_stream_info(AVFormatContext *ic)
449 int i, count, ret, got_picture, size, read_size;
454 AVPacketList *pktl=NULL, **ppktl;
455 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
457 int min_read_size, max_read_size;
459 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
460 Mbits. We read at most 0.1 second of file to find all streams */
462 /* XXX: base it on stream bitrate when possible */
463 if (ic->iformat == &mpegts_demux) {
464 /* maximum number of bytes we accept to read to find all the streams
466 min_read_size = 3000000;
468 min_read_size = 125000;
470 /* max read size is 2 seconds of video max */
471 max_read_size = min_read_size * 20;
473 /* set initial codec state */
474 for(i=0;i<ic->nb_streams;i++) {
476 if (has_codec_parameters(&st->codec))
477 st->codec_info_state = CSTATE_FOUND;
479 st->codec_info_state = CSTATE_NOTFOUND;
480 st->codec_info_nb_repeat_frames = 0;
481 st->codec_info_nb_real_frames = 0;
486 ppktl = &ic->packet_buffer;
488 /* check if one codec still needs to be handled */
489 for(i=0;i<ic->nb_streams;i++) {
491 if (st->codec_info_state != CSTATE_FOUND)
494 if (i == ic->nb_streams) {
495 /* NOTE: if the format has no header, then we need to read
496 some packets to get most of the streams, so we cannot
498 if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
499 read_size >= min_read_size) {
500 /* if we found the info for all the codecs, we can stop */
505 /* we did not get all the codec info, but we read too much data */
506 if (read_size >= max_read_size) {
512 pktl = av_mallocz(sizeof(AVPacketList));
518 /* add the packet in the buffered packet list */
522 /* NOTE: a new stream can be added there if no header in file
525 if (ic->iformat->read_packet(ic, pkt) < 0) {
527 ret = -1; /* we could not have all the codec parameters before EOF */
528 if ((ic->iformat->flags & AVFMT_NOHEADER) &&
533 read_size += pkt->size;
535 /* open new codecs */
536 for(i=0;i<ic->nb_streams;i++) {
538 if (st->codec_info_state == CSTATE_NOTFOUND) {
539 /* set to found in case of error */
540 st->codec_info_state = CSTATE_FOUND;
541 codec = avcodec_find_decoder(st->codec.codec_id);
543 if(codec->capabilities & CODEC_CAP_TRUNCATED)
544 st->codec.flags |= CODEC_FLAG_TRUNCATED;
546 ret = avcodec_open(&st->codec, codec);
548 st->codec_info_state = CSTATE_DECODING;
553 st = ic->streams[pkt->stream_index];
554 if (st->codec_info_state == CSTATE_DECODING) {
555 /* decode the data and update codec parameters */
559 switch(st->codec.codec_type) {
560 case CODEC_TYPE_VIDEO:
561 ret = avcodec_decode_video(&st->codec, &picture,
562 &got_picture, ptr, size);
564 case CODEC_TYPE_AUDIO:
565 ret = avcodec_decode_audio(&st->codec, samples,
566 &got_picture, ptr, size);
573 /* if error, simply ignore because another packet
578 /* we got the parameters - now we can stop
579 examining this stream */
580 /* XXX: add a codec info so that we can decide if
581 the codec can repeat frames */
582 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
583 ic->iformat != &mpegts_demux &&
584 st->codec.sub_id == 2) {
585 /* for mpeg2 video, we want to know the real
586 frame rate, so we decode 40 frames. In mpeg
587 TS case we do not do it because it would be
589 st->codec_info_nb_real_frames++;
590 st->codec_info_nb_repeat_frames += st->codec.repeat_pict;
593 if ((st->codec_info_nb_real_frames % 24) == 23) {
594 st->codec_info_nb_repeat_frames += 2;
597 /* stop after 40 frames */
598 if (st->codec_info_nb_real_frames >= 40) {
599 st->r_frame_rate = (st->codec.frame_rate *
600 st->codec_info_nb_real_frames) /
601 (st->codec_info_nb_real_frames +
602 (st->codec_info_nb_repeat_frames >> 1));
607 st->codec_info_state = CSTATE_FOUND;
608 avcodec_close(&st->codec);
619 /* close each codec if there are opened */
620 for(i=0;i<ic->nb_streams;i++) {
622 if (st->codec_info_state == CSTATE_DECODING)
623 avcodec_close(&st->codec);
626 /* set real frame rate info */
627 for(i=0;i<ic->nb_streams;i++) {
629 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
630 if (!st->r_frame_rate)
631 st->r_frame_rate = st->codec.frame_rate;
639 * Close a media file (but not its codecs)
641 * @param s media file handle
643 void av_close_input_file(AVFormatContext *s)
647 if (s->iformat->read_close)
648 s->iformat->read_close(s);
649 for(i=0;i<s->nb_streams;i++) {
650 av_free(s->streams[i]);
652 if (s->packet_buffer) {
653 AVPacketList *p, *p1;
654 p = s->packet_buffer;
657 av_free_packet(&p->pkt);
661 s->packet_buffer = NULL;
663 if (!(s->iformat->flags & AVFMT_NOFILE)) {
666 av_freep(&s->priv_data);
671 * Add a new stream to a media file. Can only be called in the
672 * read_header function. If the flag AVFMT_NOHEADER is in the format
673 * description, then new streams can be added in read_packet too.
676 * @param s media file handle
677 * @param id file format dependent stream id
679 AVStream *av_new_stream(AVFormatContext *s, int id)
683 if (s->nb_streams >= MAX_STREAMS)
686 st = av_mallocz(sizeof(AVStream));
689 st->index = s->nb_streams;
691 s->streams[s->nb_streams++] = st;
695 /************************************************************/
696 /* output media file */
699 * allocate the stream private data and write the stream header to an
702 * @param s media file handle
703 * @return 0 if OK. AVERROR_xxx if error.
705 int av_write_header(AVFormatContext *s)
710 s->priv_data = av_mallocz(s->oformat->priv_data_size);
712 return AVERROR_NOMEM;
713 /* default pts settings is MPEG like */
714 av_set_pts_info(s, 33, 1, 90000);
715 ret = s->oformat->write_header(s);
719 /* init PTS generation */
720 for(i=0;i<s->nb_streams;i++) {
723 switch (st->codec.codec_type) {
724 case CODEC_TYPE_AUDIO:
725 av_frac_init(&st->pts, 0, 0,
726 (INT64)s->pts_num * st->codec.sample_rate);
728 case CODEC_TYPE_VIDEO:
729 av_frac_init(&st->pts, 0, 0,
730 (INT64)s->pts_num * st->codec.frame_rate);
740 * Write a packet to an output media file. The packet shall contain
741 * one audio or video frame.
743 * @param s media file handle
744 * @param stream_index stream index
745 * @param buf buffer containing the frame data
746 * @param size size of buffer
747 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
749 int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
756 st = s->streams[stream_index];
757 pts_mask = (1LL << s->pts_wrap_bits) - 1;
758 ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
759 st->pts.val & pts_mask);
764 switch (st->codec.codec_type) {
765 case CODEC_TYPE_AUDIO:
766 av_frac_add(&st->pts,
767 (INT64)s->pts_den * st->codec.frame_size);
769 case CODEC_TYPE_VIDEO:
770 av_frac_add(&st->pts,
771 (INT64)s->pts_den * FRAME_RATE_BASE);
780 * write the stream trailer to an output media file and and free the
783 * @param s media file handle
784 * @return 0 if OK. AVERROR_xxx if error. */
785 int av_write_trailer(AVFormatContext *s)
788 ret = s->oformat->write_trailer(s);
789 av_freep(&s->priv_data);
793 /* "user interface" functions */
795 void dump_format(AVFormatContext *ic,
803 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
804 is_output ? "Output" : "Input",
806 is_output ? ic->oformat->name : ic->iformat->name,
807 is_output ? "to" : "from", url);
808 for(i=0;i<ic->nb_streams;i++) {
809 AVStream *st = ic->streams[i];
810 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
811 fprintf(stderr, " Stream #%d.%d", index, i);
812 /* the pid is an important information, so we display it */
813 /* XXX: add a generic system */
815 flags = ic->oformat->flags;
817 flags = ic->iformat->flags;
818 if (flags & AVFMT_SHOW_IDS) {
819 fprintf(stderr, "[0x%x]", st->id);
821 fprintf(stderr, ": %s\n", buf);
830 static SizeEntry sizes[] = {
831 { "sqcif", 128, 96 },
832 { "qcif", 176, 144 },
834 { "4cif", 704, 576 },
837 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
840 int n = sizeof(sizes) / sizeof(SizeEntry);
842 int frame_width = 0, frame_height = 0;
845 if (!strcmp(sizes[i].str, str)) {
846 frame_width = sizes[i].width;
847 frame_height = sizes[i].height;
853 frame_width = strtol(p, (char **)&p, 10);
856 frame_height = strtol(p, (char **)&p, 10);
858 if (frame_width <= 0 || frame_height <= 0)
860 *width_ptr = frame_width;
861 *height_ptr = frame_height;
865 INT64 av_gettime(void)
870 return ((INT64)tb.time * INT64_C(1000) + (INT64)tb.millitm) * INT64_C(1000);
873 gettimeofday(&tv,NULL);
874 return (INT64)tv.tv_sec * 1000000 + tv.tv_usec;
878 static time_t mktimegm(struct tm *tm)
882 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
890 (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
892 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
898 * - If not a duration:
899 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
900 * Time is localtime unless Z is suffixed to the end. In this case GMT
901 * Return the date in micro seconds since 1970
903 * HH[:MM[:SS[.m...]]]
906 INT64 parse_date(const char *datestr, int duration)
912 static const char *date_fmt[] = {
916 static const char *time_fmt[] = {
923 time_t now = time(0);
925 len = strlen(datestr);
927 lastch = datestr[len - 1];
930 is_utc = (lastch == 'z' || lastch == 'Z');
932 memset(&dt, 0, sizeof(dt));
937 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
938 q = strptime(p, date_fmt[i], &dt);
948 dt = *localtime(&now);
950 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
955 if (*p == 'T' || *p == 't' || *p == ' ')
958 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
959 q = strptime(p, time_fmt[i], &dt);
965 q = strptime(p, time_fmt[0], &dt);
967 dt.tm_sec = strtol(p, (char **)&q, 10);
973 /* Now we have all the fields that we can get */
978 return now * INT64_C(1000000);
982 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
984 dt.tm_isdst = -1; /* unknown */
997 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1000 val += n * (*q - '0');
1007 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1009 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1019 while (*p != '\0' && *p != '=' && *p != '&') {
1020 if ((q - tag) < sizeof(tag) - 1)
1028 while (*p != '&' && *p != '\0') {
1029 if ((q - arg) < arg_size - 1) {
1039 if (!strcmp(tag, tag1))
1048 /* Return in 'buf' the path with '%d' replaced by number. Also handles
1049 the '%0nd' format where 'n' is the total number of digits and
1050 '%%'. Return 0 if OK, and -1 if format error */
1051 int get_frame_filename(char *buf, int buf_size,
1052 const char *path, int number)
1056 int nd, len, c, percentd_found;
1067 while (*p >= '0' && *p <= '9') {
1068 nd = nd * 10 + *p++ - '0';
1078 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1080 if ((q - buf + len) > buf_size - 1)
1082 memcpy(q, buf1, len);
1090 if ((q - buf) < buf_size - 1)
1094 if (!percentd_found)
1105 * Print on stdout a nice hexa dump of a buffer
1107 * @param size buffer size
1109 void av_hex_dump(UINT8 *buf, int size)
1113 for(i=0;i<size;i+=16) {
1120 printf(" %02x", buf[i+j]);
1125 for(j=0;j<len;j++) {
1127 if (c < ' ' || c > '~')
1135 void url_split(char *proto, int proto_size,
1136 char *hostname, int hostname_size,
1138 char *path, int path_size,
1149 while (*p != ':' && *p != '\0') {
1150 if ((q - proto) < proto_size - 1)
1159 if (hostname_size > 0)
1169 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1170 if ((q - hostname) < hostname_size - 1)
1174 if (hostname_size > 0)
1178 port = strtoul(p, (char **)&p, 10);
1183 pstrcpy(path, path_size, p);
1187 * Set the pts for a given stream
1189 * @param pts_wrap_bits number of bits effectively used by the pts
1190 * (used for wrap control, 33 is the value for MPEG)
1191 * @param pts_num numerator to convert to seconds (MPEG: 1)
1192 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1194 void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1195 int pts_num, int pts_den)
1197 s->pts_wrap_bits = pts_wrap_bits;
1198 s->pts_num = pts_num;
1199 s->pts_den = pts_den;
1202 /* fraction handling */
1205 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1206 * as 0 <= num < den.
1208 * @param f fractional number
1209 * @param val integer value
1210 * @param num must be >= 0
1211 * @param den must be >= 1
1213 void av_frac_init(AVFrac *f, INT64 val, INT64 num, INT64 den)
1225 /* set f to (val + 0.5) */
1226 void av_frac_set(AVFrac *f, INT64 val)
1229 f->num = f->den >> 1;
1233 * Fractionnal addition to f: f = f + (incr / f->den)
1235 * @param f fractional number
1236 * @param incr increment, can be positive or negative
1238 void av_frac_add(AVFrac *f, INT64 incr)
1242 num = f->num + incr;
1245 f->val += num / den;
1251 } else if (num >= den) {
1252 f->val += num / den;