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 (fmt == &rtp_demux && !strcmp(filename, "null"))) {
344 if (!fmt || must_open_file) {
345 /* if no file needed do not try to open one */
346 if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
351 url_setbufsize(&ic->pb, buf_size);
354 /* read probe data */
355 pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);
356 url_fseek(&ic->pb, 0, SEEK_SET);
360 /* guess file format */
362 fmt = av_probe_input_format(pd, 1);
365 /* if still no format found, error */
371 /* XXX: suppress this hack for redirectors */
372 #ifdef CONFIG_NETWORK
373 if (fmt == &redir_demux) {
374 err = redir_open(ic_ptr, &ic->pb);
383 /* check filename in case of an image number is expected */
384 if (ic->iformat->flags & AVFMT_NEEDNUMBER) {
385 if (filename_number_test(ic->filename) < 0) {
386 err = AVERROR_NUMEXPECTED;
391 /* allocate private data */
392 if (fmt->priv_data_size > 0) {
393 ic->priv_data = av_mallocz(fmt->priv_data_size);
394 if (!ic->priv_data) {
399 ic->priv_data = NULL;
401 /* default pts settings is MPEG like */
402 av_set_pts_info(ic, 33, 1, 90000);
404 err = ic->iformat->read_header(ic, ap);
410 if (!fmt || must_open_file) {
415 av_freep(&ic->priv_data);
423 * Read a packet from a media file
424 * @param s media file handle
425 * @param pkt is filled
426 * @return 0 if OK. AVERROR_xxx if error.
428 int av_read_packet(AVFormatContext *s, AVPacket *pkt)
432 pktl = s->packet_buffer;
434 /* read packet from packet buffer, if there is data */
436 s->packet_buffer = pktl->next;
440 return s->iformat->read_packet(s, pkt);
445 /* return TRUE if the stream has accurate timings for at least one component */
446 static int av_has_timings(AVFormatContext *ic)
451 for(i = 0;i < ic->nb_streams; i++) {
453 if (st->start_time != AV_NOPTS_VALUE &&
454 st->duration != AV_NOPTS_VALUE)
460 /* estimate the stream timings from the one of each components. Also
461 compute the global bitrate if possible */
462 static void av_update_stream_timings(AVFormatContext *ic)
464 int64_t start_time, end_time, end_time1;
468 start_time = MAXINT64;
470 for(i = 0;i < ic->nb_streams; i++) {
472 if (st->start_time != AV_NOPTS_VALUE) {
473 if (st->start_time < start_time)
474 start_time = st->start_time;
475 if (st->duration != AV_NOPTS_VALUE) {
476 end_time1 = st->start_time + st->duration;
477 if (end_time1 > end_time)
478 end_time = end_time1;
482 if (start_time != MAXINT64) {
483 ic->start_time = start_time;
484 if (end_time != MAXINT64) {
485 ic->duration = end_time - start_time;
486 if (ic->file_size > 0) {
487 /* compute the bit rate */
488 ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
489 (double)ic->duration;
496 static void fill_all_stream_timings(AVFormatContext *ic)
501 av_update_stream_timings(ic);
502 for(i = 0;i < ic->nb_streams; i++) {
504 if (st->start_time == AV_NOPTS_VALUE) {
505 st->start_time = ic->start_time;
506 st->duration = ic->duration;
511 static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
513 int64_t filesize, duration;
517 /* if bit_rate is already set, we believe it */
518 if (ic->bit_rate == 0) {
520 for(i=0;i<ic->nb_streams;i++) {
522 bit_rate += st->codec.bit_rate;
524 ic->bit_rate = bit_rate;
527 /* if duration is already set, we believe it */
528 if (ic->duration == AV_NOPTS_VALUE &&
530 ic->file_size != 0) {
531 filesize = ic->file_size;
533 duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
534 for(i = 0; i < ic->nb_streams; i++) {
536 if (st->start_time == AV_NOPTS_VALUE ||
537 st->duration == AV_NOPTS_VALUE) {
539 st->duration = duration;
546 static void flush_packet_queue(AVFormatContext *s)
551 pktl = s->packet_buffer;
554 s->packet_buffer = pktl->next;
559 #define DURATION_MAX_READ_SIZE 250000
561 /* only usable for MPEG-PS streams */
562 static void av_estimate_timings_from_pts(AVFormatContext *ic)
564 AVPacket pkt1, *pkt = &pkt1;
566 int read_size, i, ret;
567 int64_t start_time, end_time, end_time1;
568 int64_t filesize, offset, duration;
570 /* we read the first packets to get the first PTS (not fully
571 accurate, but it is enough now) */
572 url_fseek(&ic->pb, 0, SEEK_SET);
575 if (read_size >= DURATION_MAX_READ_SIZE)
577 /* if all info is available, we can stop */
578 for(i = 0;i < ic->nb_streams; i++) {
580 if (st->start_time == AV_NOPTS_VALUE)
583 if (i == ic->nb_streams)
586 ret = av_read_packet(ic, pkt);
589 read_size += pkt->size;
590 st = ic->streams[pkt->stream_index];
591 if (pkt->pts != AV_NOPTS_VALUE) {
592 if (st->start_time == AV_NOPTS_VALUE)
593 st->start_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
598 /* we compute the minimum start_time and use it as default */
599 start_time = MAXINT64;
600 for(i = 0; i < ic->nb_streams; i++) {
602 if (st->start_time != AV_NOPTS_VALUE &&
603 st->start_time < start_time)
604 start_time = st->start_time;
606 printf("start=%lld\n", start_time);
607 if (start_time != MAXINT64)
608 ic->start_time = start_time;
610 /* estimate the end time (duration) */
611 /* XXX: may need to support wrapping */
612 filesize = ic->file_size;
613 offset = filesize - DURATION_MAX_READ_SIZE;
617 /* flush packet queue */
618 flush_packet_queue(ic);
620 url_fseek(&ic->pb, offset, SEEK_SET);
623 if (read_size >= DURATION_MAX_READ_SIZE)
625 /* if all info is available, we can stop */
626 for(i = 0;i < ic->nb_streams; i++) {
628 if (st->duration == AV_NOPTS_VALUE)
631 if (i == ic->nb_streams)
634 ret = av_read_packet(ic, pkt);
637 read_size += pkt->size;
638 st = ic->streams[pkt->stream_index];
639 if (pkt->pts != AV_NOPTS_VALUE) {
640 end_time = (int64_t)((double)pkt->pts * ic->pts_num * (double)AV_TIME_BASE / ic->pts_den);
641 duration = end_time - st->start_time;
643 if (st->duration == AV_NOPTS_VALUE ||
644 st->duration < duration)
645 st->duration = duration;
651 /* estimate total duration */
653 for(i = 0;i < ic->nb_streams; i++) {
655 if (st->duration != AV_NOPTS_VALUE) {
656 end_time1 = st->start_time + st->duration;
657 if (end_time1 > end_time)
658 end_time = end_time1;
662 /* update start_time (new stream may have been created, so we do
664 if (ic->start_time != AV_NOPTS_VALUE) {
665 for(i = 0; i < ic->nb_streams; i++) {
667 if (st->start_time == AV_NOPTS_VALUE)
668 st->start_time = ic->start_time;
672 if (end_time != MININT64) {
673 /* put dummy values for duration if needed */
674 for(i = 0;i < ic->nb_streams; i++) {
676 if (st->duration == AV_NOPTS_VALUE &&
677 st->start_time != AV_NOPTS_VALUE)
678 st->duration = end_time - st->start_time;
680 ic->duration = end_time - ic->start_time;
683 url_fseek(&ic->pb, 0, SEEK_SET);
686 static void av_estimate_timings(AVFormatContext *ic)
691 /* get the file size, if possible */
692 if (ic->iformat->flags & AVFMT_NOFILE) {
695 h = url_fileno(&ic->pb);
696 file_size = url_filesize(h);
700 ic->file_size = file_size;
702 if (ic->iformat == &mpegps_demux) {
703 /* get accurate estimate from the PTSes */
704 av_estimate_timings_from_pts(ic);
705 } else if (av_has_timings(ic)) {
706 /* at least one components has timings - we use them for all
708 fill_all_stream_timings(ic);
710 /* less precise: use bit rate info */
711 av_estimate_timings_from_bit_rate(ic);
713 av_update_stream_timings(ic);
719 for(i = 0;i < ic->nb_streams; i++) {
721 printf("%d: start_time: %0.3f duration: %0.3f\n",
722 i, (double)st->start_time / AV_TIME_BASE,
723 (double)st->duration / AV_TIME_BASE);
725 printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
726 (double)ic->start_time / AV_TIME_BASE,
727 (double)ic->duration / AV_TIME_BASE,
728 ic->bit_rate / 1000);
733 /* state for codec information */
734 #define CSTATE_NOTFOUND 0
735 #define CSTATE_DECODING 1
736 #define CSTATE_FOUND 2
738 static int has_codec_parameters(AVCodecContext *enc)
741 switch(enc->codec_type) {
742 case CODEC_TYPE_AUDIO:
743 val = enc->sample_rate;
745 case CODEC_TYPE_VIDEO:
756 * Read the beginning of a media file to get stream information. This
757 * is useful for file formats with no headers such as MPEG. This
758 * function also compute the real frame rate in case of mpeg2 repeat
761 * @param ic media file handle
762 * @return >=0 if OK. AVERROR_xxx if error.
764 int av_find_stream_info(AVFormatContext *ic)
766 int i, count, ret, got_picture, size, read_size;
771 AVPacketList *pktl=NULL, **ppktl;
772 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
774 int min_read_size, max_read_size;
776 /* typical mpeg ts rate is 40 Mbits. DVD rate is about 10
777 Mbits. We read at most 0.2 second of file to find all streams */
779 /* XXX: base it on stream bitrate when possible */
780 if (ic->iformat == &mpegts_demux) {
781 /* maximum number of bytes we accept to read to find all the streams
783 min_read_size = 6000000;
785 min_read_size = 250000;
787 /* max read size is 2 seconds of video max */
788 max_read_size = min_read_size * 10;
790 /* set initial codec state */
791 for(i=0;i<ic->nb_streams;i++) {
793 if (has_codec_parameters(&st->codec))
794 st->codec_info_state = CSTATE_FOUND;
796 st->codec_info_state = CSTATE_NOTFOUND;
797 st->codec_info_nb_repeat_frames = 0;
798 st->codec_info_nb_real_frames = 0;
803 ppktl = &ic->packet_buffer;
805 /* check if one codec still needs to be handled */
806 for(i=0;i<ic->nb_streams;i++) {
808 if (st->codec_info_state != CSTATE_FOUND)
811 if (i == ic->nb_streams) {
812 /* NOTE: if the format has no header, then we need to read
813 some packets to get most of the streams, so we cannot
815 if (!(ic->iformat->flags & AVFMT_NOHEADER) ||
816 read_size >= min_read_size) {
817 /* if we found the info for all the codecs, we can stop */
822 /* we did not get all the codec info, but we read too much data */
823 if (read_size >= max_read_size) {
829 pktl = av_mallocz(sizeof(AVPacketList));
835 /* add the packet in the buffered packet list */
839 /* NOTE: a new stream can be added there if no header in file
842 if (ic->iformat->read_packet(ic, pkt) < 0) {
844 ret = -1; /* we could not have all the codec parameters before EOF */
845 if ((ic->iformat->flags & AVFMT_NOHEADER) &&
850 read_size += pkt->size;
852 /* open new codecs */
853 for(i=0;i<ic->nb_streams;i++) {
855 if (st->codec_info_state == CSTATE_NOTFOUND) {
856 /* set to found in case of error */
857 st->codec_info_state = CSTATE_FOUND;
858 codec = avcodec_find_decoder(st->codec.codec_id);
860 if(codec->capabilities & CODEC_CAP_TRUNCATED)
861 st->codec.flags |= CODEC_FLAG_TRUNCATED;
863 ret = avcodec_open(&st->codec, codec);
865 st->codec_info_state = CSTATE_DECODING;
870 st = ic->streams[pkt->stream_index];
871 if (st->codec_info_state == CSTATE_DECODING) {
872 /* decode the data and update codec parameters */
876 switch(st->codec.codec_type) {
877 case CODEC_TYPE_VIDEO:
878 ret = avcodec_decode_video(&st->codec, &picture,
879 &got_picture, ptr, size);
881 case CODEC_TYPE_AUDIO:
882 ret = avcodec_decode_audio(&st->codec, samples,
883 &got_picture, ptr, size);
890 /* if error, simply ignore because another packet
895 /* we got the parameters - now we can stop
896 examining this stream */
897 /* XXX: add a codec info so that we can decide if
898 the codec can repeat frames */
899 if (st->codec.codec_id == CODEC_ID_MPEG1VIDEO &&
900 ic->iformat != &mpegts_demux &&
901 st->codec.sub_id == 2) {
902 /* for mpeg2 video, we want to know the real
903 frame rate, so we decode 40 frames. In mpeg
904 TS case we do not do it because it would be
906 st->codec_info_nb_real_frames++;
907 st->codec_info_nb_repeat_frames += st->codec.coded_frame->repeat_pict;
910 if ((st->codec_info_nb_real_frames % 24) == 23) {
911 st->codec_info_nb_repeat_frames += 2;
914 /* stop after 40 frames */
915 if (st->codec_info_nb_real_frames >= 40) {
918 &st->r_frame_rate_base,
919 (int64_t)st->codec.frame_rate * st->codec_info_nb_real_frames,
920 (st->codec_info_nb_real_frames + (st->codec_info_nb_repeat_frames >> 1)) * st->codec.frame_rate_base,
926 st->codec_info_state = CSTATE_FOUND;
927 avcodec_close(&st->codec);
938 /* close each codec if there are opened */
939 for(i=0;i<ic->nb_streams;i++) {
941 if (st->codec_info_state == CSTATE_DECODING)
942 avcodec_close(&st->codec);
945 /* set real frame rate info */
946 for(i=0;i<ic->nb_streams;i++) {
948 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
949 if (!st->r_frame_rate){
950 st->r_frame_rate = st->codec.frame_rate;
951 st->r_frame_rate_base = st->codec.frame_rate_base;
957 av_estimate_timings(ic);
962 * Close a media file (but not its codecs)
964 * @param s media file handle
966 void av_close_input_file(AVFormatContext *s)
968 int i, must_open_file;
970 if (s->iformat->read_close)
971 s->iformat->read_close(s);
972 for(i=0;i<s->nb_streams;i++) {
973 av_free(s->streams[i]);
975 if (s->packet_buffer) {
976 AVPacketList *p, *p1;
977 p = s->packet_buffer;
980 av_free_packet(&p->pkt);
984 s->packet_buffer = NULL;
987 if ((s->iformat->flags & AVFMT_NOFILE) ||
988 (s->iformat == &rtp_demux && !strcmp(s->filename, "null"))) {
991 if (must_open_file) {
994 av_freep(&s->priv_data);
999 * Add a new stream to a media file. Can only be called in the
1000 * read_header function. If the flag AVFMT_NOHEADER is in the format
1001 * description, then new streams can be added in read_packet too.
1004 * @param s media file handle
1005 * @param id file format dependent stream id
1007 AVStream *av_new_stream(AVFormatContext *s, int id)
1011 if (s->nb_streams >= MAX_STREAMS)
1014 st = av_mallocz(sizeof(AVStream));
1017 avcodec_get_context_defaults(&st->codec);
1019 st->index = s->nb_streams;
1021 st->start_time = AV_NOPTS_VALUE;
1022 st->duration = AV_NOPTS_VALUE;
1023 s->streams[s->nb_streams++] = st;
1027 /************************************************************/
1028 /* output media file */
1030 int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1034 if (s->oformat->priv_data_size > 0) {
1035 s->priv_data = av_mallocz(s->oformat->priv_data_size);
1037 return AVERROR_NOMEM;
1039 s->priv_data = NULL;
1041 if (s->oformat->set_parameters) {
1042 ret = s->oformat->set_parameters(s, ap);
1050 * allocate the stream private data and write the stream header to an
1053 * @param s media file handle
1054 * @return 0 if OK. AVERROR_xxx if error.
1056 int av_write_header(AVFormatContext *s)
1061 /* default pts settings is MPEG like */
1062 av_set_pts_info(s, 33, 1, 90000);
1063 ret = s->oformat->write_header(s);
1067 /* init PTS generation */
1068 for(i=0;i<s->nb_streams;i++) {
1071 switch (st->codec.codec_type) {
1072 case CODEC_TYPE_AUDIO:
1073 av_frac_init(&st->pts, 0, 0,
1074 (int64_t)s->pts_num * st->codec.sample_rate);
1076 case CODEC_TYPE_VIDEO:
1077 av_frac_init(&st->pts, 0, 0,
1078 (int64_t)s->pts_num * st->codec.frame_rate);
1088 * Write a packet to an output media file. The packet shall contain
1089 * one audio or video frame.
1091 * @param s media file handle
1092 * @param stream_index stream index
1093 * @param buf buffer containing the frame data
1094 * @param size size of buffer
1095 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
1097 int av_write_frame(AVFormatContext *s, int stream_index, const uint8_t *buf,
1102 int ret, frame_size;
1104 st = s->streams[stream_index];
1105 pts_mask = (1LL << s->pts_wrap_bits) - 1;
1106 ret = s->oformat->write_packet(s, stream_index, (uint8_t *)buf, size,
1107 st->pts.val & pts_mask);
1112 switch (st->codec.codec_type) {
1113 case CODEC_TYPE_AUDIO:
1114 if (st->codec.frame_size <= 1) {
1115 frame_size = size / st->codec.channels;
1116 /* specific hack for pcm codecs because no frame size is provided */
1117 switch(st->codec.codec_id) {
1118 case CODEC_ID_PCM_S16LE:
1119 case CODEC_ID_PCM_S16BE:
1120 case CODEC_ID_PCM_U16LE:
1121 case CODEC_ID_PCM_U16BE:
1128 frame_size = st->codec.frame_size;
1130 av_frac_add(&st->pts,
1131 (int64_t)s->pts_den * frame_size);
1133 case CODEC_TYPE_VIDEO:
1134 av_frac_add(&st->pts,
1135 (int64_t)s->pts_den * st->codec.frame_rate_base);
1144 * write the stream trailer to an output media file and and free the
1145 * file private data.
1147 * @param s media file handle
1148 * @return 0 if OK. AVERROR_xxx if error. */
1149 int av_write_trailer(AVFormatContext *s)
1152 ret = s->oformat->write_trailer(s);
1153 av_freep(&s->priv_data);
1157 /* "user interface" functions */
1159 void dump_format(AVFormatContext *ic,
1167 fprintf(stderr, "%s #%d, %s, %s '%s':\n",
1168 is_output ? "Output" : "Input",
1170 is_output ? ic->oformat->name : ic->iformat->name,
1171 is_output ? "to" : "from", url);
1173 printf(" Duration: ");
1174 if (ic->duration != AV_NOPTS_VALUE) {
1175 int hours, mins, secs, us;
1176 secs = ic->duration / AV_TIME_BASE;
1177 us = ic->duration % AV_TIME_BASE;
1182 printf("%02d:%02d:%02d.%01d", hours, mins, secs,
1183 (10 * us) / AV_TIME_BASE);
1187 printf(", bitrate: ");
1189 printf("%d kb/s", ic->bit_rate / 1000);
1195 for(i=0;i<ic->nb_streams;i++) {
1196 AVStream *st = ic->streams[i];
1197 avcodec_string(buf, sizeof(buf), &st->codec, is_output);
1198 fprintf(stderr, " Stream #%d.%d", index, i);
1199 /* the pid is an important information, so we display it */
1200 /* XXX: add a generic system */
1202 flags = ic->oformat->flags;
1204 flags = ic->iformat->flags;
1205 if (flags & AVFMT_SHOW_IDS) {
1206 fprintf(stderr, "[0x%x]", st->id);
1208 fprintf(stderr, ": %s\n", buf);
1215 int frame_rate, frame_rate_base;
1218 static AbvEntry frame_abvs[] = {
1219 { "ntsc", 352, 240, 30000, 1001 },
1220 { "pal", 352, 288, 25, 1 },
1221 { "film", 352, 240, 24, 1 },
1222 { "ntsc-film", 352, 240, 24000, 1001 },
1223 { "sqcif", 128, 96, 0, 0 },
1224 { "qcif", 176, 144, 0, 0 },
1225 { "cif", 352, 288, 0, 0 },
1226 { "4cif", 704, 576, 0, 0 },
1229 int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
1232 int n = sizeof(frame_abvs) / sizeof(AbvEntry);
1234 int frame_width = 0, frame_height = 0;
1237 if (!strcmp(frame_abvs[i].abv, str)) {
1238 frame_width = frame_abvs[i].width;
1239 frame_height = frame_abvs[i].height;
1245 frame_width = strtol(p, (char **)&p, 10);
1248 frame_height = strtol(p, (char **)&p, 10);
1250 if (frame_width <= 0 || frame_height <= 0)
1252 *width_ptr = frame_width;
1253 *height_ptr = frame_height;
1257 int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
1262 /* First, we check our abbreviation table */
1263 for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
1264 if (!strcmp(frame_abvs[i].abv, arg)) {
1265 *frame_rate = frame_abvs[i].frame_rate;
1266 *frame_rate_base = frame_abvs[i].frame_rate_base;
1270 /* Then, we try to parse it as fraction */
1271 cp = strchr(arg, '/');
1274 *frame_rate = strtol(arg, &cpp, 10);
1275 if (cpp != arg || cpp == cp)
1276 *frame_rate_base = strtol(cp+1, &cpp, 10);
1281 /* Finally we give up and parse it as double */
1282 *frame_rate_base = DEFAULT_FRAME_RATE_BASE;
1283 *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
1285 if (!*frame_rate || !*frame_rate_base)
1291 int64_t av_gettime(void)
1296 return ((int64_t)tb.time * int64_t_C(1000) + (int64_t)tb.millitm) * int64_t_C(1000);
1299 gettimeofday(&tv,NULL);
1300 return (int64_t)tv.tv_sec * 1000000 + tv.tv_usec;
1304 static time_t mktimegm(struct tm *tm)
1308 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
1316 (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 719469);
1318 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
1324 * - If not a duration:
1325 * [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
1326 * Time is localtime unless Z is suffixed to the end. In this case GMT
1327 * Return the date in micro seconds since 1970
1329 * HH[:MM[:SS[.m...]]]
1332 int64_t parse_date(const char *datestr, int duration)
1338 static const char *date_fmt[] = {
1342 static const char *time_fmt[] = {
1349 time_t now = time(0);
1351 len = strlen(datestr);
1353 lastch = datestr[len - 1];
1356 is_utc = (lastch == 'z' || lastch == 'Z');
1358 memset(&dt, 0, sizeof(dt));
1363 for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
1364 q = strptime(p, date_fmt[i], &dt);
1374 dt = *localtime(&now);
1376 dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
1381 if (*p == 'T' || *p == 't' || *p == ' ')
1384 for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
1385 q = strptime(p, time_fmt[i], &dt);
1391 q = strptime(p, time_fmt[0], &dt);
1393 dt.tm_sec = strtol(p, (char **)&q, 10);
1399 /* Now we have all the fields that we can get */
1404 return now * int64_t_C(1000000);
1408 t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
1410 dt.tm_isdst = -1; /* unknown */
1423 for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
1426 val += n * (*q - '0');
1433 /* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
1435 int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
1445 while (*p != '\0' && *p != '=' && *p != '&') {
1446 if ((q - tag) < sizeof(tag) - 1)
1454 while (*p != '&' && *p != '\0') {
1455 if ((q - arg) < arg_size - 1) {
1465 if (!strcmp(tag, tag1))
1474 /* Return in 'buf' the path with '%d' replaced by number. Also handles
1475 the '%0nd' format where 'n' is the total number of digits and
1476 '%%'. Return 0 if OK, and -1 if format error */
1477 int get_frame_filename(char *buf, int buf_size,
1478 const char *path, int number)
1482 int nd, len, c, percentd_found;
1494 while (isdigit(*p)) {
1495 nd = nd * 10 + *p++ - '0';
1498 if (c == '*' && nd > 0) {
1499 // The nd field is actually the modulus
1500 number = number % nd;
1504 } while (isdigit(c));
1513 snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
1515 if ((q - buf + len) > buf_size - 1)
1517 memcpy(q, buf1, len);
1525 if ((q - buf) < buf_size - 1)
1529 if (!percentd_found)
1540 * Print on stdout a nice hexa dump of a buffer
1542 * @param size buffer size
1544 void av_hex_dump(uint8_t *buf, int size)
1548 for(i=0;i<size;i+=16) {
1555 printf(" %02x", buf[i+j]);
1560 for(j=0;j<len;j++) {
1562 if (c < ' ' || c > '~')
1570 void url_split(char *proto, int proto_size,
1571 char *hostname, int hostname_size,
1573 char *path, int path_size,
1584 while (*p != ':' && *p != '\0') {
1585 if ((q - proto) < proto_size - 1)
1594 if (hostname_size > 0)
1604 while (*p != ':' && *p != '/' && *p != '?' && *p != '\0') {
1605 if ((q - hostname) < hostname_size - 1)
1609 if (hostname_size > 0)
1613 port = strtoul(p, (char **)&p, 10);
1618 pstrcpy(path, path_size, p);
1622 * Set the pts for a given stream
1624 * @param pts_wrap_bits number of bits effectively used by the pts
1625 * (used for wrap control, 33 is the value for MPEG)
1626 * @param pts_num numerator to convert to seconds (MPEG: 1)
1627 * @param pts_den denominator to convert to seconds (MPEG: 90000)
1629 void av_set_pts_info(AVFormatContext *s, int pts_wrap_bits,
1630 int pts_num, int pts_den)
1632 s->pts_wrap_bits = pts_wrap_bits;
1633 s->pts_num = pts_num;
1634 s->pts_den = pts_den;
1637 /* fraction handling */
1640 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
1641 * as 0 <= num < den.
1643 * @param f fractional number
1644 * @param val integer value
1645 * @param num must be >= 0
1646 * @param den must be >= 1
1648 void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
1660 /* set f to (val + 0.5) */
1661 void av_frac_set(AVFrac *f, int64_t val)
1664 f->num = f->den >> 1;
1668 * Fractionnal addition to f: f = f + (incr / f->den)
1670 * @param f fractional number
1671 * @param incr increment, can be positive or negative
1673 void av_frac_add(AVFrac *f, int64_t incr)
1677 num = f->num + incr;
1680 f->val += num / den;
1686 } else if (num >= den) {
1687 f->val += num / den;
1694 * register a new image format
1695 * @param img_fmt Image format descriptor
1697 void av_register_image_format(AVImageFormat *img_fmt)
1701 p = &first_image_format;
1702 while (*p != NULL) p = &(*p)->next;
1704 img_fmt->next = NULL;
1707 /* guess image format */
1708 AVImageFormat *av_probe_image_format(AVProbeData *pd)
1710 AVImageFormat *fmt1, *fmt;
1711 int score, score_max;
1715 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1716 if (fmt1->img_probe) {
1717 score = fmt1->img_probe(pd);
1718 if (score > score_max) {
1727 AVImageFormat *guess_image_format(const char *filename)
1729 AVImageFormat *fmt1;
1731 for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
1732 if (fmt1->extensions && match_ext(filename, fmt1->extensions))
1739 * Read an image from a stream.
1740 * @param gb byte stream containing the image
1741 * @param fmt image format, NULL if probing is required
1743 int av_read_image(ByteIOContext *pb, const char *filename,
1745 int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
1747 char buf[PROBE_BUF_SIZE];
1748 AVProbeData probe_data, *pd = &probe_data;
1753 pd->filename = filename;
1755 pos = url_ftell(pb);
1756 pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
1757 url_fseek(pb, pos, SEEK_SET);
1758 fmt = av_probe_image_format(pd);
1761 return AVERROR_NOFMT;
1762 ret = fmt->img_read(pb, alloc_cb, opaque);
1767 * Write an image to a stream.
1768 * @param pb byte stream for the image output
1769 * @param fmt image format
1770 * @param img image data and informations
1772 int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
1774 return fmt->img_write(pb, img);