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>
32 AVInputFormat *first_iformat;
33 AVOutputFormat *first_oformat;
35 void av_register_input_format(AVInputFormat *format)
39 while (*p != NULL) p = &(*p)->next;
44 void av_register_output_format(AVOutputFormat *format)
48 while (*p != NULL) p = &(*p)->next;
53 int match_ext(const char *filename, const char *extensions)
58 ext = strrchr(filename, '.');
64 while (*p != '\0' && *p != ',')
67 if (!strcasecmp(ext1, ext))
77 AVOutputFormat *guess_format(const char *short_name, const char *filename,
78 const char *mime_type)
80 AVOutputFormat *fmt, *fmt_found;
83 /* find the proper file type */
89 if (fmt->name && short_name && !strcmp(fmt->name, short_name))
91 if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
93 if (filename && fmt->extensions &&
94 match_ext(filename, fmt->extensions)) {
97 if (score > score_max) {
106 AVInputFormat *av_find_input_format(const char *short_name)
109 for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
110 if (!strcmp(fmt->name, short_name))
118 * Return TRUE if val is a prefix of str. If it returns TRUE, ptr is
119 * set to the next character in 'str' after the prefix.
121 * @param str input string
122 * @param val prefix to test
123 * @param ptr updated after the prefix in str in there is a match
124 * @return TRUE if there is a match
126 int strstart(const char *str, const char *val, const char **ptr)
143 * Copy the string str to buf. If str length is bigger than buf_size -
144 * 1 then it is clamped to buf_size - 1.
145 * NOTE: this function does what strncpy should have done to be
146 * useful. NEVER use strncpy.
148 * @param buf destination buffer
149 * @param buf_size size of destination buffer
150 * @param str source string
152 void pstrcpy(char *buf, int buf_size, const char *str)
159 if (c == 0 || q >= buf + buf_size - 1)
166 void register_all(void)
169 avcodec_register_all();
190 #ifdef CONFIG_VIDEO4LINUX
193 #ifdef CONFIG_AUDIO_OSS
197 register_protocol(&file_protocol);
198 register_protocol(&pipe_protocol);
199 #ifdef CONFIG_NETWORK
200 register_protocol(&udp_protocol);
201 register_protocol(&http_protocol);
205 /* memory handling */
208 * Allocate the payload of a packet and intialized its fields to default values.
211 * @param size wanted payload size
212 * @return 0 if OK. AVERROR_xxx otherwise.
214 int av_new_packet(AVPacket *pkt, int size)
216 pkt->data = av_malloc(size);
218 return AVERROR_NOMEM;
222 pkt->stream_index = 0;
230 * @param pkt packet to free
232 void av_free_packet(AVPacket *pkt)
234 av_freep(&pkt->data);
241 int fifo_init(FifoBuffer *f, int size)
243 f->buffer = av_malloc(size);
246 f->end = f->buffer + size;
247 f->wptr = f->rptr = f->buffer;
251 void fifo_free(FifoBuffer *f)
256 int fifo_size(FifoBuffer *f, UINT8 *rptr)
260 if (f->wptr >= rptr) {
261 size = f->wptr - rptr;
263 size = (f->end - rptr) + (f->wptr - f->buffer);
268 /* get data from the fifo (return -1 if not enough data) */
269 int fifo_read(FifoBuffer *f, UINT8 *buf, int buf_size, UINT8 **rptr_ptr)
271 UINT8 *rptr = *rptr_ptr;
274 if (f->wptr >= rptr) {
275 size = f->wptr - rptr;
277 size = (f->end - rptr) + (f->wptr - f->buffer);
282 while (buf_size > 0) {
286 memcpy(buf, rptr, len);
297 void fifo_write(FifoBuffer *f, UINT8 *buf, int size, UINT8 **wptr_ptr)
306 memcpy(wptr, buf, len);
316 int filename_number_test(const char *filename)
319 return get_frame_filename(buf, sizeof(buf), filename, 1);
322 /* guess file format */
323 static AVInputFormat *probe_input_format(AVProbeData *pd, int is_opened)
325 AVInputFormat *fmt1, *fmt;
326 int score, score_max;
330 for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
331 if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
334 if (fmt1->read_probe) {
335 score = fmt1->read_probe(pd);
336 } else if (fmt1->extensions) {
337 if (match_ext(pd->filename, fmt1->extensions)) {
341 if (score > score_max) {
349 /************************************************************/
350 /* input media file */
352 #define PROBE_BUF_SIZE 2048
355 * Open a media file as input. The codec are not opened. Only the file
356 * header (if present) is read.
358 * @param ic_ptr the opened media file handle is put here
359 * @param filename filename to open.
360 * @param fmt if non NULL, force the file format to use
361 * @param buf_size optional buffer size (zero if default is OK)
362 * @param ap additionnal parameters needed when opening the file (NULL if default)
363 * @return 0 if OK. AVERROR_xxx otherwise.
365 int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
368 AVFormatParameters *ap)
370 AVFormatContext *ic = NULL;
372 char buf[PROBE_BUF_SIZE];
373 AVProbeData probe_data, *pd = &probe_data;
375 ic = av_mallocz(sizeof(AVFormatContext));
380 pstrcpy(ic->filename, sizeof(ic->filename), filename);
381 pd->filename = ic->filename;
386 /* guess format if no file can be opened */
387 fmt = probe_input_format(pd, 0);
390 /* if no file needed do not try to open one */
391 if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {
392 if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
397 url_setbufsize(&ic->pb, buf_size);
399 /* read probe data */
400 pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
401 url_fseek(&ic->pb, 0, SEEK_SET);
404 /* guess file format */
406 fmt = probe_input_format(pd, 1);
409 /* if still no format found, error */
417 /* allocate private data */
418 ic->priv_data = av_mallocz(fmt->priv_data_size);
419 if (!ic->priv_data) {
424 /* check filename in case of an image number is expected */
425 if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
426 if (filename_number_test(ic->filename) < 0) {
427 err = AVERROR_NUMEXPECTED;
432 err = ic->iformat->read_header(ic, ap);
438 if (!(fmt->flags & AVFMT_NOFILE)) {
443 av_freep(&ic->priv_data);
451 * Read a packet from a media file
452 * @param s media file handle
453 * @param pkt is filled
454 * @return 0 if OK. AVERROR_xxx if error.
456 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
460 pktl = s->packet_buffer;
462 /* read packet from packet buffer, if there is data */
464 s->packet_buffer = pktl->next;
468 return s->iformat->read_packet(s, pkt);
472 /* state for codec information */
473 #define CSTATE_NOTFOUND 0
474 #define CSTATE_DECODING 1
475 #define CSTATE_FOUND 2
477 static int has_codec_parameters(AVCodecContext *enc)
480 switch(enc->codec_type) {
481 case CODEC_TYPE_AUDIO:
482 val = enc->sample_rate;
484 case CODEC_TYPE_VIDEO:
495 * Read the beginning of a media file to get stream information. This
496 * is useful for file formats with no headers such as MPEG. This
497 * function also compute the real frame rate in case of mpeg2 repeat
500 * @param ic media file handle
501 * @return >=0 if OK. AVERROR_xxx if error.
503 int av_find_stream_info(AVFormatContext *ic)
505 int i, count, ret, got_picture, size, read_size;
510 AVPacketList *pktl=NULL, **ppktl;
511 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
513 int min_read_size, max_read_size;
515 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
516 Mbits. We read at most 0.1 second of file to find all streams */
518 /* XXX: base it on stream bitrate when possible */
519 if (ic->iformat == &mpegts_demux) {
520 /* maximum number of bytes we accept to read to find all the streams
522 min_read_size = 3000000;
524 min_read_size = 125000;
526 /* max read size is 2 seconds of video max */
527 max_read_size = min_read_size * 20;
529 /* set initial codec state */
530 for(i=0;i<ic->nb_streams;i++) {
532 if (has_codec_parameters(&st->codec))
533 st->codec_info_state = CSTATE_FOUND;
535 st->codec_info_state = CSTATE_NOTFOUND;
536 st->codec_info_nb_repeat_frames = 0;
537 st->codec_info_nb_real_frames = 0;
542 ppktl = &ic->packet_buffer;
544 /* check if one codec still needs to be handled */
545 for(i=0;i<ic->nb_streams;i++) {
547 if (st->codec_info_state != CSTATE_FOUND)
550 if (i == ic->nb_streams) {
551 /* NOTE: if the format has no header, then we need to read
552 some packets to get most of the streams, so we cannot
554 if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
555 read_size >= min_read_size) {
556 /* if we found the info for all the codecs, we can stop */
561 /* we did not get all the codec info, but we read too much data */
562 if (read_size >= max_read_size) {
568 pktl = av_mallocz(sizeof(AVPacketList));
574 /* add the packet in the buffered packet list */
578 /* NOTE: a new stream can be added there if no header in file
581 if (ic->iformat->read_packet(ic, pkt) < 0) {
583 ret = -1; /* we could not have all the codec parameters before EOF */
584 if ((ic->iformat->flags & AVFMT_NOHEADER) &&
589 read_size += pkt->size;
591 /* open new codecs */
592 for(i=0;i<ic->nb_streams;i++) {
594 if (st->codec_info_state == CSTATE_NOTFOUND) {
595 /* set to found in case of error */
596 st->codec_info_state = CSTATE_FOUND;
597 codec = avcodec_find_decoder(st->codec.codec_id);
599 ret = avcodec_open(&st->codec, codec);
601 st->codec_info_state = CSTATE_DECODING;
606 st = ic->streams[pkt->stream_index];
607 if (st->codec_info_state == CSTATE_DECODING) {
608 /* decode the data and update codec parameters */
612 switch(st->codec.codec_type) {
613 case CODEC_TYPE_VIDEO:
614 ret = avcodec_decode_video(&st->codec, &picture,
615 &got_picture, ptr, size);
617 case CODEC_TYPE_AUDIO:
618 ret = avcodec_decode_audio(&st->codec, samples,
619 &got_picture, ptr, size);
626 /* if error, simply ignore because another packet
631 /* we got the parameters - now we can stop
632 examining this stream */
633 /* XXX: add a codec info so that we can decide if
634 the codec can repeat frames */
635 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
636 ic->iformat != &mpegts_demux &&
637 st->codec.sub_id == 2) {
638 /* for mpeg2 video, we want to know the real
639 frame rate, so we decode 40 frames. In mpeg
640 TS case we do not do it because it would be
642 st->codec_info_nb_real_frames++;
643 st->codec_info_nb_repeat_frames += st->codec.repeat_pict;
646 if ((st->codec_info_nb_real_frames % 24) == 23) {
647 st->codec_info_nb_repeat_frames += 2;
650 /* stop after 40 frames */
651 if (st->codec_info_nb_real_frames >= 40) {
652 st->r_frame_rate = (st->codec.frame_rate *
653 st->codec_info_nb_real_frames) /
654 (st->codec_info_nb_real_frames +
655 (st->codec_info_nb_repeat_frames >> 1));
660 st->codec_info_state = CSTATE_FOUND;
661 avcodec_close(&st->codec);
672 /* close each codec if there are opened */
673 for(i=0;i<ic->nb_streams;i++) {
675 if (st->codec_info_state == CSTATE_DECODING)
676 avcodec_close(&st->codec);
679 /* set real frame rate info */
680 for(i=0;i<ic->nb_streams;i++) {
682 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
683 if (!st->r_frame_rate)
684 st->r_frame_rate = st->codec.frame_rate;
692 * Close a media file (but not its codecs)
694 * @param s media file handle
696 void av_close_input_file(AVFormatContext *s)
700 if (s->iformat->read_close)
701 s->iformat->read_close(s);
702 for(i=0;i<s->nb_streams;i++) {
703 av_free(s->streams[i]);
705 if (s->packet_buffer) {
706 AVPacketList *p, *p1;
707 p = s->packet_buffer;
710 av_free_packet(&p->pkt);
714 s->packet_buffer = NULL;
716 if (!(s->iformat->flags & AVFMT_NOFILE)) {
719 av_freep(&s->priv_data);
724 * Add a new stream to a media file. Can only be called in the
725 * read_header function. If the flag AVFMT_NOHEADER is in the format
726 * description, then new streams can be added in read_packet too.
729 * @param s media file handle
730 * @param id file format dependent stream id
732 AVStream *av_new_stream(AVFormatContext *s, int id)
736 if (s->nb_streams >= MAX_STREAMS)
739 st = av_mallocz(sizeof(AVStream));
742 st->index = s->nb_streams;
744 s->streams[s->nb_streams++] = st;
748 /************************************************************/
749 /* output media file */
752 * allocate the stream private data and write the stream header to an
755 * @param s media file handle
756 * @return 0 if OK. AVERROR_xxx if error.
758 int av_write_header(AVFormatContext *s)
760 s->priv_data = av_mallocz(s->oformat->priv_data_size);
762 return AVERROR_NOMEM;
763 return s->oformat->write_header(s);
767 * write a packet to an output media file
769 * @param s media file handle
770 * @param pkt packet to write
771 * @param force_pts XXX: need to suppress that
773 int av_write_packet(AVFormatContext *s, AVPacket *pkt, int force_pts)
775 /* XXX: currently, an emulation because internal API must change */
776 return s->oformat->write_packet(s, pkt->stream_index, pkt->data, pkt->size, force_pts);
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;
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 /* syntax: [YYYY-MM-DD ][[HH:]MM:]SS[.m...] . Return the date in micro seconds since 1970 */
879 INT64 parse_date(const char *datestr, int duration)
885 memset(&dt, 0, sizeof(dt));
889 if (strlen(p) >= 5 && p[4] == '-') {
890 dt.tm_year = strtol(p, (char **)&p, 10);
893 dt.tm_mon = strtol(p, (char **)&p, 10) - 1;
896 dt.tm_mday = strtol(p, (char **)&p, 10) - 1;
900 time_t now = time(0);
901 dt = *localtime(&now);
908 dt.tm_hour = strtol(p, (char **)&p, 10);
911 dt.tm_min = strtol(p, (char **)&p, 10);
914 dt.tm_sec = strtol(p, (char **)&p, 10);
917 t = (INT64) 1000000 * (dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec);
919 t = (INT64) 1000000 * mktime(&dt);
928 val = strtol(p, NULL, 10);
938 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
940 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
950 while (*p != '\0' && *p != '=' && *p != '&') {
951 if ((q - tag) < sizeof(tag) - 1)
959 while (*p != '&' && *p != '\0') {
960 if ((q - arg) < arg_size - 1) {
970 if (!strcmp(tag, tag1))
979 /* Return in 'buf' the path with '%d' replaced by number. Also handles
980 the '%0nd' format where 'n' is the total number of digits and
981 '%%'. Return 0 if OK, and -1 if format error */
982 int get_frame_filename(char *buf, int buf_size,
983 const char *path, int number)
987 int nd, len, c, percentd_found;
998 while (*p >= '0' && *p <= '9') {
999 nd = nd * 10 + *p++ - '0';
1009 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1011 if ((q - buf + len) > buf_size - 1)
1013 memcpy(q, buf1, len);
1021 if ((q - buf) < buf_size - 1)
1025 if (!percentd_found)
1034 static int gcd(INT64 a, INT64 b)
1047 void ticker_init(Ticker *tick, INT64 inrate, INT64 outrate)
1051 g = gcd(inrate, outrate);
1055 tick->value = -outrate/2;
1057 tick->inrate = inrate;
1058 tick->outrate = outrate;
1059 tick->div = tick->outrate / tick->inrate;
1060 tick->mod = tick->outrate % tick->inrate;
1065 * Print on stdout a nice hexa dump of a buffer
1067 * @param size buffer size
1069 void av_hex_dump(UINT8 *buf, int size)
1073 for(i=0;i<size;i+=16) {
1080 printf(" %02x", buf[i+j]);
1085 for(j=0;j<len;j++) {
1087 if (c < ' ' || c > '~')