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
19 #define HAVE_AV_CONFIG_H
21 #include "framehook.h"
26 #include <sys/ioctl.h>
29 #include <sys/resource.h>
35 #define MAXINT64 INT64_C(0x7fffffffffffffff)
40 #define HAS_ARG 0x0001
41 #define OPT_BOOL 0x0002
42 #define OPT_EXPERT 0x0004
43 #define OPT_STRING 0x0008
53 /* select an input stream for an output stream */
54 typedef struct AVStreamMap {
59 extern const OptionDef options[];
65 static AVFormatContext *input_files[MAX_FILES];
66 static int nb_input_files = 0;
68 static AVFormatContext *output_files[MAX_FILES];
69 static int nb_output_files = 0;
71 static AVStreamMap stream_maps[MAX_FILES];
72 static int nb_stream_maps;
74 static AVInputFormat *file_iformat;
75 static AVOutputFormat *file_oformat;
76 static int frame_width = 160;
77 static int frame_height = 128;
78 static int frame_topBand = 0;
79 static int frame_bottomBand = 0;
80 static int frame_leftBand = 0;
81 static int frame_rightBand = 0;
82 static int frame_rate = 25 * FRAME_RATE_BASE;
83 static int video_bit_rate = 200*1000;
84 static int video_bit_rate_tolerance = 4000*1000;
85 static int video_qscale = 0;
86 static int video_qmin = 2;
87 static int video_qmax = 31;
88 static int video_qdiff = 3;
89 static float video_qblur = 0.5;
90 static float video_qcomp = 0.5;
91 #if 0 //experimental, (can be removed)
92 static float video_rc_qsquish=1.0;
93 static float video_rc_qmod_amp=0;
94 static int video_rc_qmod_freq=0;
96 static char *video_rc_override_string=NULL;
97 static char *video_rc_eq="tex^qComp";
98 static int video_rc_buffer_size=0;
99 static float video_rc_buffer_aggressivity=1.0;
100 static int video_rc_max_rate=0;
101 static int video_rc_min_rate=0;
102 static float video_rc_initial_cplx=0;
103 static float video_b_qfactor = 1.25;
104 static float video_b_qoffset = 1.25;
105 static float video_i_qfactor = -0.8;
106 static float video_i_qoffset = 0.0;
107 static int me_method = 0;
108 static int video_disable = 0;
109 static int video_codec_id = CODEC_ID_NONE;
110 static int same_quality = 0;
111 static int b_frames = 0;
112 static int use_hq = 0;
113 static int use_4mv = 0;
114 static int do_deinterlace = 0;
115 static int workaround_bugs = FF_BUG_AUTODETECT;
116 static int error_resilience = 2;
117 static int error_concealment = 3;
118 static int dct_algo = 0;
119 static int idct_algo = 0;
120 static int use_part = 0;
121 static int packet_size = 0;
123 static int gop_size = 12;
124 static int intra_only = 0;
125 static int audio_sample_rate = 44100;
126 static int audio_bit_rate = 64000;
127 static int audio_disable = 0;
128 static int audio_channels = 1;
129 static int audio_codec_id = CODEC_ID_NONE;
131 static INT64 recording_time = 0;
132 static int file_overwrite = 0;
133 static char *str_title = NULL;
134 static char *str_author = NULL;
135 static char *str_copyright = NULL;
136 static char *str_comment = NULL;
137 static int do_benchmark = 0;
138 static int do_hex_dump = 0;
139 static int do_play = 0;
140 static int do_psnr = 0;
141 static int do_vstats = 0;
142 static int do_pass = 0;
143 static char *pass_logfilename = NULL;
144 static int audio_stream_copy = 0;
145 static int video_stream_copy = 0;
147 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
149 #if !defined(CONFIG_AUDIO_OSS) && !defined(CONFIG_AUDIO_BEOS)
150 const char *audio_device = "none";
152 #ifndef CONFIG_VIDEO4LINUX
153 const char *v4l_device = "none";
156 typedef struct AVOutputStream {
157 int file_index; /* file index */
158 int index; /* stream index in the output file */
159 int source_index; /* AVInputStream index */
160 AVStream *st; /* stream in the output file */
161 int encoding_needed; /* true if encoding needed for this stream */
163 /* input pts and corresponding output pts
166 double sync_ipts_offset;
169 AVPicture pict_tmp; /* temporary image for resizing */
171 ImgReSampleContext *img_resample_ctx; /* for image resampling */
175 ReSampleContext *resample; /* for audio resampling */
176 FifoBuffer fifo; /* for compression: one audio fifo per codec */
180 typedef struct AVInputStream {
184 int discard; /* true if stream data should be discarded */
185 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
186 INT64 sample_index; /* current sample */
187 int frame_decoded; /* true if a video or audio frame has been decoded */
190 typedef struct AVInputFile {
191 int eof_reached; /* true if eof reached */
192 int ist_index; /* index of first stream in ist_table */
193 int buffer_size; /* current total buffer size */
194 int buffer_size_max; /* buffer size at which we consider we can stop
196 int nb_streams; /* nb streams we are aware of */
201 /* init terminal so that we can grab keys */
202 static struct termios oldtty;
204 static void term_exit(void)
206 tcsetattr (0, TCSANOW, &oldtty);
209 static void term_init(void)
216 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
217 |INLCR|IGNCR|ICRNL|IXON);
218 tty.c_oflag |= OPOST;
219 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
220 tty.c_cflag &= ~(CSIZE|PARENB);
225 tcsetattr (0, TCSANOW, &tty);
228 #ifdef CONFIG_BEOS_NETSERVER
229 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
233 /* read a key without blocking */
234 static int read_key(void)
238 #ifndef CONFIG_BEOS_NETSERVER
246 n = select(1, &rfds, NULL, NULL, &tv);
260 /* no interactive support */
261 static void term_exit(void)
265 static void term_init(void)
269 static int read_key(void)
276 int read_ffserver_streams(AVFormatContext *s, const char *filename)
281 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
284 /* copy stream format */
285 s->nb_streams = ic->nb_streams;
286 for(i=0;i<ic->nb_streams;i++) {
289 st = av_mallocz(sizeof(AVFormatContext));
290 memcpy(st, ic->streams[i], sizeof(AVStream));
294 av_close_input_file(ic);
298 #define MAX_AUDIO_PACKET_SIZE 16384
300 static void do_audio_out(AVFormatContext *s,
303 unsigned char *buf, int size)
306 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
307 UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
308 int size_out, frame_bytes, ret;
311 enc = &ost->st->codec;
313 if (ost->audio_resample) {
315 size_out = audio_resample(ost->resample,
316 (short *)buftmp, (short *)buf,
317 size / (ist->st->codec.channels * 2));
318 size_out = size_out * enc->channels * 2;
324 /* now encode as many frames as possible */
325 if (enc->frame_size > 1) {
326 /* output resampled raw samples */
327 fifo_write(&ost->fifo, buftmp, size_out,
330 frame_bytes = enc->frame_size * 2 * enc->channels;
332 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
333 &ost->fifo.rptr) == 0) {
334 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
336 av_write_frame(s, ost->index, audio_out, ret);
339 /* output a pcm frame */
340 /* XXX: change encoding codec API to avoid this ? */
341 switch(enc->codec->id) {
342 case CODEC_ID_PCM_S16LE:
343 case CODEC_ID_PCM_S16BE:
344 case CODEC_ID_PCM_U16LE:
345 case CODEC_ID_PCM_U16BE:
348 size_out = size_out >> 1;
351 ret = avcodec_encode_audio(enc, audio_out, size_out,
353 av_write_frame(s, ost->index, audio_out, ret);
357 /* write a picture to a raw mux */
358 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
359 int pix_fmt, int w, int h)
361 UINT8 *buf, *src, *dest;
364 /* XXX: not efficient, should add test if we can take
365 directly the AVPicture */
367 case PIX_FMT_YUV420P:
368 size = avpicture_get_size(pix_fmt, w, h);
369 buf = av_malloc(size);
378 src = picture->data[i];
380 memcpy(dest, src, w);
382 src += picture->linesize[i];
386 case PIX_FMT_YUV422P:
388 buf = av_malloc(size);
396 src = picture->data[i];
398 memcpy(dest, src, w);
400 src += picture->linesize[i];
404 case PIX_FMT_YUV444P:
406 buf = av_malloc(size);
411 src = picture->data[i];
413 memcpy(dest, src, w);
415 src += picture->linesize[i];
421 buf = av_malloc(size);
425 src = picture->data[0];
427 memcpy(dest, src, w * 2);
429 src += picture->linesize[0];
435 buf = av_malloc(size);
439 src = picture->data[0];
441 memcpy(dest, src, w * 3);
443 src += picture->linesize[0];
449 av_write_frame(s, index, buf, size);
453 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
457 AVPicture picture_tmp;
460 dec = &ist->st->codec;
462 /* deinterlace : must be done before any resize */
463 if (do_deinterlace) {
466 /* create temporary picture */
467 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
468 buf = av_malloc(size);
472 picture2 = &picture_tmp;
473 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
475 if (avpicture_deinterlace(picture2, picture,
476 dec->pix_fmt, dec->width, dec->height) < 0) {
477 /* if error, do not deinterlace */
486 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
488 if (picture != picture2)
489 *picture = *picture2;
493 /* we begin to correct av delay at this threshold */
494 #define AV_DELAY_MAX 0.100
496 static void do_video_out(AVFormatContext *s,
500 int *frame_size, AVOutputStream *audio_sync)
502 int nb_frames, i, ret;
503 AVPicture *picture, *pict;
504 AVPicture picture_tmp1;
505 static UINT8 *video_buffer;
506 UINT8 *buf = NULL, *buf1 = NULL;
507 AVCodecContext *enc, *dec;
509 #define VIDEO_BUFFER_SIZE (1024*1024)
511 enc = &ost->st->codec;
512 dec = &ist->st->codec;
514 /* by default, we output a single frame */
517 /* NOTE: the A/V sync is always done by considering the audio is
518 the master clock. It is suffisant for transcoding or playing,
519 but not for the general case */
521 /* compute the A-V delay and duplicate/remove frames if needed */
522 double adelta, vdelta, apts, vpts, av_delay;
524 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
525 ost->sync_ipts != AV_NOPTS_VALUE) {
527 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
528 s->pts_num / s->pts_den;
529 apts = audio_sync->sync_ipts + adelta;
531 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
532 s->pts_num / s->pts_den;
533 vpts = ost->sync_ipts + vdelta;
535 av_delay = apts - vpts;
536 // printf("delay=%f\n", av_delay);
537 if (av_delay < -AV_DELAY_MAX)
539 else if (av_delay > AV_DELAY_MAX)
545 if (ost->sync_ipts != AV_NOPTS_VALUE) {
546 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
547 if (vdelta < 100 && vdelta > -100) {
548 if (vdelta < -AV_DELAY_MAX)
550 else if (vdelta > AV_DELAY_MAX)
553 ost->sync_ipts_offset -= vdelta;
558 static char *action[] = { "drop frame", "copy frame", "dup frame" };
559 printf("Input PTS %12.6f, output PTS %12.6f: %s\n",
560 (double) ost->sync_ipts, (double) ost->st->pts.val * s->pts_num / s->pts_den,
570 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
574 /* convert pixel format if needed */
575 if (enc->pix_fmt != dec->pix_fmt) {
578 /* create temporary picture */
579 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
580 buf = av_malloc(size);
583 pict = &picture_tmp1;
584 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
586 if (img_convert(pict, enc->pix_fmt,
587 picture1, dec->pix_fmt,
588 dec->width, dec->height) < 0) {
589 fprintf(stderr, "pixel format conversion not handled\n");
596 /* XXX: resampling could be done before raw format convertion in
597 some cases to go faster */
598 /* XXX: only works for YUV420P */
599 if (ost->video_resample) {
600 picture = &ost->pict_tmp;
601 img_resample(ost->img_resample_ctx, picture, pict);
605 /* duplicates frame if needed */
606 /* XXX: pb because no interleaving */
607 for(i=0;i<nb_frames;i++) {
608 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
609 AVVideoFrame big_picture;
611 memset(&big_picture, 0, sizeof(AVVideoFrame));
612 *(AVPicture*)&big_picture= *picture;
614 /* handles sameq here. This is not correct because it may
615 not be a global option */
617 big_picture.quality = ist->st->quality;
619 big_picture.quality = ost->st->quality;
621 ret = avcodec_encode_video(enc,
622 video_buffer, VIDEO_BUFFER_SIZE,
624 //enc->frame_number = enc->real_pict_num;
625 av_write_frame(s, ost->index, video_buffer, ret);
627 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
628 // enc->frame_number-1, enc->real_pict_num, ret,
630 /* if two pass, output log */
631 if (ost->logfile && enc->stats_out) {
632 fprintf(ost->logfile, "%s", enc->stats_out);
635 if (s->oformat->flags & AVFMT_RAWPICTURE) {
636 /* raw pictures are written as AVPicture structure to
637 avoid any copies. We support temorarily the older
639 av_write_frame(s, ost->index,
640 (UINT8 *)picture, sizeof(AVPicture));
642 write_picture(s, ost->index, picture, enc->pix_fmt,
643 enc->width, enc->height);
653 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
656 static FILE *fvstats=NULL;
657 static INT64 total_size = 0;
664 double ti1, bitrate, avg_bitrate;
668 today = localtime(&today2);
669 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
672 fvstats = fopen(filename,"w");
680 enc = &ost->st->codec;
681 total_size += frame_size;
682 if (enc->codec_type == CODEC_TYPE_VIDEO) {
683 frame_number = ost->frame_number;
684 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_picture->quality);
686 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
688 fprintf(fvstats,"f_size= %6d ", frame_size);
689 /* compute pts value */
690 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
694 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
695 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
696 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
697 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
698 fprintf(fvstats,"type= %s\n", enc->coded_picture->key_frame == 1 ? "I" : "P");
702 void print_report(AVFormatContext **output_files,
703 AVOutputStream **ost_table, int nb_ostreams,
708 AVFormatContext *oc, *os;
711 int frame_number, vid, i;
712 double bitrate, ti1, pts;
713 static INT64 last_time = -1;
715 if (!is_last_report) {
717 /* display the report every 0.5 seconds */
718 cur_time = av_gettime();
719 if (last_time == -1) {
720 last_time = cur_time;
723 if ((cur_time - last_time) < 500000)
725 last_time = cur_time;
729 oc = output_files[0];
731 total_size = url_ftell(&oc->pb);
736 for(i=0;i<nb_ostreams;i++) {
738 os = output_files[ost->file_index];
739 enc = &ost->st->codec;
740 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
741 sprintf(buf + strlen(buf), "q=%2.1f ",
742 enc->coded_picture->quality);
744 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
745 frame_number = ost->frame_number;
746 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
747 frame_number, enc->coded_picture ? enc->coded_picture->quality : 0);
749 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
752 /* compute min output value */
753 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
754 if ((pts < ti1) && (pts > 0))
759 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
761 sprintf(buf + strlen(buf),
762 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
763 (double)total_size / 1024, ti1, bitrate);
765 fprintf(stderr, "%s ", buf);
767 if (is_last_report) {
768 fprintf(stderr, "\n");
770 fprintf(stderr, "\r");
776 * The following code is the main loop of the file converter
778 static int av_encode(AVFormatContext **output_files,
780 AVFormatContext **input_files,
782 AVStreamMap *stream_maps, int nb_stream_maps)
784 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
785 AVFormatContext *is, *os;
786 AVCodecContext *codec, *icodec;
787 AVOutputStream *ost, **ost_table = NULL;
788 AVInputStream *ist, **ist_table = NULL;
789 AVInputFile *file_table;
790 AVFormatContext *stream_no_data;
793 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
797 /* input stream init */
799 for(i=0;i<nb_input_files;i++) {
801 file_table[i].ist_index = j;
802 file_table[i].nb_streams = is->nb_streams;
807 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
811 for(i=0;i<nb_istreams;i++) {
812 ist = av_mallocz(sizeof(AVInputStream));
818 for(i=0;i<nb_input_files;i++) {
820 for(k=0;k<is->nb_streams;k++) {
821 ist = ist_table[j++];
822 ist->st = is->streams[k];
825 ist->discard = 1; /* the stream is discarded by default
830 /* output stream init */
832 for(i=0;i<nb_output_files;i++) {
833 os = output_files[i];
834 nb_ostreams += os->nb_streams;
836 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
837 fprintf(stderr, "Number of stream maps must match number of output streams\n");
841 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
844 for(i=0;i<nb_ostreams;i++) {
845 ost = av_mallocz(sizeof(AVOutputStream));
852 for(k=0;k<nb_output_files;k++) {
853 os = output_files[k];
854 for(i=0;i<os->nb_streams;i++) {
856 ost = ost_table[n++];
859 ost->st = os->streams[i];
860 if (nb_stream_maps > 0) {
861 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
862 stream_maps[n-1].stream_index;
864 /* get corresponding input stream index : we select the first one with the right type */
866 for(j=0;j<nb_istreams;j++) {
869 ist->st->codec.codec_type == ost->st->codec.codec_type) {
870 ost->source_index = j;
876 /* try again and reuse existing stream */
877 for(j=0;j<nb_istreams;j++) {
879 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
880 ost->source_index = j;
885 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
886 ost->file_index, ost->index);
891 ist = ist_table[ost->source_index];
896 /* for each output stream, we compute the right encoding parameters */
897 for(i=0;i<nb_ostreams;i++) {
899 ist = ist_table[ost->source_index];
901 codec = &ost->st->codec;
902 icodec = &ist->st->codec;
904 if (ost->st->stream_copy) {
905 /* if stream_copy is selected, no need to decode or encode */
906 codec->codec_id = icodec->codec_id;
907 codec->codec_type = icodec->codec_type;
908 codec->codec_tag = icodec->codec_tag;
909 codec->bit_rate = icodec->bit_rate;
910 switch(codec->codec_type) {
911 case CODEC_TYPE_AUDIO:
912 codec->sample_rate = icodec->sample_rate;
913 codec->channels = icodec->channels;
915 case CODEC_TYPE_VIDEO:
916 codec->frame_rate = icodec->frame_rate;
917 codec->width = icodec->width;
918 codec->height = icodec->height;
924 switch(codec->codec_type) {
925 case CODEC_TYPE_AUDIO:
926 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
929 if (codec->channels == icodec->channels &&
930 codec->sample_rate == icodec->sample_rate) {
931 ost->audio_resample = 0;
933 if (codec->channels != icodec->channels &&
934 icodec->codec_id == CODEC_ID_AC3) {
935 /* Special case for 5:1 AC3 input */
936 /* and mono or stereo output */
937 /* Request specific number of channels */
938 icodec->channels = codec->channels;
939 if (codec->sample_rate == icodec->sample_rate)
940 ost->audio_resample = 0;
942 ost->audio_resample = 1;
943 ost->resample = audio_resample_init(codec->channels, icodec->channels,
945 icodec->sample_rate);
947 /* Request specific number of channels */
948 icodec->channels = codec->channels;
950 ost->audio_resample = 1;
951 ost->resample = audio_resample_init(codec->channels, icodec->channels,
953 icodec->sample_rate);
956 ist->decoding_needed = 1;
957 ost->encoding_needed = 1;
959 case CODEC_TYPE_VIDEO:
960 if (codec->width == icodec->width &&
961 codec->height == icodec->height) {
962 ost->video_resample = 0;
965 ost->video_resample = 1;
966 buf = av_malloc((codec->width * codec->height * 3) / 2);
969 ost->pict_tmp.data[0] = buf;
970 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
971 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
972 ost->pict_tmp.linesize[0] = codec->width;
973 ost->pict_tmp.linesize[1] = codec->width / 2;
974 ost->pict_tmp.linesize[2] = codec->width / 2;
976 ost->img_resample_ctx = img_resample_full_init(
977 ost->st->codec.width, ost->st->codec.height,
978 ist->st->codec.width, ist->st->codec.height,
979 frame_topBand, frame_bottomBand,
980 frame_leftBand, frame_rightBand);
982 ost->encoding_needed = 1;
983 ist->decoding_needed = 1;
989 if (ost->encoding_needed &&
990 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
991 char logfilename[1024];
996 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
998 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
999 if (codec->flags & CODEC_FLAG_PASS1) {
1000 f = fopen(logfilename, "w");
1002 perror(logfilename);
1007 /* read the log file */
1008 f = fopen(logfilename, "r");
1010 perror(logfilename);
1013 fseek(f, 0, SEEK_END);
1015 fseek(f, 0, SEEK_SET);
1016 logbuffer = av_malloc(size + 1);
1018 fprintf(stderr, "Could not allocate log buffer\n");
1021 fread(logbuffer, 1, size, f);
1023 logbuffer[size] = '\0';
1024 codec->stats_in = logbuffer;
1030 /* dump the file output parameters - cannot be done before in case
1032 for(i=0;i<nb_output_files;i++) {
1033 dump_format(output_files[i], i, output_files[i]->filename, 1);
1036 /* dump the stream mapping */
1037 fprintf(stderr, "Stream mapping:\n");
1038 for(i=0;i<nb_ostreams;i++) {
1040 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1041 ist_table[ost->source_index]->file_index,
1042 ist_table[ost->source_index]->index,
1047 /* open each encoder */
1048 for(i=0;i<nb_ostreams;i++) {
1050 if (ost->encoding_needed) {
1052 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1054 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1055 ost->file_index, ost->index);
1058 if (avcodec_open(&ost->st->codec, codec) < 0) {
1059 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1060 ost->file_index, ost->index);
1066 /* open each decoder */
1067 for(i=0;i<nb_istreams;i++) {
1069 if (ist->decoding_needed) {
1071 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1073 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1074 ist->st->codec.codec_id, ist->file_index, ist->index);
1077 if (avcodec_open(&ist->st->codec, codec) < 0) {
1078 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1079 ist->file_index, ist->index);
1082 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1083 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1084 ist->frame_decoded = 1;
1089 for(i=0;i<nb_istreams;i++) {
1093 /* compute buffer size max (should use a complete heuristic) */
1094 for(i=0;i<nb_input_files;i++) {
1095 file_table[i].buffer_size_max = 2048;
1098 /* open files and write file headers */
1099 for(i=0;i<nb_output_files;i++) {
1100 os = output_files[i];
1101 if (av_write_header(os) < 0) {
1102 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1108 #ifndef CONFIG_WIN32
1110 fprintf(stderr, "Press [q] to stop encoding\n");
1112 fprintf(stderr, "Press [q] to stop playing\n");
1121 int file_index, ist_index;
1126 int data_size, got_picture;
1128 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1129 void *buffer_to_free;
1133 /* if 'q' pressed, exits */
1135 /* read_key() returns 0 on EOF */
1141 /* select the stream that we must read now by looking at the
1142 smallest output pts */
1145 for(i=0;i<nb_ostreams;i++) {
1148 os = output_files[ost->file_index];
1149 ist = ist_table[ost->source_index];
1150 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1151 if (!file_table[ist->file_index].eof_reached &&
1154 file_index = ist->file_index;
1157 /* if none, if is finished */
1158 if (file_index < 0) {
1162 /* finish if recording time exhausted */
1163 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1166 /* read a packet from it and output it in the fifo */
1167 is = input_files[file_index];
1168 if (av_read_packet(is, &pkt) < 0) {
1169 file_table[file_index].eof_reached = 1;
1173 stream_no_data = is;
1177 /* the following test is needed in case new streams appear
1178 dynamically in stream : we ignore them */
1179 if (pkt.stream_index >= file_table[file_index].nb_streams)
1180 goto discard_packet;
1181 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1182 ist = ist_table[ist_index];
1184 goto discard_packet;
1187 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1188 av_hex_dump(pkt.data, pkt.size);
1191 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1199 ipts = AV_NOPTS_VALUE;
1201 /* decode the packet if needed */
1202 data_buf = NULL; /* fail safe */
1204 if (ist->decoding_needed) {
1205 /* NOTE1: we only take into account the PTS if a new
1206 frame has begun (MPEG semantics) */
1207 /* NOTE2: even if the fraction is not initialized,
1208 av_frac_set can be used to set the integer part */
1209 if (ist->frame_decoded &&
1210 pkt.pts != AV_NOPTS_VALUE &&
1213 ist->frame_decoded = 0;
1217 switch(ist->st->codec.codec_type) {
1218 case CODEC_TYPE_AUDIO:
1219 /* XXX: could avoid copy if PCM 16 bits with same
1220 endianness as CPU */
1221 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1225 /* Some bug in mpeg audio decoder gives */
1226 /* data_size < 0, it seems they are overflows */
1227 if (data_size <= 0) {
1228 /* no audio frame */
1233 data_buf = (UINT8 *)samples;
1235 case CODEC_TYPE_VIDEO:
1236 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1239 size = (ist->st->codec.width * ist->st->codec.height);
1240 avpicture_fill(&picture, ptr,
1241 ist->st->codec.pix_fmt,
1242 ist->st->codec.width,
1243 ist->st->codec.height);
1246 AVVideoFrame big_picture;
1248 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1249 ret = avcodec_decode_video(&ist->st->codec,
1250 &big_picture, &got_picture, ptr, len);
1251 picture= *(AVPicture*)&big_picture;
1252 ist->st->quality= big_picture.quality;
1255 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1256 ist->file_index, ist->index);
1257 av_free_packet(&pkt);
1261 /* no picture yet */
1281 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1282 pre_process_video_frame(ist, &picture, &buffer_to_free);
1285 ist->frame_decoded = 1;
1288 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1289 is the one of the next displayed one */
1290 /* XXX: add mpeg4 too ? */
1291 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1292 if (ist->st->codec.pict_type != B_TYPE) {
1294 tmp = ist->last_ip_pts;
1295 ist->last_ip_pts = ist->frac_pts.val;
1296 ist->frac_pts.val = tmp;
1300 /* transcode raw format, encode packets and output them */
1302 for(i=0;i<nb_ostreams;i++) {
1306 if (ost->source_index == ist_index) {
1307 os = output_files[ost->file_index];
1309 if (ipts != AV_NOPTS_VALUE) {
1311 printf("%d: got pts=%f %f\n",
1312 i, pkt.pts / 90000.0,
1313 (ipts - ost->st->pts.val) / 90000.0);
1315 /* set the input output pts pairs */
1316 ost->sync_ipts = (double)ipts * is->pts_num /
1318 /* XXX: take into account the various fifos,
1319 in particular for audio */
1320 ost->sync_opts = ost->st->pts.val;
1321 //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
1323 //printf("pts.val=%lld\n", ost->st->pts.val);
1326 if (ost->encoding_needed) {
1327 switch(ost->st->codec.codec_type) {
1328 case CODEC_TYPE_AUDIO:
1329 do_audio_out(os, ost, ist, data_buf, data_size);
1331 case CODEC_TYPE_VIDEO:
1332 /* find an audio stream for synchro */
1335 AVOutputStream *audio_sync, *ost1;
1337 for(i=0;i<nb_ostreams;i++) {
1338 ost1 = ost_table[i];
1339 if (ost1->file_index == ost->file_index &&
1340 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1346 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1348 do_video_stats(os, ost, frame_size);
1355 /* no reencoding needed : output the packet directly */
1356 /* force the input stream PTS */
1357 av_write_frame(os, ost->index, data_buf, data_size);
1358 ost->st->codec.frame_number++;
1359 ost->frame_number++;
1363 av_free(buffer_to_free);
1364 ipts = AV_NOPTS_VALUE;
1367 av_free_packet(&pkt);
1369 /* dump report by using the output first video and audio streams */
1370 print_report(output_files, ost_table, nb_ostreams, 0);
1374 /* dump report by using the first video and audio streams */
1375 print_report(output_files, ost_table, nb_ostreams, 1);
1377 /* close each encoder */
1378 for(i=0;i<nb_ostreams;i++) {
1380 if (ost->encoding_needed) {
1381 av_freep(&ost->st->codec.stats_in);
1382 avcodec_close(&ost->st->codec);
1386 /* close each decoder */
1387 for(i=0;i<nb_istreams;i++) {
1389 if (ist->decoding_needed) {
1390 avcodec_close(&ist->st->codec);
1395 /* write the trailer if needed and close file */
1396 for(i=0;i<nb_output_files;i++) {
1397 os = output_files[i];
1398 av_write_trailer(os);
1404 av_free(file_table);
1407 for(i=0;i<nb_istreams;i++) {
1414 for(i=0;i<nb_ostreams;i++) {
1418 fclose(ost->logfile);
1419 ost->logfile = NULL;
1421 fifo_free(&ost->fifo); /* works even if fifo is not
1422 initialized but set to zero */
1423 av_free(ost->pict_tmp.data[0]);
1424 if (ost->video_resample)
1425 img_resample_close(ost->img_resample_ctx);
1426 if (ost->audio_resample)
1427 audio_resample_close(ost->resample);
1440 int file_read(const char *filename)
1443 unsigned char buffer[1024];
1446 if (url_open(&h, filename, O_RDONLY) < 0) {
1447 printf("could not open '%s'\n", filename);
1451 len = url_read(h, buffer, sizeof(buffer));
1454 for(i=0;i<len;i++) putchar(buffer[i]);
1461 void show_licence(void)
1464 "ffmpeg version " FFMPEG_VERSION "\n"
1465 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1466 "This library is free software; you can redistribute it and/or\n"
1467 "modify it under the terms of the GNU Lesser General Public\n"
1468 "License as published by the Free Software Foundation; either\n"
1469 "version 2 of the License, or (at your option) any later version.\n"
1471 "This library is distributed in the hope that it will be useful,\n"
1472 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1473 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1474 "Lesser General Public License for more details.\n"
1476 "You should have received a copy of the GNU Lesser General Public\n"
1477 "License along with this library; if not, write to the Free Software\n"
1478 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1483 void opt_format(const char *arg)
1485 file_iformat = av_find_input_format(arg);
1486 file_oformat = guess_format(arg, NULL, NULL);
1487 if (!file_iformat && !file_oformat) {
1488 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1493 void opt_video_bitrate(const char *arg)
1495 video_bit_rate = atoi(arg) * 1000;
1498 void opt_video_bitrate_tolerance(const char *arg)
1500 video_bit_rate_tolerance = atoi(arg) * 1000;
1503 void opt_video_bitrate_max(const char *arg)
1505 video_rc_max_rate = atoi(arg) * 1000;
1508 void opt_video_bitrate_min(const char *arg)
1510 video_rc_min_rate = atoi(arg) * 1000;
1513 void opt_video_buffer_size(const char *arg)
1515 video_rc_buffer_size = atoi(arg) * 1000;
1518 void opt_video_rc_eq(char *arg)
1523 void opt_video_rc_override_string(char *arg)
1525 video_rc_override_string = arg;
1529 void opt_workaround_bugs(const char *arg)
1531 workaround_bugs = atoi(arg);
1534 void opt_dct_algo(const char *arg)
1536 dct_algo = atoi(arg);
1539 void opt_idct_algo(const char *arg)
1541 idct_algo = atoi(arg);
1545 void opt_error_resilience(const char *arg)
1547 error_resilience = atoi(arg);
1550 void opt_error_concealment(const char *arg)
1552 error_concealment = atoi(arg);
1556 void opt_frame_rate(const char *arg)
1558 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1562 void opt_frame_crop_top(const char *arg)
1564 frame_topBand = atoi(arg);
1565 if (frame_topBand < 0) {
1566 fprintf(stderr, "Incorrect top crop size\n");
1569 if ((frame_topBand % 2) != 0) {
1570 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1573 if ((frame_topBand) >= frame_height){
1574 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1577 frame_height -= frame_topBand;
1580 void opt_frame_crop_bottom(const char *arg)
1582 frame_bottomBand = atoi(arg);
1583 if (frame_bottomBand < 0) {
1584 fprintf(stderr, "Incorrect bottom crop size\n");
1587 if ((frame_bottomBand % 2) != 0) {
1588 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1591 if ((frame_bottomBand) >= frame_height){
1592 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1595 frame_height -= frame_bottomBand;
1598 void opt_frame_crop_left(const char *arg)
1600 frame_leftBand = atoi(arg);
1601 if (frame_leftBand < 0) {
1602 fprintf(stderr, "Incorrect left crop size\n");
1605 if ((frame_leftBand % 2) != 0) {
1606 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1609 if ((frame_leftBand) >= frame_width){
1610 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1613 frame_width -= frame_leftBand;
1616 void opt_frame_crop_right(const char *arg)
1618 frame_rightBand = atoi(arg);
1619 if (frame_rightBand < 0) {
1620 fprintf(stderr, "Incorrect right crop size\n");
1623 if ((frame_rightBand % 2) != 0) {
1624 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1627 if ((frame_rightBand) >= frame_width){
1628 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1631 frame_width -= frame_rightBand;
1634 void opt_frame_size(const char *arg)
1636 parse_image_size(&frame_width, &frame_height, arg);
1637 if (frame_width <= 0 || frame_height <= 0) {
1638 fprintf(stderr, "Incorrect frame size\n");
1641 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1642 fprintf(stderr, "Frame size must be a multiple of 2\n");
1647 void opt_gop_size(const char *arg)
1649 gop_size = atoi(arg);
1652 void opt_b_frames(const char *arg)
1654 b_frames = atoi(arg);
1655 if (b_frames > FF_MAX_B_FRAMES) {
1656 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1658 } else if (b_frames < 1) {
1659 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1664 void opt_qscale(const char *arg)
1666 video_qscale = atoi(arg);
1667 if (video_qscale < 0 ||
1668 video_qscale > 31) {
1669 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1674 void opt_qmin(const char *arg)
1676 video_qmin = atoi(arg);
1677 if (video_qmin < 0 ||
1679 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1684 void opt_qmax(const char *arg)
1686 video_qmax = atoi(arg);
1687 if (video_qmax < 0 ||
1689 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1694 void opt_qdiff(const char *arg)
1696 video_qdiff = atoi(arg);
1697 if (video_qdiff < 0 ||
1699 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1704 void opt_qblur(const char *arg)
1706 video_qblur = atof(arg);
1709 void opt_qcomp(const char *arg)
1711 video_qcomp = atof(arg);
1714 void opt_rc_initial_cplx(const char *arg)
1716 video_rc_initial_cplx = atof(arg);
1718 void opt_b_qfactor(const char *arg)
1720 video_b_qfactor = atof(arg);
1722 void opt_i_qfactor(const char *arg)
1724 video_i_qfactor = atof(arg);
1726 void opt_b_qoffset(const char *arg)
1728 video_b_qoffset = atof(arg);
1730 void opt_i_qoffset(const char *arg)
1732 video_i_qoffset = atof(arg);
1735 void opt_packet_size(const char *arg)
1737 packet_size= atoi(arg);
1740 void opt_audio_bitrate(const char *arg)
1742 audio_bit_rate = atoi(arg) * 1000;
1745 void opt_audio_rate(const char *arg)
1747 audio_sample_rate = atoi(arg);
1750 void opt_audio_channels(const char *arg)
1752 audio_channels = atoi(arg);
1755 void opt_video_device(const char *arg)
1757 v4l_device = strdup(arg);
1760 void opt_audio_device(const char *arg)
1762 audio_device = strdup(arg);
1765 void opt_audio_codec(const char *arg)
1769 if (!strcmp(arg, "copy")) {
1770 audio_stream_copy = 1;
1774 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1779 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1782 audio_codec_id = p->id;
1787 void add_frame_hooker(const char *arg)
1792 char *args = strdup(arg);
1794 argv[0] = strtok(args, " ");
1795 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1798 i = frame_hook_add(argc, argv);
1801 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1806 const char *motion_str[] = {
1816 void opt_motion_estimation(const char *arg)
1822 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1825 if (!strcmp(*p, arg))
1829 me_method = (p - motion_str) + 1;
1832 void opt_video_codec(const char *arg)
1836 if (!strcmp(arg, "copy")) {
1837 video_stream_copy = 1;
1841 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1846 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1849 video_codec_id = p->id;
1854 void opt_map(const char *arg)
1860 m = &stream_maps[nb_stream_maps++];
1862 m->file_index = strtol(arg, (char **)&p, 0);
1866 m->stream_index = strtol(p, (char **)&p, 0);
1869 void opt_recording_time(const char *arg)
1871 recording_time = parse_date(arg, 1);
1874 void print_error(const char *filename, int err)
1877 case AVERROR_NUMEXPECTED:
1878 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1879 "Use '%%d' to specify the image number:\n"
1880 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1881 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1884 case AVERROR_INVALIDDATA:
1885 fprintf(stderr, "%s: Error while parsing header\n", filename);
1888 fprintf(stderr, "%s: Unknown format\n", filename);
1891 fprintf(stderr, "%s: Error while opening file\n", filename);
1896 void opt_input_file(const char *filename)
1898 AVFormatContext *ic;
1899 AVFormatParameters params, *ap = ¶ms;
1900 int err, i, ret, rfps;
1902 if (!strcmp(filename, "-"))
1905 /* get default parameters from command line */
1906 memset(ap, 0, sizeof(*ap));
1907 ap->sample_rate = audio_sample_rate;
1908 ap->channels = audio_channels;
1909 ap->frame_rate = frame_rate;
1910 ap->width = frame_width;
1911 ap->height = frame_height;
1913 /* open the input file with generic libav function */
1914 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1916 print_error(filename, err);
1920 /* If not enough info to get the stream parameters, we decode the
1921 first frames to get it. (used in mpeg case for example) */
1922 ret = av_find_stream_info(ic);
1924 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1928 /* update the current parameters so that they match the one of the input stream */
1929 for(i=0;i<ic->nb_streams;i++) {
1930 AVCodecContext *enc = &ic->streams[i]->codec;
1931 switch(enc->codec_type) {
1932 case CODEC_TYPE_AUDIO:
1933 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1934 audio_channels = enc->channels;
1935 audio_sample_rate = enc->sample_rate;
1937 case CODEC_TYPE_VIDEO:
1938 frame_height = enc->height;
1939 frame_width = enc->width;
1940 rfps = ic->streams[i]->r_frame_rate;
1941 enc->workaround_bugs = workaround_bugs;
1942 enc->error_resilience = error_resilience;
1943 enc->error_concealment = error_concealment;
1944 enc->idct_algo= idct_algo;
1945 /* if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1946 enc->flags|= CODEC_FLAG_TRUNCATED; */
1947 if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
1948 enc->flags|= CODEC_FLAG_TRUNCATED;
1950 if (enc->frame_rate != rfps) {
1951 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1952 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1953 (float)rfps / FRAME_RATE_BASE);
1955 /* update the current frame rate to match the stream frame rate */
1963 input_files[nb_input_files] = ic;
1964 /* dump the file content */
1965 dump_format(ic, nb_input_files, filename, 0);
1967 file_iformat = NULL;
1968 file_oformat = NULL;
1971 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1973 int has_video, has_audio, i, j;
1974 AVFormatContext *ic;
1978 for(j=0;j<nb_input_files;j++) {
1979 ic = input_files[j];
1980 for(i=0;i<ic->nb_streams;i++) {
1981 AVCodecContext *enc = &ic->streams[i]->codec;
1982 switch(enc->codec_type) {
1983 case CODEC_TYPE_AUDIO:
1986 case CODEC_TYPE_VIDEO:
1994 *has_video_ptr = has_video;
1995 *has_audio_ptr = has_audio;
1998 void opt_output_file(const char *filename)
2001 AVFormatContext *oc;
2002 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2005 if (!strcmp(filename, "-"))
2008 oc = av_mallocz(sizeof(AVFormatContext));
2010 if (!file_oformat) {
2011 file_oformat = guess_format(NULL, filename, NULL);
2012 if (!file_oformat) {
2013 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2019 oc->oformat = file_oformat;
2021 if (!strcmp(file_oformat->name, "ffm") &&
2022 strstart(filename, "http:", NULL)) {
2023 /* special case for files sent to ffserver: we get the stream
2024 parameters from ffserver */
2025 if (read_ffserver_streams(oc, filename) < 0) {
2026 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2030 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2031 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2033 /* disable if no corresponding type found and at least one
2035 if (nb_input_files > 0) {
2036 check_audio_video_inputs(&input_has_video, &input_has_audio);
2037 if (!input_has_video)
2039 if (!input_has_audio)
2043 /* manual disable */
2044 if (audio_disable) {
2047 if (video_disable) {
2053 AVCodecContext *video_enc;
2055 st = av_mallocz(sizeof(AVStream));
2057 fprintf(stderr, "Could not alloc stream\n");
2060 avcodec_get_context_defaults(&st->codec);
2062 video_enc = &st->codec;
2063 if (video_stream_copy) {
2064 st->stream_copy = 1;
2065 video_enc->codec_type = CODEC_TYPE_VIDEO;
2070 codec_id = file_oformat->video_codec;
2071 if (video_codec_id != CODEC_ID_NONE)
2072 codec_id = video_codec_id;
2074 video_enc->codec_id = codec_id;
2076 video_enc->bit_rate = video_bit_rate;
2077 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2078 video_enc->frame_rate = frame_rate;
2080 video_enc->width = frame_width;
2081 video_enc->height = frame_height;
2084 video_enc->gop_size = gop_size;
2086 video_enc->gop_size = 0;
2087 if (video_qscale || same_quality) {
2088 video_enc->flags |= CODEC_FLAG_QSCALE;
2089 st->quality = video_qscale;
2093 video_enc->flags |= CODEC_FLAG_HQ;
2097 video_enc->flags |= CODEC_FLAG_HQ;
2098 video_enc->flags |= CODEC_FLAG_4MV;
2102 video_enc->flags |= CODEC_FLAG_PART;
2106 if (codec_id != CODEC_ID_MPEG4) {
2107 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2110 video_enc->max_b_frames = b_frames;
2111 video_enc->b_frame_strategy = 0;
2112 video_enc->b_quant_factor = 2.0;
2115 video_enc->qmin = video_qmin;
2116 video_enc->qmax = video_qmax;
2117 video_enc->max_qdiff = video_qdiff;
2118 video_enc->qblur = video_qblur;
2119 video_enc->qcompress = video_qcomp;
2120 video_enc->rc_eq = video_rc_eq;
2122 p= video_rc_override_string;
2125 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2127 fprintf(stderr, "error parsing rc_override\n");
2130 video_enc->rc_override=
2131 realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2132 video_enc->rc_override[i].start_frame= start;
2133 video_enc->rc_override[i].end_frame = end;
2135 video_enc->rc_override[i].qscale= q;
2136 video_enc->rc_override[i].quality_factor= 1.0;
2139 video_enc->rc_override[i].qscale= 0;
2140 video_enc->rc_override[i].quality_factor= -q/100.0;
2145 video_enc->rc_override_count=i;
2147 video_enc->rc_max_rate = video_rc_max_rate;
2148 video_enc->rc_min_rate = video_rc_min_rate;
2149 video_enc->rc_buffer_size = video_rc_buffer_size;
2150 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2151 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2152 video_enc->i_quant_factor = video_i_qfactor;
2153 video_enc->b_quant_factor = video_b_qfactor;
2154 video_enc->i_quant_offset = video_i_qoffset;
2155 video_enc->b_quant_offset = video_b_qoffset;
2156 video_enc->dct_algo = dct_algo;
2157 video_enc->idct_algo = idct_algo;
2159 video_enc->rtp_mode= 1;
2160 video_enc->rtp_payload_size= packet_size;
2164 video_enc->get_psnr = 1;
2166 video_enc->get_psnr = 0;
2168 video_enc->me_method = me_method;
2173 video_enc->flags |= CODEC_FLAG_PASS1;
2175 video_enc->flags |= CODEC_FLAG_PASS2;
2179 /* XXX: need to find a way to set codec parameters */
2180 if (oc->oformat->flags & AVFMT_RGB24) {
2181 video_enc->pix_fmt = PIX_FMT_RGB24;
2184 oc->streams[nb_streams] = st;
2189 AVCodecContext *audio_enc;
2191 st = av_mallocz(sizeof(AVStream));
2193 fprintf(stderr, "Could not alloc stream\n");
2196 avcodec_get_context_defaults(&st->codec);
2198 audio_enc = &st->codec;
2199 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2200 if (audio_stream_copy) {
2201 st->stream_copy = 1;
2203 codec_id = file_oformat->audio_codec;
2204 if (audio_codec_id != CODEC_ID_NONE)
2205 codec_id = audio_codec_id;
2206 audio_enc->codec_id = codec_id;
2208 audio_enc->bit_rate = audio_bit_rate;
2209 audio_enc->sample_rate = audio_sample_rate;
2210 /* For audio codecs other than AC3 we limit */
2211 /* the number of coded channels to stereo */
2212 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2213 audio_enc->channels = 2;
2215 audio_enc->channels = audio_channels;
2217 oc->streams[nb_streams] = st;
2221 oc->nb_streams = nb_streams;
2224 fprintf(stderr, "No audio or video streams available\n");
2229 pstrcpy(oc->title, sizeof(oc->title), str_title);
2231 pstrcpy(oc->author, sizeof(oc->author), str_author);
2233 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2235 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2238 output_files[nb_output_files++] = oc;
2240 strcpy(oc->filename, filename);
2242 /* check filename in case of an image number is expected */
2243 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2244 if (filename_number_test(oc->filename) < 0) {
2245 print_error(oc->filename, AVERROR_NUMEXPECTED);
2250 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2251 /* test if it already exists to avoid loosing precious files */
2252 if (!file_overwrite &&
2253 (strchr(filename, ':') == NULL ||
2254 strstart(filename, "file:", NULL))) {
2255 if (url_exist(filename)) {
2258 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2261 if (toupper(c) != 'Y') {
2262 fprintf(stderr, "Not overwriting - exiting\n");
2269 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2270 fprintf(stderr, "Could not open '%s'\n", filename);
2275 /* reset some options */
2276 file_oformat = NULL;
2277 file_iformat = NULL;
2280 audio_codec_id = CODEC_ID_NONE;
2281 video_codec_id = CODEC_ID_NONE;
2282 audio_stream_copy = 0;
2283 video_stream_copy = 0;
2286 /* prepare dummy protocols for grab */
2287 void prepare_grab(void)
2289 int has_video, has_audio, i, j;
2290 AVFormatContext *oc;
2291 AVFormatContext *ic;
2292 AVFormatParameters ap1, *ap = &ap1;
2294 /* see if audio/video inputs are needed */
2297 memset(ap, 0, sizeof(*ap));
2298 for(j=0;j<nb_output_files;j++) {
2299 oc = output_files[j];
2300 for(i=0;i<oc->nb_streams;i++) {
2301 AVCodecContext *enc = &oc->streams[i]->codec;
2302 switch(enc->codec_type) {
2303 case CODEC_TYPE_AUDIO:
2304 if (enc->sample_rate > ap->sample_rate)
2305 ap->sample_rate = enc->sample_rate;
2306 if (enc->channels > ap->channels)
2307 ap->channels = enc->channels;
2310 case CODEC_TYPE_VIDEO:
2311 if (enc->width > ap->width)
2312 ap->width = enc->width;
2313 if (enc->height > ap->height)
2314 ap->height = enc->height;
2315 if (enc->frame_rate > ap->frame_rate)
2316 ap->frame_rate = enc->frame_rate;
2325 if (has_video == 0 && has_audio == 0) {
2326 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2331 AVInputFormat *fmt1;
2332 fmt1 = av_find_input_format("video_grab_device");
2333 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2334 fprintf(stderr, "Could not find video grab device\n");
2337 /* by now video grab has one stream */
2338 ic->streams[0]->r_frame_rate = ap->frame_rate;
2339 input_files[nb_input_files] = ic;
2340 dump_format(ic, nb_input_files, v4l_device, 0);
2344 AVInputFormat *fmt1;
2345 fmt1 = av_find_input_format("audio_device");
2346 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2347 fprintf(stderr, "Could not find audio grab device\n");
2350 input_files[nb_input_files] = ic;
2351 dump_format(ic, nb_input_files, audio_device, 0);
2356 /* open the necessary output devices for playing */
2357 void prepare_play(void)
2359 file_iformat = NULL;
2360 file_oformat = guess_format("audio_device", NULL, NULL);
2361 if (!file_oformat) {
2362 fprintf(stderr, "Could not find audio device\n");
2366 opt_output_file(audio_device);
2369 /* same option as mencoder */
2370 void opt_pass(const char *pass_str)
2373 pass = atoi(pass_str);
2374 if (pass != 1 && pass != 2) {
2375 fprintf(stderr, "pass number can be only 1 or 2\n");
2381 #ifndef CONFIG_WIN32
2382 INT64 getutime(void)
2384 struct rusage rusage;
2386 getrusage(RUSAGE_SELF, &rusage);
2387 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2390 INT64 getutime(void)
2392 return av_gettime();
2396 extern int ffm_nopts;
2398 void opt_bitexact(void)
2400 avcodec_set_bit_exact();
2401 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2405 void show_formats(void)
2407 AVInputFormat *ifmt;
2408 AVOutputFormat *ofmt;
2413 printf("File formats:\n");
2414 printf(" Encoding:");
2415 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2416 printf(" %s", ofmt->name);
2419 printf(" Decoding:");
2420 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2421 printf(" %s", ifmt->name);
2425 printf("Codecs:\n");
2426 printf(" Encoders:");
2427 for(p = first_avcodec; p != NULL; p = p->next) {
2429 printf(" %s", p->name);
2433 printf(" Decoders:");
2434 for(p = first_avcodec; p != NULL; p = p->next) {
2436 printf(" %s", p->name);
2440 printf("Supported file protocols:");
2441 for(up = first_protocol; up != NULL; up = up->next)
2442 printf(" %s:", up->name);
2445 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2446 printf("Motion estimation methods:");
2450 if ((pp - motion_str + 1) == ME_ZERO)
2451 printf("(fastest)");
2452 else if ((pp - motion_str + 1) == ME_FULL)
2453 printf("(slowest)");
2454 else if ((pp - motion_str + 1) == ME_EPZS)
2455 printf("(default)");
2462 void show_help(void)
2465 const OptionDef *po;
2468 prog = do_play ? "ffplay" : "ffmpeg";
2470 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2474 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2475 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2477 printf("usage: ffplay [options] input_file...\n"
2478 "Simple audio player\n");
2482 "Main options are:\n");
2485 printf("\nAdvanced options are:\n");
2486 for(po = options; po->name != NULL; po++) {
2488 expert = (po->flags & OPT_EXPERT) != 0;
2490 strcpy(buf, po->name);
2491 if (po->flags & HAS_ARG) {
2493 strcat(buf, po->argname);
2495 printf("-%-17s %s\n", buf, po->help);
2503 const OptionDef options[] = {
2504 { "L", 0, {(void*)show_licence}, "show license" },
2505 { "h", 0, {(void*)show_help}, "show help" },
2506 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2507 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2508 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2509 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2510 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2511 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2512 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2513 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2514 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2515 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2516 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2517 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2519 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2520 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2521 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2522 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2523 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2524 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2525 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2526 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2527 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2528 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2529 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2530 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2531 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2532 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2533 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2534 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2535 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2536 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2537 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2538 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2539 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2540 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2541 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2542 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2543 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2544 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2545 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2546 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2547 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2548 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2550 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2551 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2552 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2553 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
2554 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2555 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2556 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2557 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2558 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2559 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2560 { "sameq", OPT_BOOL, {(void*)&same_quality},
2561 "use same video quality as source (implies VBR)" },
2563 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2564 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2565 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2566 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2567 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2568 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2569 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2570 "deinterlace pictures" },
2571 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2572 "add timings for benchmarking" },
2573 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2574 "dump each input packet" },
2575 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2576 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2577 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2578 { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
2582 int main(int argc, char **argv)
2585 const char *opt, *arg;
2586 const OptionDef *po;
2591 /* detect if invoked as player */
2592 i = strlen(argv[0]);
2593 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2601 while (optindex < argc) {
2602 opt = argv[optindex++];
2604 if (opt[0] == '-' && opt[1] != '\0') {
2606 while (po->name != NULL) {
2607 if (!strcmp(opt + 1, po->name))
2612 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2616 if (po->flags & HAS_ARG) {
2617 arg = argv[optindex++];
2619 fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2623 if (po->flags & OPT_STRING) {
2626 *po->u.str_arg = str;
2627 } else if (po->flags & OPT_BOOL) {
2630 po->u.func_arg(arg);
2634 opt_output_file(opt);
2636 opt_input_file(opt);
2643 /* file converter / grab */
2644 if (nb_output_files <= 0) {
2645 fprintf(stderr, "Must supply at least one output file\n");
2649 if (nb_input_files == 0) {
2654 if (nb_input_files <= 0) {
2655 fprintf(stderr, "Must supply at least one input file\n");
2662 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2663 stream_maps, nb_stream_maps);
2664 ti = getutime() - ti;
2666 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2670 for(i=0;i<nb_output_files;i++) {
2671 /* maybe av_close_output_file ??? */
2672 AVFormatContext *s = output_files[i];
2674 if (!(s->oformat->flags & AVFMT_NOFILE))
2676 for(j=0;j<s->nb_streams;j++)
2677 av_free(s->streams[j]);
2680 for(i=0;i<nb_input_files;i++)
2681 av_close_input_file(input_files[i]);