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
26 #include <sys/ioctl.h>
29 #include <sys/resource.h>
39 #define MAXINT64 INT64_C(0x7fffffffffffffff)
44 #define HAS_ARG 0x0001
45 #define OPT_BOOL 0x0002
46 #define OPT_EXPERT 0x0004
47 #define OPT_STRING 0x0008
57 /* select an input stream for an output stream */
58 typedef struct AVStreamMap {
63 extern const OptionDef options[];
69 static AVFormatContext *input_files[MAX_FILES];
70 static int nb_input_files = 0;
72 static AVFormatContext *output_files[MAX_FILES];
73 static int nb_output_files = 0;
75 static AVStreamMap stream_maps[MAX_FILES];
76 static int nb_stream_maps;
78 static AVInputFormat *file_iformat;
79 static AVOutputFormat *file_oformat;
80 static int frame_width = 160;
81 static int frame_height = 128;
82 static int frame_topBand = 0;
83 static int frame_bottomBand = 0;
84 static int frame_leftBand = 0;
85 static int frame_rightBand = 0;
86 static int frame_rate = 25 * FRAME_RATE_BASE;
87 static int video_bit_rate = 200*1000;
88 static int video_bit_rate_tolerance = 4000*1000;
89 static int video_qscale = 0;
90 static int video_qmin = 2;
91 static int video_qmax = 31;
92 static int video_qdiff = 3;
93 static float video_qblur = 0.5;
94 static float video_qcomp = 0.5;
95 static float video_rc_qsquish=1.0;
96 static float video_rc_qmod_amp=0;
97 static int video_rc_qmod_freq=0;
98 static char *video_rc_override_string=NULL;
99 static char *video_rc_eq="tex^qComp";
100 static int video_rc_buffer_size=0;
101 static float video_rc_buffer_aggressivity=1.0;
102 static int video_rc_max_rate=0;
103 static int video_rc_min_rate=0;
104 static float video_rc_initial_cplx=0;
105 static float video_b_qfactor = 1.25;
106 static float video_b_qoffset = 1.25;
107 static float video_i_qfactor = -0.8;
108 static float video_i_qoffset = 0.0;
109 static int me_method = 0;
110 static int video_disable = 0;
111 static int video_codec_id = CODEC_ID_NONE;
112 static int same_quality = 0;
113 static int b_frames = 0;
114 static int use_hq = 0;
115 static int use_4mv = 0;
116 static int do_deinterlace = 0;
117 static int workaround_bugs = 0;
118 static int error_resilience = 0;
119 static int dct_algo = 0;
120 static int idct_algo = 0;
121 static int use_part = 0;
122 static int packet_size = 0;
124 static int gop_size = 12;
125 static int intra_only = 0;
126 static int audio_sample_rate = 44100;
127 static int audio_bit_rate = 64000;
128 static int audio_disable = 0;
129 static int audio_channels = 1;
130 static int audio_codec_id = CODEC_ID_NONE;
132 static INT64 recording_time = 0;
133 static int file_overwrite = 0;
134 static char *str_title = NULL;
135 static char *str_author = NULL;
136 static char *str_copyright = NULL;
137 static char *str_comment = NULL;
138 static int do_benchmark = 0;
139 static int do_hex_dump = 0;
140 static int do_play = 0;
141 static int do_psnr = 0;
142 static int do_vstats = 0;
143 static int mpeg_vcd = 0;
144 static int do_pass = 0;
145 static char *pass_logfilename = NULL;
146 static int audio_stream_copy = 0;
147 static int video_stream_copy = 0;
149 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
151 #ifndef CONFIG_AUDIO_OSS
152 const char *audio_device = "none";
154 #ifndef CONFIG_VIDEO4LINUX
155 const char *v4l_device = "none";
158 typedef struct AVOutputStream {
159 int file_index; /* file index */
160 int index; /* stream index in the output file */
161 int source_index; /* AVInputStream index */
162 AVStream *st; /* stream in the output file */
163 int encoding_needed; /* true if encoding needed for this stream */
166 AVPicture pict_tmp; /* temporary image for resizing */
168 ImgReSampleContext *img_resample_ctx; /* for image resampling */
172 ReSampleContext *resample; /* for audio resampling */
173 FifoBuffer fifo; /* for compression: one audio fifo per codec */
177 typedef struct AVInputStream {
181 int discard; /* true if stream data should be discarded */
182 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
183 Ticker pts_ticker; /* Ticker for PTS calculation */
184 int ticker_inited; /* to signal if the ticker was initialized */
185 INT64 pts; /* current pts */
186 int pts_increment; /* expected pts increment for next packet */
187 int frame_number; /* current frame */
188 INT64 sample_index; /* current sample */
191 typedef struct AVInputFile {
192 int eof_reached; /* true if eof reached */
193 int ist_index; /* index of first stream in ist_table */
194 int buffer_size; /* current total buffer size */
195 int buffer_size_max; /* buffer size at which we consider we can stop
197 int nb_streams; /* nb streams we are aware of */
202 /* init terminal so that we can grab keys */
203 static struct termios oldtty;
205 static void term_exit(void)
207 tcsetattr (0, TCSANOW, &oldtty);
210 static void term_init(void)
217 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
218 |INLCR|IGNCR|ICRNL|IXON);
219 tty.c_oflag |= OPOST;
220 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
221 tty.c_cflag &= ~(CSIZE|PARENB);
226 tcsetattr (0, TCSANOW, &tty);
231 /* read a key without blocking */
232 static int read_key(void)
243 n = select(1, &rfds, NULL, NULL, &tv);
256 /* no interactive support */
257 static void term_exit(void)
261 static void term_init(void)
265 static int read_key(void)
272 int read_ffserver_streams(AVFormatContext *s, const char *filename)
277 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
280 /* copy stream format */
281 s->nb_streams = ic->nb_streams;
282 for(i=0;i<ic->nb_streams;i++) {
284 st = av_mallocz(sizeof(AVFormatContext));
285 memcpy(st, ic->streams[i], sizeof(AVStream));
289 av_close_input_file(ic);
293 #define MAX_AUDIO_PACKET_SIZE 16384
295 static void do_audio_out(AVFormatContext *s,
298 unsigned char *buf, int size)
301 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
302 UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
303 int size_out, frame_bytes, ret;
306 enc = &ost->st->codec;
308 if (ost->audio_resample) {
310 size_out = audio_resample(ost->resample,
311 (short *)buftmp, (short *)buf,
312 size / (ist->st->codec.channels * 2));
313 size_out = size_out * enc->channels * 2;
319 /* now encode as many frames as possible */
320 if (enc->frame_size > 1) {
321 /* output resampled raw samples */
322 fifo_write(&ost->fifo, buftmp, size_out,
325 frame_bytes = enc->frame_size * 2 * enc->channels;
327 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
328 &ost->fifo.rptr) == 0) {
329 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
331 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
334 /* output a pcm frame */
335 /* XXX: change encoding codec API to avoid this ? */
336 switch(enc->codec->id) {
337 case CODEC_ID_PCM_S16LE:
338 case CODEC_ID_PCM_S16BE:
339 case CODEC_ID_PCM_U16LE:
340 case CODEC_ID_PCM_U16BE:
343 size_out = size_out >> 1;
346 ret = avcodec_encode_audio(enc, audio_out, size_out,
348 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
352 /* write a picture to a raw mux */
353 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
354 int pix_fmt, int w, int h)
356 UINT8 *buf, *src, *dest;
359 /* XXX: not efficient, should add test if we can take
360 directly the AVPicture */
362 case PIX_FMT_YUV420P:
363 size = avpicture_get_size(pix_fmt, w, h);
364 buf = av_malloc(size);
373 src = picture->data[i];
375 memcpy(dest, src, w);
377 src += picture->linesize[i];
381 case PIX_FMT_YUV422P:
383 buf = av_malloc(size);
391 src = picture->data[i];
393 memcpy(dest, src, w);
395 src += picture->linesize[i];
399 case PIX_FMT_YUV444P:
401 buf = av_malloc(size);
406 src = picture->data[i];
408 memcpy(dest, src, w);
410 src += picture->linesize[i];
416 buf = av_malloc(size);
420 src = picture->data[0];
422 memcpy(dest, src, w * 2);
424 src += picture->linesize[0];
430 buf = av_malloc(size);
434 src = picture->data[0];
436 memcpy(dest, src, w * 3);
438 src += picture->linesize[0];
444 s->oformat->write_packet(s, index, buf, size, 0);
449 static void do_video_out(AVFormatContext *s,
455 int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
456 AVPicture *picture, *picture2, *pict;
457 AVPicture picture_tmp1, picture_tmp2;
458 static UINT8 *video_buffer;
459 UINT8 *buf = NULL, *buf1 = NULL;
460 AVCodecContext *enc, *dec;
462 #define VIDEO_BUFFER_SIZE (1024*1024)
464 enc = &ost->st->codec;
465 dec = &ist->st->codec;
467 frame_number = ist->frame_number;
468 dec_frame_rate = ist->st->r_frame_rate;
469 // fprintf(stderr, "\n%d", dec_frame_rate);
470 /* first drop frame if needed */
471 n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
472 n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
478 video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
479 if(!video_buffer) return;
481 /* deinterlace : must be done before any resize */
482 if (do_deinterlace) {
485 /* create temporary picture */
486 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
487 buf1 = av_malloc(size);
491 picture2 = &picture_tmp2;
492 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
494 if (avpicture_deinterlace(picture2, picture1,
495 dec->pix_fmt, dec->width, dec->height) < 0) {
496 /* if error, do not deinterlace */
505 /* convert pixel format if needed */
506 if (enc->pix_fmt != dec->pix_fmt) {
509 /* create temporary picture */
510 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
511 buf = av_malloc(size);
514 pict = &picture_tmp1;
515 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
517 if (img_convert(pict, enc->pix_fmt,
518 picture2, dec->pix_fmt,
519 dec->width, dec->height) < 0) {
520 fprintf(stderr, "pixel format conversion not handled\n");
527 /* XXX: resampling could be done before raw format convertion in
528 some cases to go faster */
529 /* XXX: only works for YUV420P */
530 if (ost->video_resample) {
531 picture = &ost->pict_tmp;
532 img_resample(ost->img_resample_ctx, picture, pict);
537 /* duplicates frame if needed */
538 /* XXX: pb because no interleaving */
540 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
541 /* handles sameq here. This is not correct because it may
542 not be a global option */
544 enc->quality = dec->quality;
547 ret = avcodec_encode_video(enc,
548 video_buffer, VIDEO_BUFFER_SIZE,
550 //enc->frame_number = enc->real_pict_num;
551 s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
553 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
554 // enc->frame_number-1, enc->real_pict_num, ret,
556 /* if two pass, output log */
557 if (ost->logfile && enc->stats_out) {
558 fprintf(ost->logfile, "%s", enc->stats_out);
561 write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
569 static void do_video_stats(AVOutputStream *ost,
573 static FILE *fvstats=NULL;
574 static INT64 total_size = 0;
581 double ti1, bitrate, avg_bitrate;
585 today = localtime(&today2);
586 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
589 fvstats = fopen(filename,"w");
597 enc = &ost->st->codec;
598 total_size += frame_size;
599 if (enc->codec_type == CODEC_TYPE_VIDEO) {
600 frame_number = ist->frame_number;
601 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
603 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
605 fprintf(fvstats,"f_size= %6d ", frame_size);
606 /* compute min pts value */
607 if (!ist->discard && ist->pts < ti) {
610 ti1 = (double)ti / 1000000.0;
614 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
615 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
616 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
617 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
618 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
626 * The following code is the main loop of the file converter
628 static int av_encode(AVFormatContext **output_files,
630 AVFormatContext **input_files,
632 AVStreamMap *stream_maps, int nb_stream_maps)
634 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
635 AVFormatContext *is, *os;
636 AVCodecContext *codec, *icodec;
637 AVOutputStream *ost, **ost_table = NULL;
638 AVInputStream *ist, **ist_table = NULL;
639 INT64 min_pts, start_time;
640 AVInputFile *file_table;
641 AVFormatContext *stream_no_data;
644 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
648 /* input stream init */
650 for(i=0;i<nb_input_files;i++) {
652 file_table[i].ist_index = j;
653 file_table[i].nb_streams = is->nb_streams;
658 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
662 for(i=0;i<nb_istreams;i++) {
663 ist = av_mallocz(sizeof(AVInputStream));
669 for(i=0;i<nb_input_files;i++) {
671 for(k=0;k<is->nb_streams;k++) {
672 ist = ist_table[j++];
673 ist->st = is->streams[k];
676 ist->discard = 1; /* the stream is discarded by default
681 /* output stream init */
683 for(i=0;i<nb_output_files;i++) {
684 os = output_files[i];
685 nb_ostreams += os->nb_streams;
687 os->flags |= AVF_FLAG_VCD;
689 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
690 fprintf(stderr, "Number of stream maps must match number of output streams\n");
694 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
697 for(i=0;i<nb_ostreams;i++) {
698 ost = av_mallocz(sizeof(AVOutputStream));
705 for(k=0;k<nb_output_files;k++) {
706 os = output_files[k];
707 for(i=0;i<os->nb_streams;i++) {
709 ost = ost_table[n++];
712 ost->st = os->streams[i];
713 if (nb_stream_maps > 0) {
714 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
715 stream_maps[n-1].stream_index;
717 /* get corresponding input stream index : we select the first one with the right type */
719 for(j=0;j<nb_istreams;j++) {
722 ist->st->codec.codec_type == ost->st->codec.codec_type) {
723 ost->source_index = j;
729 /* try again and reuse existing stream */
730 for(j=0;j<nb_istreams;j++) {
732 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
733 ost->source_index = j;
738 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
739 ost->file_index, ost->index);
744 ist = ist_table[ost->source_index];
749 /* for each output stream, we compute the right encoding parameters */
750 for(i=0;i<nb_ostreams;i++) {
752 ist = ist_table[ost->source_index];
754 codec = &ost->st->codec;
755 icodec = &ist->st->codec;
757 if (ost->st->stream_copy) {
758 /* if stream_copy is selected, no need to decode or encode */
759 codec->codec_id = icodec->codec_id;
760 codec->codec_type = icodec->codec_type;
761 codec->codec_tag = icodec->codec_tag;
762 codec->bit_rate = icodec->bit_rate;
763 switch(codec->codec_type) {
764 case CODEC_TYPE_AUDIO:
765 codec->sample_rate = icodec->sample_rate;
766 codec->channels = icodec->channels;
768 case CODEC_TYPE_VIDEO:
769 codec->frame_rate = icodec->frame_rate;
770 codec->width = icodec->width;
771 codec->height = icodec->height;
777 switch(codec->codec_type) {
778 case CODEC_TYPE_AUDIO:
779 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
782 if (codec->channels == icodec->channels &&
783 codec->sample_rate == icodec->sample_rate) {
784 ost->audio_resample = 0;
786 if (codec->channels != icodec->channels &&
787 icodec->codec_id == CODEC_ID_AC3) {
788 /* Special case for 5:1 AC3 input */
789 /* and mono or stereo output */
790 /* Request specific number of channels */
791 icodec->channels = codec->channels;
792 if (codec->sample_rate == icodec->sample_rate)
793 ost->audio_resample = 0;
795 ost->audio_resample = 1;
796 ost->resample = audio_resample_init(codec->channels, icodec->channels,
798 icodec->sample_rate);
800 /* Request specific number of channels */
801 icodec->channels = codec->channels;
803 ost->audio_resample = 1;
804 ost->resample = audio_resample_init(codec->channels, icodec->channels,
806 icodec->sample_rate);
809 ist->decoding_needed = 1;
810 ost->encoding_needed = 1;
812 case CODEC_TYPE_VIDEO:
813 if (codec->width == icodec->width &&
814 codec->height == icodec->height) {
815 ost->video_resample = 0;
818 ost->video_resample = 1;
819 buf = av_malloc((codec->width * codec->height * 3) / 2);
822 ost->pict_tmp.data[0] = buf;
823 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
824 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
825 ost->pict_tmp.linesize[0] = codec->width;
826 ost->pict_tmp.linesize[1] = codec->width / 2;
827 ost->pict_tmp.linesize[2] = codec->width / 2;
829 ost->img_resample_ctx = img_resample_full_init(
830 ost->st->codec.width, ost->st->codec.height,
831 ist->st->codec.width, ist->st->codec.height,
832 frame_topBand, frame_bottomBand,
833 frame_leftBand, frame_rightBand);
835 ost->encoding_needed = 1;
836 ist->decoding_needed = 1;
842 if (ost->encoding_needed &&
843 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
844 char logfilename[1024];
849 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
851 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
852 if (codec->flags & CODEC_FLAG_PASS1) {
853 f = fopen(logfilename, "w");
860 /* read the log file */
861 f = fopen(logfilename, "r");
866 fseek(f, 0, SEEK_END);
868 fseek(f, 0, SEEK_SET);
869 logbuffer = av_malloc(size + 1);
871 fprintf(stderr, "Could not allocate log buffer\n");
874 fread(logbuffer, 1, size, f);
876 logbuffer[size] = '\0';
877 codec->stats_in = logbuffer;
883 /* dump the file output parameters - cannot be done before in case
885 for(i=0;i<nb_output_files;i++) {
886 dump_format(output_files[i], i, output_files[i]->filename, 1);
889 /* dump the stream mapping */
890 fprintf(stderr, "Stream mapping:\n");
891 for(i=0;i<nb_ostreams;i++) {
893 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
894 ist_table[ost->source_index]->file_index,
895 ist_table[ost->source_index]->index,
900 /* open each encoder */
901 for(i=0;i<nb_ostreams;i++) {
903 if (ost->encoding_needed) {
905 codec = avcodec_find_encoder(ost->st->codec.codec_id);
907 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
908 ost->file_index, ost->index);
911 if (avcodec_open(&ost->st->codec, codec) < 0) {
912 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
913 ost->file_index, ost->index);
919 /* open each decoder */
920 for(i=0;i<nb_istreams;i++) {
922 if (ist->decoding_needed) {
924 codec = avcodec_find_decoder(ist->st->codec.codec_id);
926 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
927 ist->file_index, ist->index);
930 if (avcodec_open(&ist->st->codec, codec) < 0) {
931 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
932 ist->file_index, ist->index);
935 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
936 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
941 for(i=0;i<nb_istreams;i++) {
944 ist->frame_number = 0;
947 /* compute buffer size max (should use a complete heuristic) */
948 for(i=0;i<nb_input_files;i++) {
949 file_table[i].buffer_size_max = 2048;
952 /* open files and write file headers */
953 for(i=0;i<nb_output_files;i++) {
954 os = output_files[i];
955 if (av_write_header(os) < 0) {
956 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
964 fprintf(stderr, "Press [q] to stop encoding\n");
966 fprintf(stderr, "Press [q] to stop playing\n");
971 start_time = av_gettime();
977 int file_index, ist_index;
982 int data_size, got_picture;
984 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
987 /* if 'q' pressed, exits */
989 /* read_key() returns 0 on EOF */
995 /* select the input file with the smallest pts */
998 for(i=0;i<nb_istreams;i++) {
1000 /* For some reason, the pts_increment code breaks q estimation?!? */
1001 if (!ist->discard && !file_table[ist->file_index].eof_reached &&
1002 ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
1003 min_pts = ist->pts /* + ist->pts_increment */;
1004 file_index = ist->file_index;
1007 /* if none, if is finished */
1008 if (file_index < 0) {
1009 if (stream_no_data) {
1010 #ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
1012 snooze(10 * 1000); /* mmu_man */ /* in microsec */
1013 #elif defined(__CYGWIN__)
1019 ts.tv_nsec = 1000 * 1000 * 10;
1028 /* finish if recording time exhausted */
1029 if (recording_time > 0 && min_pts >= recording_time)
1031 /* read a packet from it and output it in the fifo */
1032 is = input_files[file_index];
1033 if (av_read_packet(is, &pkt) < 0) {
1034 file_table[file_index].eof_reached = 1;
1038 stream_no_data = is;
1042 /* the following test is needed in case new streams appear
1043 dynamically in stream : we ignore them */
1044 if (pkt.stream_index >= file_table[file_index].nb_streams)
1045 goto discard_packet;
1046 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1047 ist = ist_table[ist_index];
1049 goto discard_packet;
1051 if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
1052 ist->frame_number++;
1055 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1056 av_hex_dump(pkt.data, pkt.size);
1059 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1065 /* decode the packet if needed */
1066 data_buf = NULL; /* fail safe */
1068 if (ist->decoding_needed) {
1069 switch(ist->st->codec.codec_type) {
1070 case CODEC_TYPE_AUDIO:
1071 /* XXX: could avoid copy if PCM 16 bits with same
1072 endianness as CPU */
1073 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1077 /* Some bug in mpeg audio decoder gives */
1078 /* data_size < 0, it seems they are overflows */
1079 if (data_size <= 0) {
1080 /* no audio frame */
1085 data_buf = (UINT8 *)samples;
1087 case CODEC_TYPE_VIDEO:
1088 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1091 size = (ist->st->codec.width * ist->st->codec.height);
1092 avpicture_fill(&picture, ptr,
1093 ist->st->codec.pix_fmt,
1094 ist->st->codec.width,
1095 ist->st->codec.height);
1098 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1099 ret = avcodec_decode_video(&ist->st->codec,
1100 &picture, &got_picture, ptr, len);
1103 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1104 ist->file_index, ist->index);
1105 av_free_packet(&pkt);
1109 /* no picture yet */
1126 if (!ist->ticker_inited) {
1127 switch (ist->st->codec.codec_type) {
1128 case CODEC_TYPE_AUDIO:
1129 ticker_init(&ist->pts_ticker,
1130 (INT64)ist->st->codec.sample_rate,
1132 ist->ticker_inited = 1;
1134 case CODEC_TYPE_VIDEO:
1135 ticker_init(&ist->pts_ticker,
1136 (INT64)ist->st->r_frame_rate,
1137 ((INT64)1000000 * FRAME_RATE_BASE));
1138 ist->ticker_inited = 1;
1145 switch(ist->st->codec.codec_type) {
1146 case CODEC_TYPE_AUDIO:
1147 //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1148 ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
1149 ist->sample_index += data_size / (2 * ist->st->codec.channels);
1150 ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1152 case CODEC_TYPE_VIDEO:
1153 ist->frame_number++;
1154 //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
1155 // ist->st->codec.frame_rate;
1156 ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
1157 ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) /
1158 ist->st->codec.frame_rate;
1166 /* transcode raw format, encode packets and output them */
1168 for(i=0;i<nb_ostreams;i++) {
1171 if (ost->source_index == ist_index) {
1172 os = output_files[ost->file_index];
1174 if (ost->encoding_needed) {
1175 switch(ost->st->codec.codec_type) {
1176 case CODEC_TYPE_AUDIO:
1177 do_audio_out(os, ost, ist, data_buf, data_size);
1179 case CODEC_TYPE_VIDEO:
1180 do_video_out(os, ost, ist, &picture, &frame_size);
1182 do_video_stats(ost, ist, frame_size);
1188 /* no reencoding needed : output the packet directly */
1189 /* force the input stream PTS */
1190 os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1196 av_free_packet(&pkt);
1198 /* dump report by using the first video and audio streams */
1201 AVFormatContext *oc;
1202 INT64 total_size, ti;
1203 AVCodecContext *enc;
1204 int frame_number, vid;
1205 double bitrate, ti1;
1206 static INT64 last_time;
1208 if ((min_pts - last_time) >= 500000) {
1209 last_time = min_pts;
1211 oc = output_files[0];
1213 total_size = url_ftell(&oc->pb);
1218 for(i=0;i<nb_ostreams;i++) {
1220 enc = &ost->st->codec;
1221 ist = ist_table[ost->source_index];
1222 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1223 frame_number = ist->frame_number;
1224 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1225 frame_number, enc->quality);
1227 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1230 /* compute min pts value */
1231 if (!ist->discard && ist->pts < ti) {
1236 ti1 = (double)ti / 1000000.0;
1239 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1241 sprintf(buf + strlen(buf),
1242 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1243 (double)total_size / 1024, ti1, bitrate);
1245 fprintf(stderr, "%s \r", buf);
1252 /* dump report by using the first video and audio streams */
1255 AVFormatContext *oc;
1256 INT64 total_size, ti;
1257 AVCodecContext *enc;
1258 int frame_number, vid;
1259 double bitrate, ti1;
1261 oc = output_files[0];
1263 total_size = url_ftell(&oc->pb);
1268 for(i=0;i<nb_ostreams;i++) {
1270 enc = &ost->st->codec;
1271 ist = ist_table[ost->source_index];
1272 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1273 frame_number = ist->frame_number;
1274 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1275 frame_number, enc->quality);
1277 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1280 /* compute min pts value */
1281 if (!ist->discard && ist->pts < ti) {
1286 ti1 = ti / 1000000.0;
1289 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1291 sprintf(buf + strlen(buf),
1292 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1293 (double)total_size / 1024, ti1, bitrate);
1295 fprintf(stderr, "%s \n", buf);
1297 /* close each encoder */
1298 for(i=0;i<nb_ostreams;i++) {
1300 if (ost->encoding_needed) {
1301 av_freep(&ost->st->codec.stats_in);
1302 avcodec_close(&ost->st->codec);
1306 /* close each decoder */
1307 for(i=0;i<nb_istreams;i++) {
1309 if (ist->decoding_needed) {
1310 avcodec_close(&ist->st->codec);
1315 /* write the trailer if needed and close file */
1316 for(i=0;i<nb_output_files;i++) {
1317 os = output_files[i];
1318 av_write_trailer(os);
1324 av_free(file_table);
1327 for(i=0;i<nb_istreams;i++) {
1334 for(i=0;i<nb_ostreams;i++) {
1338 fclose(ost->logfile);
1339 ost->logfile = NULL;
1341 fifo_free(&ost->fifo); /* works even if fifo is not
1342 initialized but set to zero */
1343 av_free(ost->pict_tmp.data[0]);
1344 if (ost->video_resample)
1345 img_resample_close(ost->img_resample_ctx);
1346 if (ost->audio_resample)
1347 audio_resample_close(ost->resample);
1360 int file_read(const char *filename)
1363 unsigned char buffer[1024];
1366 if (url_open(&h, filename, O_RDONLY) < 0) {
1367 printf("could not open '%s'\n", filename);
1371 len = url_read(h, buffer, sizeof(buffer));
1374 for(i=0;i<len;i++) putchar(buffer[i]);
1381 void show_licence(void)
1384 "ffmpeg version " FFMPEG_VERSION "\n"
1385 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1386 "This library is free software; you can redistribute it and/or\n"
1387 "modify it under the terms of the GNU Lesser General Public\n"
1388 "License as published by the Free Software Foundation; either\n"
1389 "version 2 of the License, or (at your option) any later version.\n"
1391 "This library is distributed in the hope that it will be useful,\n"
1392 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1393 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1394 "Lesser General Public License for more details.\n"
1396 "You should have received a copy of the GNU Lesser General Public\n"
1397 "License along with this library; if not, write to the Free Software\n"
1398 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1403 void opt_format(const char *arg)
1405 file_iformat = av_find_input_format(arg);
1406 file_oformat = guess_format(arg, NULL, NULL);
1407 if (!file_iformat && !file_oformat) {
1408 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1413 void opt_video_bitrate(const char *arg)
1415 video_bit_rate = atoi(arg) * 1000;
1418 void opt_video_bitrate_tolerance(const char *arg)
1420 video_bit_rate_tolerance = atoi(arg) * 1000;
1423 void opt_video_bitrate_max(const char *arg)
1425 video_rc_max_rate = atoi(arg) * 1000;
1428 void opt_video_bitrate_min(const char *arg)
1430 video_rc_min_rate = atoi(arg) * 1000;
1433 void opt_video_buffer_size(const char *arg)
1435 video_rc_buffer_size = atoi(arg) * 1000;
1438 void opt_video_rc_eq(char *arg)
1444 void opt_workaround_bugs(const char *arg)
1446 workaround_bugs = atoi(arg);
1449 void opt_dct_algo(const char *arg)
1451 dct_algo = atoi(arg);
1454 void opt_idct_algo(const char *arg)
1456 idct_algo = atoi(arg);
1460 void opt_error_resilience(const char *arg)
1462 error_resilience = atoi(arg);
1465 void opt_frame_rate(const char *arg)
1467 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1471 void opt_frame_crop_top(const char *arg)
1473 frame_topBand = atoi(arg);
1474 if (frame_topBand < 0) {
1475 fprintf(stderr, "Incorrect top crop size\n");
1478 if ((frame_topBand % 2) != 0) {
1479 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1482 if ((frame_topBand) >= frame_height){
1483 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1486 frame_height -= frame_topBand;
1489 void opt_frame_crop_bottom(const char *arg)
1491 frame_bottomBand = atoi(arg);
1492 if (frame_bottomBand < 0) {
1493 fprintf(stderr, "Incorrect bottom crop size\n");
1496 if ((frame_bottomBand % 2) != 0) {
1497 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1500 if ((frame_bottomBand) >= frame_height){
1501 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1504 frame_height -= frame_bottomBand;
1507 void opt_frame_crop_left(const char *arg)
1509 frame_leftBand = atoi(arg);
1510 if (frame_leftBand < 0) {
1511 fprintf(stderr, "Incorrect left crop size\n");
1514 if ((frame_leftBand % 2) != 0) {
1515 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1518 if ((frame_leftBand) >= frame_width){
1519 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1522 frame_width -= frame_leftBand;
1525 void opt_frame_crop_right(const char *arg)
1527 frame_rightBand = atoi(arg);
1528 if (frame_rightBand < 0) {
1529 fprintf(stderr, "Incorrect right crop size\n");
1532 if ((frame_rightBand % 2) != 0) {
1533 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1536 if ((frame_rightBand) >= frame_width){
1537 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1540 frame_width -= frame_rightBand;
1543 void opt_frame_size(const char *arg)
1545 parse_image_size(&frame_width, &frame_height, arg);
1546 if (frame_width <= 0 || frame_height <= 0) {
1547 fprintf(stderr, "Incorrect frame size\n");
1550 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1551 fprintf(stderr, "Frame size must be a multiple of 2\n");
1556 void opt_gop_size(const char *arg)
1558 gop_size = atoi(arg);
1561 void opt_b_frames(const char *arg)
1563 b_frames = atoi(arg);
1564 if (b_frames > FF_MAX_B_FRAMES) {
1565 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1567 } else if (b_frames < 1) {
1568 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1573 void opt_qscale(const char *arg)
1575 video_qscale = atoi(arg);
1576 if (video_qscale < 0 ||
1577 video_qscale > 31) {
1578 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1583 void opt_qmin(const char *arg)
1585 video_qmin = atoi(arg);
1586 if (video_qmin < 0 ||
1588 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1593 void opt_qmax(const char *arg)
1595 video_qmax = atoi(arg);
1596 if (video_qmax < 0 ||
1598 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1603 void opt_qdiff(const char *arg)
1605 video_qdiff = atoi(arg);
1606 if (video_qdiff < 0 ||
1608 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1613 void opt_qblur(const char *arg)
1615 video_qblur = atof(arg);
1618 void opt_qcomp(const char *arg)
1620 video_qcomp = atof(arg);
1623 void opt_b_qfactor(const char *arg)
1625 video_b_qfactor = atof(arg);
1627 void opt_i_qfactor(const char *arg)
1629 video_i_qfactor = atof(arg);
1631 void opt_b_qoffset(const char *arg)
1633 video_b_qoffset = atof(arg);
1635 void opt_i_qoffset(const char *arg)
1637 video_i_qoffset = atof(arg);
1640 void opt_packet_size(const char *arg)
1642 packet_size= atoi(arg);
1645 void opt_audio_bitrate(const char *arg)
1647 audio_bit_rate = atoi(arg) * 1000;
1650 void opt_audio_rate(const char *arg)
1652 audio_sample_rate = atoi(arg);
1655 void opt_audio_channels(const char *arg)
1657 audio_channels = atoi(arg);
1660 void opt_video_device(const char *arg)
1662 v4l_device = strdup(arg);
1665 void opt_audio_device(const char *arg)
1667 audio_device = strdup(arg);
1670 void opt_audio_codec(const char *arg)
1674 if (!strcmp(arg, "copy")) {
1675 audio_stream_copy = 1;
1679 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1684 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1687 audio_codec_id = p->id;
1692 const char *motion_str[] = {
1702 void opt_motion_estimation(const char *arg)
1708 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1711 if (!strcmp(*p, arg))
1715 me_method = (p - motion_str) + 1;
1718 void opt_video_codec(const char *arg)
1722 if (!strcmp(arg, "copy")) {
1723 video_stream_copy = 1;
1727 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1732 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1735 video_codec_id = p->id;
1740 void opt_map(const char *arg)
1746 m = &stream_maps[nb_stream_maps++];
1748 m->file_index = strtol(arg, (char **)&p, 0);
1752 m->stream_index = strtol(p, (char **)&p, 0);
1755 void opt_recording_time(const char *arg)
1757 recording_time = parse_date(arg, 1);
1760 void print_error(const char *filename, int err)
1763 case AVERROR_NUMEXPECTED:
1764 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1765 "Use '%%d' to specify the image number:\n"
1766 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1767 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1770 case AVERROR_INVALIDDATA:
1771 fprintf(stderr, "%s: Error while parsing header\n", filename);
1774 fprintf(stderr, "%s: Unknown format\n", filename);
1777 fprintf(stderr, "%s: Error while opening file\n", filename);
1782 void opt_input_file(const char *filename)
1784 AVFormatContext *ic;
1785 AVFormatParameters params, *ap = ¶ms;
1786 int err, i, ret, rfps;
1788 /* get default parameters from command line */
1789 memset(ap, 0, sizeof(*ap));
1790 ap->sample_rate = audio_sample_rate;
1791 ap->channels = audio_channels;
1792 ap->frame_rate = frame_rate;
1793 ap->width = frame_width;
1794 ap->height = frame_height;
1796 /* open the input file with generic libav function */
1797 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1799 print_error(filename, err);
1803 /* If not enough info to get the stream parameters, we decode the
1804 first frames to get it. (used in mpeg case for example) */
1805 ret = av_find_stream_info(ic);
1807 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1811 /* update the current parameters so that they match the one of the input stream */
1812 for(i=0;i<ic->nb_streams;i++) {
1813 AVCodecContext *enc = &ic->streams[i]->codec;
1814 switch(enc->codec_type) {
1815 case CODEC_TYPE_AUDIO:
1816 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1817 audio_channels = enc->channels;
1818 audio_sample_rate = enc->sample_rate;
1820 case CODEC_TYPE_VIDEO:
1821 frame_height = enc->height;
1822 frame_width = enc->width;
1823 rfps = ic->streams[i]->r_frame_rate;
1824 enc->workaround_bugs = workaround_bugs;
1825 enc->error_resilience = error_resilience;
1826 enc->idct_algo= idct_algo;
1827 if (enc->frame_rate != rfps) {
1828 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1829 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1830 (float)rfps / FRAME_RATE_BASE);
1832 /* update the current frame rate to match the stream frame rate */
1840 input_files[nb_input_files] = ic;
1841 /* dump the file content */
1842 dump_format(ic, nb_input_files, filename, 0);
1844 file_iformat = NULL;
1845 file_oformat = NULL;
1848 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1850 int has_video, has_audio, i, j;
1851 AVFormatContext *ic;
1855 for(j=0;j<nb_input_files;j++) {
1856 ic = input_files[j];
1857 for(i=0;i<ic->nb_streams;i++) {
1858 AVCodecContext *enc = &ic->streams[i]->codec;
1859 switch(enc->codec_type) {
1860 case CODEC_TYPE_AUDIO:
1863 case CODEC_TYPE_VIDEO:
1871 *has_video_ptr = has_video;
1872 *has_audio_ptr = has_audio;
1875 void opt_output_file(const char *filename)
1878 AVFormatContext *oc;
1879 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1882 if (!strcmp(filename, "-"))
1885 oc = av_mallocz(sizeof(AVFormatContext));
1887 if (!file_oformat) {
1888 file_oformat = guess_format(NULL, filename, NULL);
1889 if (!file_oformat) {
1890 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1896 oc->oformat = file_oformat;
1898 if (!strcmp(file_oformat->name, "ffm") &&
1899 strstart(filename, "http:", NULL)) {
1900 /* special case for files sent to ffserver: we get the stream
1901 parameters from ffserver */
1902 if (read_ffserver_streams(oc, filename) < 0) {
1903 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1907 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1908 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1910 /* disable if no corresponding type found and at least one
1912 if (nb_input_files > 0) {
1913 check_audio_video_inputs(&input_has_video, &input_has_audio);
1914 if (!input_has_video)
1916 if (!input_has_audio)
1920 /* manual disable */
1921 if (audio_disable) {
1924 if (video_disable) {
1930 AVCodecContext *video_enc;
1932 st = av_mallocz(sizeof(AVStream));
1934 fprintf(stderr, "Could not alloc stream\n");
1938 video_enc = &st->codec;
1939 if (video_stream_copy) {
1940 st->stream_copy = 1;
1941 video_enc->codec_type = CODEC_TYPE_VIDEO;
1943 codec_id = file_oformat->video_codec;
1944 if (video_codec_id != CODEC_ID_NONE)
1945 codec_id = video_codec_id;
1947 video_enc->codec_id = codec_id;
1949 video_enc->bit_rate = video_bit_rate;
1950 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1951 video_enc->frame_rate = frame_rate;
1953 video_enc->width = frame_width;
1954 video_enc->height = frame_height;
1957 video_enc->gop_size = gop_size;
1959 video_enc->gop_size = 0;
1960 if (video_qscale || same_quality) {
1961 video_enc->flags |= CODEC_FLAG_QSCALE;
1962 video_enc->quality = video_qscale;
1966 video_enc->flags |= CODEC_FLAG_HQ;
1970 video_enc->flags |= CODEC_FLAG_HQ;
1971 video_enc->flags |= CODEC_FLAG_4MV;
1975 video_enc->flags |= CODEC_FLAG_PART;
1979 if (codec_id != CODEC_ID_MPEG4) {
1980 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1983 video_enc->max_b_frames = b_frames;
1984 video_enc->b_frame_strategy = 0;
1985 video_enc->b_quant_factor = 2.0;
1988 video_enc->qmin = video_qmin;
1989 video_enc->qmax = video_qmax;
1990 video_enc->max_qdiff = video_qdiff;
1991 video_enc->qblur = video_qblur;
1992 video_enc->qcompress = video_qcomp;
1993 video_enc->rc_eq = video_rc_eq;
1994 video_enc->rc_max_rate = video_rc_max_rate;
1995 video_enc->rc_min_rate = video_rc_min_rate;
1996 video_enc->rc_buffer_size = video_rc_buffer_size;
1997 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
1998 video_enc->i_quant_factor = video_i_qfactor;
1999 video_enc->b_quant_factor = video_b_qfactor;
2000 video_enc->i_quant_offset = video_i_qoffset;
2001 video_enc->b_quant_offset = video_b_qoffset;
2002 video_enc->dct_algo = dct_algo;
2003 video_enc->idct_algo = idct_algo;
2005 video_enc->rtp_mode= 1;
2006 video_enc->rtp_payload_size= packet_size;
2010 video_enc->get_psnr = 1;
2012 video_enc->get_psnr = 0;
2014 video_enc->me_method = me_method;
2019 video_enc->flags |= CODEC_FLAG_PASS1;
2021 video_enc->flags |= CODEC_FLAG_PASS2;
2025 /* XXX: need to find a way to set codec parameters */
2026 if (oc->oformat->flags & AVFMT_RGB24) {
2027 video_enc->pix_fmt = PIX_FMT_RGB24;
2030 oc->streams[nb_streams] = st;
2035 AVCodecContext *audio_enc;
2037 st = av_mallocz(sizeof(AVStream));
2039 fprintf(stderr, "Could not alloc stream\n");
2043 audio_enc = &st->codec;
2044 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2045 if (audio_stream_copy) {
2046 st->stream_copy = 1;
2048 codec_id = file_oformat->audio_codec;
2049 if (audio_codec_id != CODEC_ID_NONE)
2050 codec_id = audio_codec_id;
2051 audio_enc->codec_id = codec_id;
2053 audio_enc->bit_rate = audio_bit_rate;
2054 audio_enc->sample_rate = audio_sample_rate;
2055 /* For audio codecs other than AC3 we limit */
2056 /* the number of coded channels to stereo */
2057 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2058 audio_enc->channels = 2;
2060 audio_enc->channels = audio_channels;
2062 oc->streams[nb_streams] = st;
2066 oc->nb_streams = nb_streams;
2069 fprintf(stderr, "No audio or video streams available\n");
2074 pstrcpy(oc->title, sizeof(oc->title), str_title);
2076 pstrcpy(oc->author, sizeof(oc->author), str_author);
2078 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2080 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2083 output_files[nb_output_files++] = oc;
2085 strcpy(oc->filename, filename);
2087 /* check filename in case of an image number is expected */
2088 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2089 if (filename_number_test(oc->filename) < 0) {
2090 print_error(oc->filename, AVERROR_NUMEXPECTED);
2095 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2096 /* test if it already exists to avoid loosing precious files */
2097 if (!file_overwrite &&
2098 (strchr(filename, ':') == NULL ||
2099 strstart(filename, "file:", NULL))) {
2100 if (url_exist(filename)) {
2103 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2106 if (toupper(c) != 'Y') {
2107 fprintf(stderr, "Not overwriting - exiting\n");
2114 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2115 fprintf(stderr, "Could not open '%s'\n", filename);
2120 /* reset some options */
2121 file_oformat = NULL;
2122 file_iformat = NULL;
2125 audio_codec_id = CODEC_ID_NONE;
2126 video_codec_id = CODEC_ID_NONE;
2127 audio_stream_copy = 0;
2128 video_stream_copy = 0;
2131 /* prepare dummy protocols for grab */
2132 void prepare_grab(void)
2134 int has_video, has_audio, i, j;
2135 AVFormatContext *oc;
2136 AVFormatContext *ic;
2137 AVFormatParameters ap1, *ap = &ap1;
2139 /* see if audio/video inputs are needed */
2142 memset(ap, 0, sizeof(*ap));
2143 for(j=0;j<nb_output_files;j++) {
2144 oc = output_files[j];
2145 for(i=0;i<oc->nb_streams;i++) {
2146 AVCodecContext *enc = &oc->streams[i]->codec;
2147 switch(enc->codec_type) {
2148 case CODEC_TYPE_AUDIO:
2149 if (enc->sample_rate > ap->sample_rate)
2150 ap->sample_rate = enc->sample_rate;
2151 if (enc->channels > ap->channels)
2152 ap->channels = enc->channels;
2155 case CODEC_TYPE_VIDEO:
2156 if (enc->width > ap->width)
2157 ap->width = enc->width;
2158 if (enc->height > ap->height)
2159 ap->height = enc->height;
2160 if (enc->frame_rate > ap->frame_rate)
2161 ap->frame_rate = enc->frame_rate;
2170 if (has_video == 0 && has_audio == 0) {
2171 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2176 AVInputFormat *fmt1;
2177 fmt1 = av_find_input_format("video_grab_device");
2178 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2179 fprintf(stderr, "Could not find video grab device\n");
2182 /* by now video grab has one stream */
2183 ic->streams[0]->r_frame_rate = ap->frame_rate;
2184 input_files[nb_input_files] = ic;
2185 dump_format(ic, nb_input_files, v4l_device, 0);
2189 AVInputFormat *fmt1;
2190 fmt1 = av_find_input_format("audio_device");
2191 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2192 fprintf(stderr, "Could not find audio grab device\n");
2195 input_files[nb_input_files] = ic;
2196 dump_format(ic, nb_input_files, audio_device, 0);
2201 /* open the necessary output devices for playing */
2202 void prepare_play(void)
2204 file_iformat = NULL;
2205 file_oformat = guess_format("audio_device", NULL, NULL);
2206 if (!file_oformat) {
2207 fprintf(stderr, "Could not find audio device\n");
2211 opt_output_file(audio_device);
2214 /* same option as mencoder */
2215 void opt_pass(const char *pass_str)
2218 pass = atoi(pass_str);
2219 if (pass != 1 && pass != 2) {
2220 fprintf(stderr, "pass number can be only 1 or 2\n");
2226 #ifndef CONFIG_WIN32
2227 INT64 getutime(void)
2229 struct rusage rusage;
2231 getrusage(RUSAGE_SELF, &rusage);
2232 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2235 INT64 getutime(void)
2237 return av_gettime();
2241 extern int ffm_nopts;
2243 void opt_bitexact(void)
2245 avcodec_set_bit_exact();
2246 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2250 void show_formats(void)
2252 AVInputFormat *ifmt;
2253 AVOutputFormat *ofmt;
2258 printf("File formats:\n");
2259 printf(" Encoding:");
2260 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2261 printf(" %s", ofmt->name);
2264 printf(" Decoding:");
2265 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2266 printf(" %s", ifmt->name);
2270 printf("Codecs:\n");
2271 printf(" Encoders:");
2272 for(p = first_avcodec; p != NULL; p = p->next) {
2274 printf(" %s", p->name);
2278 printf(" Decoders:");
2279 for(p = first_avcodec; p != NULL; p = p->next) {
2281 printf(" %s", p->name);
2285 printf("Supported file protocols:");
2286 for(up = first_protocol; up != NULL; up = up->next)
2287 printf(" %s:", up->name);
2290 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2291 printf("Motion estimation methods:");
2295 if ((pp - motion_str + 1) == ME_ZERO)
2296 printf("(fastest)");
2297 else if ((pp - motion_str + 1) == ME_FULL)
2298 printf("(slowest)");
2299 else if ((pp - motion_str + 1) == ME_EPZS)
2300 printf("(default)");
2307 void show_help(void)
2310 const OptionDef *po;
2313 prog = do_play ? "ffplay" : "ffmpeg";
2315 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2319 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2320 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2322 printf("usage: ffplay [options] input_file...\n"
2323 "Simple audio player\n");
2327 "Main options are:\n");
2330 printf("\nAdvanced options are:\n");
2331 for(po = options; po->name != NULL; po++) {
2333 expert = (po->flags & OPT_EXPERT) != 0;
2335 strcpy(buf, po->name);
2336 if (po->flags & HAS_ARG) {
2338 strcat(buf, po->argname);
2340 printf("-%-17s %s\n", buf, po->help);
2348 const OptionDef options[] = {
2349 { "L", 0, {(void*)show_licence}, "show license" },
2350 { "h", 0, {(void*)show_help}, "show help" },
2351 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2352 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2353 { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2354 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2355 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2356 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2357 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2358 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2359 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2360 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2361 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2362 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2363 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2365 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2366 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2367 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2368 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2369 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2370 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2371 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2372 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2373 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2374 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2375 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2376 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2377 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2378 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2379 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2380 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2381 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2382 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2383 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2384 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2385 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2386 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2387 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2388 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2389 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2390 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2391 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2392 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2394 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2395 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2396 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2397 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2398 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2399 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2400 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2401 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2402 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2403 { "sameq", OPT_BOOL, {(void*)&same_quality},
2404 "use same video quality as source (implies VBR)" },
2406 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2407 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2408 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2409 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2410 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2411 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2412 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2413 "deinterlace pictures" },
2414 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2415 "add timings for benchmarking" },
2416 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2417 "dump each input packet" },
2418 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2419 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2420 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2424 int main(int argc, char **argv)
2427 const char *opt, *arg;
2428 const OptionDef *po;
2433 /* detect if invoked as player */
2434 i = strlen(argv[0]);
2435 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2443 while (optindex < argc) {
2444 opt = argv[optindex++];
2446 if (opt[0] == '-' && opt[1] != '\0') {
2448 while (po->name != NULL) {
2449 if (!strcmp(opt + 1, po->name))
2454 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2458 if (po->flags & HAS_ARG)
2459 arg = argv[optindex++];
2460 if (po->flags & OPT_STRING) {
2463 *po->u.str_arg = str;
2464 } else if (po->flags & OPT_BOOL) {
2467 po->u.func_arg(arg);
2471 opt_output_file(opt);
2473 opt_input_file(opt);
2480 /* file converter / grab */
2481 if (nb_output_files <= 0) {
2482 fprintf(stderr, "Must supply at least one output file\n");
2486 if (nb_input_files == 0) {
2491 if (nb_input_files <= 0) {
2492 fprintf(stderr, "Must supply at least one input file\n");
2499 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2500 stream_maps, nb_stream_maps);
2501 ti = getutime() - ti;
2503 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2507 for(i=0;i<nb_output_files;i++) {
2508 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
2509 url_fclose(&output_files[i]->pb);
2511 for(i=0;i<nb_input_files;i++)
2512 av_close_input_file(input_files[i]);