2 * Various utilities for ffmpeg system
3 * Copyright (c) 2000, 2001, 2002 Gerard Lantau
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program 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
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #define strcasecmp _stricmp
28 #include <sys/types.h>
29 #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();
195 register_protocol(&file_protocol
);
196 register_protocol(&pipe_protocol
);
198 register_protocol(&udp_protocol
);
199 register_protocol(&http_protocol
);
203 /* memory handling */
206 * Allocate the payload of a packet and intialized its fields to default values.
209 * @param size wanted payload size
210 * @return 0 if OK. AVERROR_xxx otherwise.
212 int av_new_packet(AVPacket
*pkt
, int size
)
214 pkt
->data
= av_malloc(size
);
216 return AVERROR_NOMEM
;
220 pkt
->stream_index
= 0;
228 * @param pkt packet to free
230 void av_free_packet(AVPacket
*pkt
)
232 av_freep(&pkt
->data
);
239 int fifo_init(FifoBuffer
*f
, int size
)
241 f
->buffer
= av_malloc(size
);
244 f
->end
= f
->buffer
+ size
;
245 f
->wptr
= f
->rptr
= f
->buffer
;
249 void fifo_free(FifoBuffer
*f
)
254 int fifo_size(FifoBuffer
*f
, UINT8
*rptr
)
258 if (f
->wptr
>= rptr
) {
259 size
= f
->wptr
- rptr
;
261 size
= (f
->end
- rptr
) + (f
->wptr
- f
->buffer
);
266 /* get data from the fifo (return -1 if not enough data) */
267 int fifo_read(FifoBuffer
*f
, UINT8
*buf
, int buf_size
, UINT8
**rptr_ptr
)
269 UINT8
*rptr
= *rptr_ptr
;
272 if (f
->wptr
>= rptr
) {
273 size
= f
->wptr
- rptr
;
275 size
= (f
->end
- rptr
) + (f
->wptr
- f
->buffer
);
280 while (buf_size
> 0) {
284 memcpy(buf
, rptr
, len
);
295 void fifo_write(FifoBuffer
*f
, UINT8
*buf
, int size
, UINT8
**wptr_ptr
)
304 memcpy(wptr
, buf
, len
);
314 int filename_number_test(const char *filename
)
317 return get_frame_filename(buf
, sizeof(buf
), filename
, 1);
320 /* guess file format */
321 static AVInputFormat
*probe_input_format(AVProbeData
*pd
, int is_opened
)
323 AVInputFormat
*fmt1
, *fmt
;
324 int score
, score_max
;
328 for(fmt1
= first_iformat
; fmt1
!= NULL
; fmt1
= fmt1
->next
) {
329 if (!is_opened
&& !(fmt1
->flags
& AVFMT_NOFILE
))
332 if (fmt1
->extensions
) {
333 if (match_ext(pd
->filename
, fmt1
->extensions
)) {
336 } else if (fmt1
->read_probe
) {
337 score
= fmt1
->read_probe(pd
);
339 if (score
> score_max
) {
347 /************************************************************/
348 /* input media file */
350 #define PROBE_BUF_SIZE 2048
353 * Open a media file as input. The codec are not opened. Only the file
354 * header (if present) is read.
356 * @param ic_ptr the opened media file handle is put here
357 * @param filename filename to open.
358 * @param fmt if non NULL, force the file format to use
359 * @param buf_size optional buffer size (zero if default is OK)
360 * @param ap additionnal parameters needed when opening the file (NULL if default)
361 * @return 0 if OK. AVERROR_xxx otherwise.
363 int av_open_input_file(AVFormatContext
**ic_ptr
, const char *filename
,
366 AVFormatParameters
*ap
)
368 AVFormatContext
*ic
= NULL
;
370 char buf
[PROBE_BUF_SIZE
];
371 AVProbeData probe_data
, *pd
= &probe_data
;
373 ic
= av_mallocz(sizeof(AVFormatContext
));
378 pstrcpy(ic
->filename
, sizeof(ic
->filename
), filename
);
379 pd
->filename
= ic
->filename
;
384 /* guess format if no file can be opened */
385 fmt
= probe_input_format(pd
, 0);
388 /* if no file needed do not try to open one */
389 if (!fmt
|| !(fmt
->flags
& AVFMT_NOFILE
)) {
390 if (url_fopen(&ic
->pb
, filename
, URL_RDONLY
) < 0) {
395 url_setbufsize(&ic
->pb
, buf_size
);
397 /* read probe data */
398 pd
->buf_size
= get_buffer(&ic
->pb
, buf
, PROBE_BUF_SIZE
);
399 url_fseek(&ic
->pb
, 0, SEEK_SET
);
402 /* guess file format */
404 fmt
= probe_input_format(pd
, 1);
407 /* if still no format found, error */
415 /* allocate private data */
416 ic
->priv_data
= av_mallocz(fmt
->priv_data_size
);
417 if (!ic
->priv_data
) {
422 /* check filename in case of an image number is expected */
423 if (ic
->iformat
->flags
& AVFMT_NEEDNUMBER
) {
424 if (filename_number_test(ic
->filename
) < 0) {
425 err
= AVERROR_NUMEXPECTED
;
430 err
= ic
->iformat
->read_header(ic
, ap
);
436 if (!(fmt
->flags
& AVFMT_NOFILE
)) {
441 av_free(ic
->priv_data
);
449 * Read a packet from a media file
450 * @param s media file handle
451 * @param pkt is filled
452 * @return 0 if OK. AVERROR_xxx if error.
454 int av_read_packet(AVFormatContext
*s
, AVPacket
*pkt
)
458 pktl
= s
->packet_buffer
;
460 /* read packet from packet buffer, if there is data */
462 s
->packet_buffer
= pktl
->next
;
466 return s
->iformat
->read_packet(s
, pkt
);
470 /* state for codec information */
471 #define CSTATE_NOTFOUND 0
472 #define CSTATE_DECODING 1
473 #define CSTATE_FOUND 2
475 static int has_codec_parameters(AVCodecContext
*enc
)
478 switch(enc
->codec_type
) {
479 case CODEC_TYPE_AUDIO
:
480 val
= enc
->sample_rate
;
482 case CODEC_TYPE_VIDEO
:
493 * Read the beginning of a media file to get stream information. This
494 * is useful for file formats with no headers such as MPEG. This
495 * function also compute the real frame rate in case of mpeg2 repeat
498 * @param ic media file handle
499 * @return >=0 if OK. AVERROR_xxx if error.
501 int av_find_stream_info(AVFormatContext
*ic
)
503 int i
, count
, ret
, got_picture
, size
, read_size
;
508 AVPacketList
*pktl
=NULL
, **ppktl
;
509 short samples
[AVCODEC_MAX_AUDIO_FRAME_SIZE
/ 2];
511 int min_read_size
, max_read_size
;
513 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
514 Mbits. We read at most 0.1 second of file to find all streams */
516 /* XXX: base it on stream bitrate when possible */
517 if (ic
->iformat
== &mpegts_demux
) {
518 /* maximum number of bytes we accept to read to find all the streams
520 min_read_size
= 3000000;
522 min_read_size
= 125000;
524 /* max read size is 2 seconds of video max */
525 max_read_size
= min_read_size
* 20;
527 /* set initial codec state */
528 for(i
=0;i
<ic
->nb_streams
;i
++) {
530 if (has_codec_parameters(&st
->codec
))
531 st
->codec_info_state
= CSTATE_FOUND
;
533 st
->codec_info_state
= CSTATE_NOTFOUND
;
534 st
->codec_info_nb_repeat_frames
= 0;
535 st
->codec_info_nb_real_frames
= 0;
540 ppktl
= &ic
->packet_buffer
;
542 /* check if one codec still needs to be handled */
543 for(i
=0;i
<ic
->nb_streams
;i
++) {
545 if (st
->codec_info_state
!= CSTATE_FOUND
)
548 if (i
== ic
->nb_streams
) {
549 /* NOTE: if the format has no header, then we need to read
550 some packets to get most of the streams, so we cannot
552 if (!(ic
->iformat
->flags
& AVFMT_NOHEADER
) ||
553 read_size
>= min_read_size
) {
554 /* if we found the info for all the codecs, we can stop */
559 /* we did not get all the codec info, but we read too much data */
560 if (read_size
>= max_read_size
) {
566 pktl
= av_mallocz(sizeof(AVPacketList
));
572 /* add the packet in the buffered packet list */
576 /* NOTE: a new stream can be added there if no header in file
579 if (ic
->iformat
->read_packet(ic
, pkt
) < 0) {
581 ret
= -1; /* we could not have all the codec parameters before EOF */
582 if ((ic
->iformat
->flags
& AVFMT_NOHEADER
) &&
587 read_size
+= pkt
->size
;
589 /* open new codecs */
590 for(i
=0;i
<ic
->nb_streams
;i
++) {
592 if (st
->codec_info_state
== CSTATE_NOTFOUND
) {
593 /* set to found in case of error */
594 st
->codec_info_state
= CSTATE_FOUND
;
595 codec
= avcodec_find_decoder(st
->codec
.codec_id
);
597 ret
= avcodec_open(&st
->codec
, codec
);
599 st
->codec_info_state
= CSTATE_DECODING
;
604 st
= ic
->streams
[pkt
->stream_index
];
605 if (st
->codec_info_state
== CSTATE_DECODING
) {
606 /* decode the data and update codec parameters */
610 switch(st
->codec
.codec_type
) {
611 case CODEC_TYPE_VIDEO
:
612 ret
= avcodec_decode_video(&st
->codec
, &picture
,
613 &got_picture
, ptr
, size
);
615 case CODEC_TYPE_AUDIO
:
616 ret
= avcodec_decode_audio(&st
->codec
, samples
,
617 &got_picture
, ptr
, size
);
624 /* if error, simply ignore because another packet
629 /* we got the parameters - now we can stop
630 examining this stream */
631 /* XXX: add a codec info so that we can decide if
632 the codec can repeat frames */
633 if (st
->codec
.codec_id
== CODEC_ID_MPEG1VIDEO
&&
634 ic
->iformat
!= &mpegts_demux
&&
635 st
->codec
.sub_id
== 2) {
636 /* for mpeg2 video, we want to know the real
637 frame rate, so we decode 40 frames. In mpeg
638 TS case we do not do it because it would be
640 st
->codec_info_nb_real_frames
++;
641 st
->codec_info_nb_repeat_frames
+= st
->codec
.repeat_pict
;
644 if ((st
->codec_info_nb_real_frames
% 24) == 23) {
645 st
->codec_info_nb_repeat_frames
+= 2;
648 /* stop after 40 frames */
649 if (st
->codec_info_nb_real_frames
>= 40) {
650 st
->r_frame_rate
= (st
->codec
.frame_rate
*
651 st
->codec_info_nb_real_frames
) /
652 (st
->codec_info_nb_real_frames
+
653 (st
->codec_info_nb_repeat_frames
>> 1));
658 st
->codec_info_state
= CSTATE_FOUND
;
659 avcodec_close(&st
->codec
);
670 /* close each codec if there are opened */
671 for(i
=0;i
<ic
->nb_streams
;i
++) {
673 if (st
->codec_info_state
== CSTATE_DECODING
)
674 avcodec_close(&st
->codec
);
677 /* set real frame rate info */
678 for(i
=0;i
<ic
->nb_streams
;i
++) {
680 if (st
->codec
.codec_type
== CODEC_TYPE_VIDEO
) {
681 if (!st
->r_frame_rate
)
682 st
->r_frame_rate
= st
->codec
.frame_rate
;
690 * Close a media file (but not its codecs)
692 * @param s media file handle
694 void av_close_input_file(AVFormatContext
*s
)
698 if (s
->iformat
->read_close
)
699 s
->iformat
->read_close(s
);
700 for(i
=0;i
<s
->nb_streams
;i
++) {
701 av_free(s
->streams
[i
]);
703 if (s
->packet_buffer
) {
704 AVPacketList
*p
, *p1
;
705 p
= s
->packet_buffer
;
708 av_free_packet(&p
->pkt
);
712 s
->packet_buffer
= NULL
;
714 if (!(s
->iformat
->flags
& AVFMT_NOFILE
)) {
717 av_free(s
->priv_data
);
722 * Add a new stream to a media file. Can only be called in the
723 * read_header function. If the flag AVFMT_NOHEADER is in the format
724 * description, then new streams can be added in read_packet too.
727 * @param s media file handle
728 * @param id file format dependent stream id
730 AVStream
*av_new_stream(AVFormatContext
*s
, int id
)
734 if (s
->nb_streams
>= MAX_STREAMS
)
737 st
= av_mallocz(sizeof(AVStream
));
740 st
->index
= s
->nb_streams
;
742 s
->streams
[s
->nb_streams
++] = st
;
746 /************************************************************/
747 /* output media file */
750 * allocate the stream private data and write the stream header to an
753 * @param s media file handle
754 * @return 0 if OK. AVERROR_xxx if error.
756 int av_write_header(AVFormatContext
*s
)
758 s
->priv_data
= av_mallocz(s
->oformat
->priv_data_size
);
760 return AVERROR_NOMEM
;
761 return s
->oformat
->write_header(s
);
765 * write a packet to an output media file
767 * @param s media file handle
768 * @param pkt packet to write
769 * @param force_pts XXX: need to suppress that
771 int av_write_packet(AVFormatContext
*s
, AVPacket
*pkt
, int force_pts
)
773 /* XXX: currently, an emulation because internal API must change */
774 return s
->oformat
->write_packet(s
, pkt
->stream_index
, pkt
->data
, pkt
->size
, force_pts
);
778 * write the stream trailer to an output media file and and free the
781 * @param s media file handle
782 * @return 0 if OK. AVERROR_xxx if error. */
783 int av_write_trailer(AVFormatContext
*s
)
786 ret
= s
->oformat
->write_trailer(s
);
787 av_freep(&s
->priv_data
);
791 /* "user interface" functions */
793 void dump_format(AVFormatContext
*ic
,
801 fprintf(stderr
, "%s #%d, %s, %s '%s':\n",
802 is_output ?
"Output" : "Input",
804 is_output ? ic
->oformat
->name
: ic
->iformat
->name
,
805 is_output ?
"to" : "from", url
);
806 for(i
=0;i
<ic
->nb_streams
;i
++) {
807 AVStream
*st
= ic
->streams
[i
];
808 avcodec_string(buf
, sizeof(buf
), &st
->codec
, is_output
);
809 fprintf(stderr
, " Stream #%d.%d", index
, i
);
810 /* the pid is an important information, so we display it */
811 /* XXX: add a generic system */
813 flags
= ic
->oformat
->flags
;
815 flags
= ic
->iformat
->flags
;
816 if (flags
& AVFMT_SHOW_IDS
) {
817 fprintf(stderr
, "[0x%x]", st
->id
);
819 fprintf(stderr
, ": %s\n", buf
);
828 static SizeEntry sizes
[] = {
829 { "sqcif", 128, 96 },
830 { "qcif", 176, 144 },
832 { "4cif", 704, 576 },
835 int parse_image_size(int *width_ptr
, int *height_ptr
, const char *str
)
838 int n
= sizeof(sizes
) / sizeof(SizeEntry
);
840 int frame_width
= 0, frame_height
= 0;
843 if (!strcmp(sizes
[i
].str
, str
)) {
844 frame_width
= sizes
[i
].width
;
845 frame_height
= sizes
[i
].height
;
851 frame_width
= strtol(p
, (char **)&p
, 10);
854 frame_height
= strtol(p
, (char **)&p
, 10);
856 if (frame_width
<= 0 || frame_height
<= 0)
858 *width_ptr
= frame_width
;
859 *height_ptr
= frame_height
;
868 return ((INT64
)tb
.time
* INT64_C(1000) + (INT64
)tb
.millitm
) * INT64_C(1000);
871 gettimeofday(&tv
,NULL
);
872 return (INT64
)tv
.tv_sec
* 1000000 + tv
.tv_usec
;
876 /* syntax: [YYYY-MM-DD ][[HH:]MM:]SS[.m...] . Return the date in micro seconds since 1970 */
877 INT64
parse_date(const char *datestr
, int duration
)
885 static const UINT8 months
[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
886 int year
, month
, day
, i
;
888 if (strlen(p
) >= 5 && p
[4] == '-') {
890 year
= strtol(p
, (char **)&p
, 10);
893 month
= strtol(p
, (char **)&p
, 10) - 1;
896 day
= strtol(p
, (char **)&p
, 10) - 1;
899 day
+= (year
- 1970) * 365;
900 /* if >= March, take February of current year into account too */
903 for(i
=1970;i
<year
;i
++) {
904 if ((i
% 100) == 0) {
905 if ((i
% 400) == 0) day
++;
906 } else if ((i
% 4) == 0) {
913 day
= (time(NULL
) / (3600 * 24));
915 t
= day
* (3600 * 24);
923 val
= strtol(p
, (char **)&p
, 10);
924 sec
= sec
* 60 + val
;
929 t
= (t
+ sec
) * 1000000;
936 val
= strtol(p
, NULL
, 10);
946 /* syntax: '?tag1=val1&tag2=val2...'. No URL decoding is done. Return
948 int find_info_tag(char *arg
, int arg_size
, const char *tag1
, const char *info
)
958 while (*p
!= '\0' && *p
!= '=' && *p
!= '&') {
959 if ((q
- tag
) < sizeof(tag
) - 1)
967 while (*p
!= '&' && *p
!= '\0') {
968 if ((q
- arg
) < arg_size
- 1)
974 if (!strcmp(tag
, tag1
))
983 /* Return in 'buf' the path with '%d' replaced by number. Also handles
984 the '%0nd' format where 'n' is the total number of digits and
985 '%%'. Return 0 if OK, and -1 if format error */
986 int get_frame_filename(char *buf
, int buf_size
,
987 const char *path
, int number
)
991 int nd
, len
, c
, percentd_found
;
1002 while (*p
>= '0' && *p
<= '9') {
1003 nd
= nd
* 10 + *p
++ - '0';
1013 snprintf(buf1
, sizeof(buf1
), "%0*d", nd
, number
);
1015 if ((q
- buf
+ len
) > buf_size
- 1)
1017 memcpy(q
, buf1
, len
);
1025 if ((q
- buf
) < buf_size
- 1)
1029 if (!percentd_found
)
1038 static int gcd(INT64 a
, INT64 b
)
1051 void ticker_init(Ticker
*tick
, INT64 inrate
, INT64 outrate
)
1055 g
= gcd(inrate
, outrate
);
1059 tick
->value
= -outrate
/2;
1061 tick
->inrate
= inrate
;
1062 tick
->outrate
= outrate
;
1063 tick
->div
= tick
->outrate
/ tick
->inrate
;
1064 tick
->mod
= tick
->outrate
% tick
->inrate
;
1069 * Print on stdout a nice hexa dump of a buffer
1071 * @param size buffer size
1073 void av_hex_dump(UINT8
*buf
, int size
)
1077 for(i
=0;i
<size
;i
+=16) {
1084 printf(" %02x", buf
[i
+j
]);
1089 for(j
=0;j
<len
;j
++) {
1091 if (c
< ' ' || c
> '~')