3 * Copyright (c) 2000-2003 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>
33 #include <sys/types.h>
34 #include <sys/select.h>
41 #if !defined(INFINITY) && defined(HUGE_VAL)
42 #define INFINITY HUGE_VAL
45 /* select an input stream for an output stream */
46 typedef struct AVStreamMap {
51 extern const OptionDef options[];
53 static void show_help(void);
54 static void show_license(void);
58 static AVFormatContext *input_files[MAX_FILES];
59 static int nb_input_files = 0;
61 static AVFormatContext *output_files[MAX_FILES];
62 static int nb_output_files = 0;
64 static AVStreamMap stream_maps[MAX_FILES];
65 static int nb_stream_maps;
67 static AVInputFormat *file_iformat;
68 static AVOutputFormat *file_oformat;
69 static AVImageFormat *image_format;
70 static int frame_width = 160;
71 static int frame_height = 128;
72 static float frame_aspect_ratio = 0;
73 static enum PixelFormat frame_pix_fmt = PIX_FMT_YUV420P;
74 static int frame_topBand = 0;
75 static int frame_bottomBand = 0;
76 static int frame_leftBand = 0;
77 static int frame_rightBand = 0;
78 static int frame_rate = 25;
79 static int frame_rate_base = 1;
80 static int video_bit_rate = 200*1000;
81 static int video_bit_rate_tolerance = 4000*1000;
82 static float video_qscale = 0;
83 static int video_qmin = 2;
84 static int video_qmax = 31;
85 static int video_mb_qmin = 2;
86 static int video_mb_qmax = 31;
87 static int video_qdiff = 3;
88 static float video_qblur = 0.5;
89 static float video_qcomp = 0.5;
90 static uint16_t *intra_matrix = NULL;
91 static uint16_t *inter_matrix = NULL;
92 #if 0 //experimental, (can be removed)
93 static float video_rc_qsquish=1.0;
94 static float video_rc_qmod_amp=0;
95 static int video_rc_qmod_freq=0;
97 static char *video_rc_override_string=NULL;
98 static char *video_rc_eq="tex^qComp";
99 static int video_rc_buffer_size=0;
100 static float video_rc_buffer_aggressivity=1.0;
101 static int video_rc_max_rate=0;
102 static int video_rc_min_rate=0;
103 static float video_rc_initial_cplx=0;
104 static float video_b_qfactor = 1.25;
105 static float video_b_qoffset = 1.25;
106 static float video_i_qfactor = -0.8;
107 static float video_i_qoffset = 0.0;
108 static int me_method = ME_EPZS;
109 static int video_disable = 0;
110 static int video_codec_id = CODEC_ID_NONE;
111 static int same_quality = 0;
112 static int b_frames = 0;
113 static int mb_decision = FF_MB_DECISION_SIMPLE;
114 static int use_4mv = 0;
115 static int use_obmc = 0;
116 static int use_aic = 0;
117 static int use_aiv = 0;
118 static int use_umv = 0;
119 static int do_deinterlace = 0;
120 static int do_interlace = 0;
121 static int workaround_bugs = FF_BUG_AUTODETECT;
122 static int error_resilience = 2;
123 static int error_concealment = 3;
124 static int dct_algo = 0;
125 static int idct_algo = 0;
126 static int use_part = 0;
127 static int packet_size = 0;
128 static int strict = 0;
129 static int debug = 0;
130 extern int loop_input; /* currently a hack */
132 static int gop_size = 12;
133 static int intra_only = 0;
134 static int audio_sample_rate = 44100;
135 static int audio_bit_rate = 64000;
136 static int audio_disable = 0;
137 static int audio_channels = 1;
138 static int audio_codec_id = CODEC_ID_NONE;
140 static int64_t recording_time = 0;
141 static int64_t start_time = 0;
142 static int file_overwrite = 0;
143 static char *str_title = NULL;
144 static char *str_author = NULL;
145 static char *str_copyright = NULL;
146 static char *str_comment = NULL;
147 static int do_benchmark = 0;
148 static int do_hex_dump = 0;
149 static int do_pkt_dump = 0;
150 static int do_psnr = 0;
151 static int do_vstats = 0;
152 static int do_pass = 0;
153 static int bitexact = 0;
154 static char *pass_logfilename = NULL;
155 static int audio_stream_copy = 0;
156 static int video_stream_copy = 0;
158 static int rate_emu = 0;
160 static char *video_grab_format = "video4linux";
161 static char *video_device = NULL;
162 static int video_channel = 0;
163 static char *video_standard = "ntsc";
165 static char *audio_grab_format = "audio_device";
166 static char *audio_device = NULL;
168 static int using_stdin = 0;
169 static int using_vhook = 0;
170 static int verbose = 1;
172 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
174 typedef struct AVOutputStream {
175 int file_index; /* file index */
176 int index; /* stream index in the output file */
177 int source_index; /* AVInputStream index */
178 AVStream *st; /* stream in the output file */
179 int encoding_needed; /* true if encoding needed for this stream */
181 /* input pts and corresponding output pts
184 double sync_ipts_offset;
187 int video_resample; /* video_resample and video_crop are mutually exclusive */
188 AVPicture pict_tmp; /* temporary image for resampling */
189 ImgReSampleContext *img_resample_ctx; /* for image resampling */
191 int video_crop; /* video_resample and video_crop are mutually exclusive */
192 int topBand; /* cropping area sizes */
197 ReSampleContext *resample; /* for audio resampling */
198 FifoBuffer fifo; /* for compression: one audio fifo per codec */
202 typedef struct AVInputStream {
206 int discard; /* true if stream data should be discarded */
207 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
208 int64_t sample_index; /* current sample */
210 int64_t start; /* time when read started */
211 unsigned long frame; /* current frame */
212 int64_t next_pts; /* synthetic pts for cases where pkt.pts
214 int64_t pts; /* current pts */
217 typedef struct AVInputFile {
218 int eof_reached; /* true if eof reached */
219 int ist_index; /* index of first stream in ist_table */
220 int buffer_size; /* current total buffer size */
221 int buffer_size_max; /* buffer size at which we consider we can stop
223 int nb_streams; /* nb streams we are aware of */
228 /* init terminal so that we can grab keys */
229 static struct termios oldtty;
231 static void term_exit(void)
233 tcsetattr (0, TCSANOW, &oldtty);
236 static volatile sig_atomic_t received_sigterm = 0;
239 sigterm_handler(int sig)
241 received_sigterm = sig;
245 static void term_init(void)
252 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
253 |INLCR|IGNCR|ICRNL|IXON);
254 tty.c_oflag |= OPOST;
255 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
256 tty.c_cflag &= ~(CSIZE|PARENB);
261 tcsetattr (0, TCSANOW, &tty);
263 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
264 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
265 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
267 register a function to be called at normal program termination
270 #ifdef CONFIG_BEOS_NETSERVER
271 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
275 /* read a key without blocking */
276 static int read_key(void)
280 #ifndef CONFIG_BEOS_NETSERVER
288 n = select(1, &rfds, NULL, NULL, &tv);
302 static volatile int received_sigterm = 0;
304 /* no interactive support */
305 static void term_exit(void)
309 static void term_init(void)
313 static int read_key(void)
320 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
325 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
328 /* copy stream format */
329 s->nb_streams = ic->nb_streams;
330 for(i=0;i<ic->nb_streams;i++) {
333 st = av_mallocz(sizeof(AVStream));
334 memcpy(st, ic->streams[i], sizeof(AVStream));
338 av_close_input_file(ic);
342 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
344 static void do_audio_out(AVFormatContext *s,
347 unsigned char *buf, int size)
350 static uint8_t *audio_buf = NULL;
351 static uint8_t *audio_out = NULL;
352 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
354 int size_out, frame_bytes, ret;
357 /* SC: dynamic allocation of buffers */
359 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
361 audio_out = av_malloc(audio_out_size);
362 if (!audio_buf || !audio_out)
363 return; /* Should signal an error ! */
366 enc = &ost->st->codec;
368 if (ost->audio_resample) {
370 size_out = audio_resample(ost->resample,
371 (short *)buftmp, (short *)buf,
372 size / (ist->st->codec.channels * 2));
373 size_out = size_out * enc->channels * 2;
379 /* now encode as many frames as possible */
380 if (enc->frame_size > 1) {
381 /* output resampled raw samples */
382 fifo_write(&ost->fifo, buftmp, size_out,
385 frame_bytes = enc->frame_size * 2 * enc->channels;
387 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
388 &ost->fifo.rptr) == 0) {
389 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
391 av_write_frame(s, ost->index, audio_out, ret);
394 /* output a pcm frame */
395 /* XXX: change encoding codec API to avoid this ? */
396 switch(enc->codec->id) {
397 case CODEC_ID_PCM_S16LE:
398 case CODEC_ID_PCM_S16BE:
399 case CODEC_ID_PCM_U16LE:
400 case CODEC_ID_PCM_U16BE:
403 size_out = size_out >> 1;
406 ret = avcodec_encode_audio(enc, audio_out, size_out,
408 av_write_frame(s, ost->index, audio_out, ret);
412 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
416 AVPicture picture_tmp;
419 dec = &ist->st->codec;
421 /* deinterlace : must be done before any resize */
422 if (do_deinterlace || using_vhook) {
425 /* create temporary picture */
426 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
427 buf = av_malloc(size);
431 picture2 = &picture_tmp;
432 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
435 if(avpicture_deinterlace(picture2, picture,
436 dec->pix_fmt, dec->width, dec->height) < 0) {
437 /* if error, do not deinterlace */
443 if (img_convert(picture2, dec->pix_fmt, picture,
444 dec->pix_fmt, dec->width, dec->height) < 0) {
445 /* if error, do not copy */
455 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
457 if (picture != picture2)
458 *picture = *picture2;
462 /* we begin to correct av delay at this threshold */
463 #define AV_DELAY_MAX 0.100
465 static void do_video_out(AVFormatContext *s,
468 AVPicture *in_picture,
469 int *frame_size, AVOutputStream *audio_sync)
471 int nb_frames, i, ret;
472 AVPicture *final_picture, *formatted_picture;
473 AVPicture picture_format_temp, picture_crop_temp;
474 static uint8_t *video_buffer;
475 uint8_t *buf = NULL, *buf1 = NULL;
476 AVCodecContext *enc, *dec;
477 enum PixelFormat target_pixfmt;
479 #define VIDEO_BUFFER_SIZE (1024*1024)
481 enc = &ost->st->codec;
482 dec = &ist->st->codec;
484 /* by default, we output a single frame */
489 /* NOTE: the A/V sync is always done by considering the audio is
490 the master clock. It is suffisant for transcoding or playing,
491 but not for the general case */
493 /* compute the A-V delay and duplicate/remove frames if needed */
494 double adelta, vdelta, av_delay;
496 adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts *
497 s->pts_num / s->pts_den);
499 vdelta = ost->sync_ipts - ((double)ost->sync_opts *
500 s->pts_num / s->pts_den);
502 av_delay = adelta - vdelta;
503 // printf("delay=%f\n", av_delay);
504 if (av_delay < -AV_DELAY_MAX)
506 else if (av_delay > AV_DELAY_MAX)
511 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
512 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
513 if (vdelta < -AV_DELAY_MAX)
515 else if (vdelta > AV_DELAY_MAX)
518 ost->sync_ipts_offset -= vdelta;
519 if (!ost->sync_ipts_offset)
520 ost->sync_ipts_offset = 0.000001; /* one microsecond */
524 #if defined(AVSYNC_DEBUG)
526 static char *action[] = { "drop frame", "copy frame", "dup frame" };
528 fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
529 (double) audio_sync->sync_ipts,
530 (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
531 fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
532 (double) ost->sync_ipts,
533 (double) ost->st->pts.val * s->pts_num / s->pts_den,
542 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
546 /* convert pixel format if needed */
547 target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
548 if (dec->pix_fmt != target_pixfmt) {
551 /* create temporary picture */
552 size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
553 buf = av_malloc(size);
556 formatted_picture = &picture_format_temp;
557 avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
559 if (img_convert(formatted_picture, target_pixfmt,
560 in_picture, dec->pix_fmt,
561 dec->width, dec->height) < 0) {
562 fprintf(stderr, "pixel format conversion not handled\n");
566 formatted_picture = in_picture;
569 /* XXX: resampling could be done before raw format convertion in
570 some cases to go faster */
571 /* XXX: only works for YUV420P */
572 if (ost->video_resample) {
573 final_picture = &ost->pict_tmp;
574 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
575 if (enc->pix_fmt != PIX_FMT_YUV420P) {
579 /* create temporary picture */
580 size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
581 buf = av_malloc(size);
584 final_picture = &picture_format_temp;
585 avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
587 if (img_convert(final_picture, enc->pix_fmt,
588 &ost->pict_tmp, PIX_FMT_YUV420P,
589 enc->width, enc->height) < 0) {
590 fprintf(stderr, "pixel format conversion not handled\n");
594 } else if (ost->video_crop) {
595 picture_crop_temp.data[0] = formatted_picture->data[0] +
596 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
598 picture_crop_temp.data[1] = formatted_picture->data[1] +
599 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
600 (ost->leftBand >> 1);
602 picture_crop_temp.data[2] = formatted_picture->data[2] +
603 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
604 (ost->leftBand >> 1);
606 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
607 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
608 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
609 final_picture = &picture_crop_temp;
611 final_picture = formatted_picture;
613 /* duplicates frame if needed */
614 /* XXX: pb because no interleaving */
615 for(i=0;i<nb_frames;i++) {
616 if (s->oformat->flags & AVFMT_RAWPICTURE) {
617 /* raw pictures are written as AVPicture structure to
618 avoid any copies. We support temorarily the older
620 AVFrame* old_frame = enc->coded_frame;
621 enc->coded_frame = dec->coded_frame;
622 av_write_frame(s, ost->index,
623 (uint8_t *)final_picture, sizeof(AVPicture));
624 enc->coded_frame = old_frame;
628 memset(&big_picture, 0, sizeof(AVFrame));
629 *(AVPicture*)&big_picture= *final_picture;
631 /* handles sameq here. This is not correct because it may
632 not be a global option */
634 big_picture.quality = ist->st->quality;
636 big_picture.quality = ost->st->quality;
638 ret = avcodec_encode_video(enc,
639 video_buffer, VIDEO_BUFFER_SIZE,
641 //enc->frame_number = enc->real_pict_num;
642 av_write_frame(s, ost->index, video_buffer, ret);
644 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
645 // enc->frame_number-1, enc->real_pict_num, ret,
647 /* if two pass, output log */
648 if (ost->logfile && enc->stats_out) {
649 fprintf(ost->logfile, "%s", enc->stats_out);
659 static double psnr(double d){
660 if(d==0) return INFINITY;
661 return -10.0*log(d)/log(10.0);
664 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
667 static FILE *fvstats=NULL;
668 static int64_t total_size = 0;
675 double ti1, bitrate, avg_bitrate;
679 today = localtime(&today2);
680 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
683 fvstats = fopen(filename,"w");
691 enc = &ost->st->codec;
692 total_size += frame_size;
693 if (enc->codec_type == CODEC_TYPE_VIDEO) {
694 frame_number = ost->frame_number;
695 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
696 if (enc->flags&CODEC_FLAG_PSNR)
697 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
699 fprintf(fvstats,"f_size= %6d ", frame_size);
700 /* compute pts value */
701 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
705 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
706 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
707 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
708 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
709 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
713 static void print_report(AVFormatContext **output_files,
714 AVOutputStream **ost_table, int nb_ostreams,
719 AVFormatContext *oc, *os;
722 int frame_number, vid, i;
723 double bitrate, ti1, pts;
724 static int64_t last_time = -1;
726 if (!is_last_report) {
728 /* display the report every 0.5 seconds */
729 cur_time = av_gettime();
730 if (last_time == -1) {
731 last_time = cur_time;
734 if ((cur_time - last_time) < 500000)
736 last_time = cur_time;
740 oc = output_files[0];
742 total_size = url_ftell(&oc->pb);
747 for(i=0;i<nb_ostreams;i++) {
749 os = output_files[ost->file_index];
750 enc = &ost->st->codec;
751 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
752 sprintf(buf + strlen(buf), "q=%2.1f ",
753 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
755 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
756 frame_number = ost->frame_number;
757 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
758 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
759 if (enc->flags&CODEC_FLAG_PSNR)
760 sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
763 /* compute min output value */
764 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
765 if ((pts < ti1) && (pts > 0))
771 if (verbose || is_last_report) {
772 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
774 sprintf(buf + strlen(buf),
775 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
776 (double)total_size / 1024, ti1, bitrate);
778 fprintf(stderr, "%s \r", buf);
783 fprintf(stderr, "\n");
787 * The following code is the main loop of the file converter
789 static int av_encode(AVFormatContext **output_files,
791 AVFormatContext **input_files,
793 AVStreamMap *stream_maps, int nb_stream_maps)
795 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
796 AVFormatContext *is, *os;
797 AVCodecContext *codec, *icodec;
798 AVOutputStream *ost, **ost_table = NULL;
799 AVInputStream *ist, **ist_table = NULL;
800 AVInputFile *file_table;
801 AVFormatContext *stream_no_data;
804 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
808 /* input stream init */
810 for(i=0;i<nb_input_files;i++) {
812 file_table[i].ist_index = j;
813 file_table[i].nb_streams = is->nb_streams;
818 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
822 for(i=0;i<nb_istreams;i++) {
823 ist = av_mallocz(sizeof(AVInputStream));
829 for(i=0;i<nb_input_files;i++) {
831 for(k=0;k<is->nb_streams;k++) {
832 ist = ist_table[j++];
833 ist->st = is->streams[k];
836 ist->discard = 1; /* the stream is discarded by default
839 if (ist->st->codec.rate_emu) {
840 ist->start = av_gettime();
846 /* output stream init */
848 for(i=0;i<nb_output_files;i++) {
849 os = output_files[i];
850 nb_ostreams += os->nb_streams;
852 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
853 fprintf(stderr, "Number of stream maps must match number of output streams\n");
857 /* Sanity check the mapping args -- do the input files & streams exist? */
858 for(i=0;i<nb_stream_maps;i++) {
859 int fi = stream_maps[i].file_index;
860 int si = stream_maps[i].stream_index;
862 if (fi < 0 || fi > nb_input_files - 1 ||
863 si < 0 || si > file_table[fi].nb_streams - 1) {
864 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
869 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
872 for(i=0;i<nb_ostreams;i++) {
873 ost = av_mallocz(sizeof(AVOutputStream));
880 for(k=0;k<nb_output_files;k++) {
881 os = output_files[k];
882 for(i=0;i<os->nb_streams;i++) {
884 ost = ost_table[n++];
887 ost->st = os->streams[i];
888 if (nb_stream_maps > 0) {
889 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
890 stream_maps[n-1].stream_index;
892 /* Sanity check that the stream types match */
893 if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
894 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
895 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
896 ost->file_index, ost->index);
901 /* get corresponding input stream index : we select the first one with the right type */
903 for(j=0;j<nb_istreams;j++) {
906 ist->st->codec.codec_type == ost->st->codec.codec_type) {
907 ost->source_index = j;
913 /* try again and reuse existing stream */
914 for(j=0;j<nb_istreams;j++) {
916 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
917 ost->source_index = j;
922 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
923 ost->file_index, ost->index);
928 ist = ist_table[ost->source_index];
933 /* for each output stream, we compute the right encoding parameters */
934 for(i=0;i<nb_ostreams;i++) {
936 ist = ist_table[ost->source_index];
938 codec = &ost->st->codec;
939 icodec = &ist->st->codec;
941 if (ost->st->stream_copy) {
942 /* if stream_copy is selected, no need to decode or encode */
943 codec->codec_id = icodec->codec_id;
944 codec->codec_type = icodec->codec_type;
945 codec->codec_tag = icodec->codec_tag;
946 codec->bit_rate = icodec->bit_rate;
947 switch(codec->codec_type) {
948 case CODEC_TYPE_AUDIO:
949 codec->sample_rate = icodec->sample_rate;
950 codec->channels = icodec->channels;
952 case CODEC_TYPE_VIDEO:
953 codec->frame_rate = icodec->frame_rate;
954 codec->frame_rate_base = icodec->frame_rate_base;
955 codec->width = icodec->width;
956 codec->height = icodec->height;
962 switch(codec->codec_type) {
963 case CODEC_TYPE_AUDIO:
964 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
967 if (codec->channels == icodec->channels &&
968 codec->sample_rate == icodec->sample_rate) {
969 ost->audio_resample = 0;
971 if (codec->channels != icodec->channels &&
972 icodec->codec_id == CODEC_ID_AC3) {
973 /* Special case for 5:1 AC3 input */
974 /* and mono or stereo output */
975 /* Request specific number of channels */
976 icodec->channels = codec->channels;
977 if (codec->sample_rate == icodec->sample_rate)
978 ost->audio_resample = 0;
980 ost->audio_resample = 1;
981 ost->resample = audio_resample_init(codec->channels, icodec->channels,
983 icodec->sample_rate);
986 printf("Can't resample. Aborting.\n");
990 /* Request specific number of channels */
991 icodec->channels = codec->channels;
993 ost->audio_resample = 1;
994 ost->resample = audio_resample_init(codec->channels, icodec->channels,
996 icodec->sample_rate);
999 printf("Can't resample. Aborting.\n");
1004 ist->decoding_needed = 1;
1005 ost->encoding_needed = 1;
1007 case CODEC_TYPE_VIDEO:
1008 if (codec->width == icodec->width &&
1009 codec->height == icodec->height &&
1010 frame_topBand == 0 &&
1011 frame_bottomBand == 0 &&
1012 frame_leftBand == 0 &&
1013 frame_rightBand == 0)
1015 ost->video_resample = 0;
1016 ost->video_crop = 0;
1017 } else if ((codec->width == icodec->width -
1018 (frame_leftBand + frame_rightBand)) &&
1019 (codec->height == icodec->height -
1020 (frame_topBand + frame_bottomBand)))
1022 ost->video_resample = 0;
1023 ost->video_crop = 1;
1024 ost->topBand = frame_topBand;
1025 ost->leftBand = frame_leftBand;
1028 ost->video_resample = 1;
1029 ost->video_crop = 0; // cropping is handled as part of resample
1030 buf = av_malloc((codec->width * codec->height * 3) / 2);
1033 ost->pict_tmp.data[0] = buf;
1034 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1035 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1036 ost->pict_tmp.linesize[0] = codec->width;
1037 ost->pict_tmp.linesize[1] = codec->width / 2;
1038 ost->pict_tmp.linesize[2] = codec->width / 2;
1040 ost->img_resample_ctx = img_resample_full_init(
1041 ost->st->codec.width, ost->st->codec.height,
1042 ist->st->codec.width, ist->st->codec.height,
1043 frame_topBand, frame_bottomBand,
1044 frame_leftBand, frame_rightBand);
1046 ost->encoding_needed = 1;
1047 ist->decoding_needed = 1;
1053 if (ost->encoding_needed &&
1054 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1055 char logfilename[1024];
1060 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1062 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1063 if (codec->flags & CODEC_FLAG_PASS1) {
1064 f = fopen(logfilename, "w");
1066 perror(logfilename);
1071 /* read the log file */
1072 f = fopen(logfilename, "r");
1074 perror(logfilename);
1077 fseek(f, 0, SEEK_END);
1079 fseek(f, 0, SEEK_SET);
1080 logbuffer = av_malloc(size + 1);
1082 fprintf(stderr, "Could not allocate log buffer\n");
1085 fread(logbuffer, 1, size, f);
1087 logbuffer[size] = '\0';
1088 codec->stats_in = logbuffer;
1094 /* dump the file output parameters - cannot be done before in case
1096 for(i=0;i<nb_output_files;i++) {
1097 dump_format(output_files[i], i, output_files[i]->filename, 1);
1100 /* dump the stream mapping */
1101 fprintf(stderr, "Stream mapping:\n");
1102 for(i=0;i<nb_ostreams;i++) {
1104 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1105 ist_table[ost->source_index]->file_index,
1106 ist_table[ost->source_index]->index,
1111 /* open each encoder */
1112 for(i=0;i<nb_ostreams;i++) {
1114 if (ost->encoding_needed) {
1116 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1118 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1119 ost->file_index, ost->index);
1122 if (avcodec_open(&ost->st->codec, codec) < 0) {
1123 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1124 ost->file_index, ost->index);
1130 /* open each decoder */
1131 for(i=0;i<nb_istreams;i++) {
1133 if (ist->decoding_needed) {
1135 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1137 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1138 ist->st->codec.codec_id, ist->file_index, ist->index);
1141 if (avcodec_open(&ist->st->codec, codec) < 0) {
1142 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1143 ist->file_index, ist->index);
1146 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1147 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1152 for(i=0;i<nb_istreams;i++) {
1154 is = input_files[ist->file_index];
1159 /* compute buffer size max (should use a complete heuristic) */
1160 for(i=0;i<nb_input_files;i++) {
1161 file_table[i].buffer_size_max = 2048;
1164 /* open files and write file headers */
1165 for(i=0;i<nb_output_files;i++) {
1166 os = output_files[i];
1167 if (av_write_header(os) < 0) {
1168 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1174 #ifndef CONFIG_WIN32
1176 fprintf(stderr, "Press [q] to stop encoding\n");
1183 for(; received_sigterm == 0;) {
1184 int file_index, ist_index;
1189 int data_size, got_picture;
1191 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1192 void *buffer_to_free;
1196 /* if 'q' pressed, exits */
1198 /* read_key() returns 0 on EOF */
1204 /* select the stream that we must read now by looking at the
1205 smallest output pts */
1208 for(i=0;i<nb_ostreams;i++) {
1211 os = output_files[ost->file_index];
1212 ist = ist_table[ost->source_index];
1213 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1214 if (!file_table[ist->file_index].eof_reached &&
1217 file_index = ist->file_index;
1220 /* if none, if is finished */
1221 if (file_index < 0) {
1225 /* finish if recording time exhausted */
1226 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1229 /* read a frame from it and output it in the fifo */
1230 is = input_files[file_index];
1231 if (av_read_frame(is, &pkt) < 0) {
1232 file_table[file_index].eof_reached = 1;
1236 stream_no_data = is;
1241 av_pkt_dump(stdout, &pkt, do_hex_dump);
1243 /* the following test is needed in case new streams appear
1244 dynamically in stream : we ignore them */
1245 if (pkt.stream_index >= file_table[file_index].nb_streams)
1246 goto discard_packet;
1247 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1248 ist = ist_table[ist_index];
1250 goto discard_packet;
1252 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1254 if (pkt.pts != AV_NOPTS_VALUE) {
1257 ist->pts = ist->next_pts;
1263 /* decode the packet if needed */
1264 data_buf = NULL; /* fail safe */
1266 if (ist->decoding_needed) {
1267 switch(ist->st->codec.codec_type) {
1268 case CODEC_TYPE_AUDIO:
1269 /* XXX: could avoid copy if PCM 16 bits with same
1270 endianness as CPU */
1271 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1277 /* Some bug in mpeg audio decoder gives */
1278 /* data_size < 0, it seems they are overflows */
1279 if (data_size <= 0) {
1280 /* no audio frame */
1283 data_buf = (uint8_t *)samples;
1284 ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) /
1285 (2 * ist->st->codec.channels);
1287 case CODEC_TYPE_VIDEO:
1289 AVFrame big_picture;
1291 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1292 ret = avcodec_decode_video(&ist->st->codec,
1293 &big_picture, &got_picture, ptr, len);
1294 picture= *(AVPicture*)&big_picture;
1295 ist->st->quality= big_picture.quality;
1298 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1299 ist->file_index, ist->index);
1300 av_free_packet(&pkt);
1304 /* no picture yet */
1305 goto discard_packet;
1307 if (ist->st->codec.frame_rate_base != 0) {
1308 ist->next_pts += ((int64_t)AV_TIME_BASE *
1309 ist->st->codec.frame_rate_base) /
1310 ist->st->codec.frame_rate;
1325 buffer_to_free = NULL;
1326 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1327 pre_process_video_frame(ist, &picture, &buffer_to_free);
1330 /* frame rate emulation */
1331 if (ist->st->codec.rate_emu) {
1332 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1333 int64_t now = av_gettime() - ist->start;
1341 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1342 is the one of the next displayed one */
1343 /* XXX: add mpeg4 too ? */
1344 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1345 if (ist->st->codec.pict_type != B_TYPE) {
1347 tmp = ist->last_ip_pts;
1348 ist->last_ip_pts = ist->frac_pts.val;
1349 ist->frac_pts.val = tmp;
1353 /* if output time reached then transcode raw format,
1354 encode packets and output them */
1355 if (start_time == 0 || ist->pts >= start_time)
1356 for(i=0;i<nb_ostreams;i++) {
1360 if (ost->source_index == ist_index) {
1361 os = output_files[ost->file_index];
1364 printf("%d: got pts=%0.3f %0.3f\n", i,
1365 (double)pkt.pts / AV_TIME_BASE,
1366 ((double)ist->pts / AV_TIME_BASE) -
1367 ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1369 /* set the input output pts pairs */
1370 ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1371 /* XXX: take into account the various fifos,
1372 in particular for audio */
1373 ost->sync_opts = ost->st->pts.val;
1374 //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ist->pts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
1376 if (ost->encoding_needed) {
1377 switch(ost->st->codec.codec_type) {
1378 case CODEC_TYPE_AUDIO:
1379 do_audio_out(os, ost, ist, data_buf, data_size);
1381 case CODEC_TYPE_VIDEO:
1382 /* find an audio stream for synchro */
1385 AVOutputStream *audio_sync, *ost1;
1387 for(i=0;i<nb_ostreams;i++) {
1388 ost1 = ost_table[i];
1389 if (ost1->file_index == ost->file_index &&
1390 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1396 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1397 if (do_vstats && frame_size)
1398 do_video_stats(os, ost, frame_size);
1407 /* no reencoding needed : output the packet directly */
1408 /* force the input stream PTS */
1410 memset(&avframe, 0, sizeof(AVFrame));
1411 ost->st->codec.coded_frame= &avframe;
1412 avframe.key_frame = pkt.flags & PKT_FLAG_KEY;
1414 av_write_frame(os, ost->index, data_buf, data_size);
1415 ost->st->codec.frame_number++;
1416 ost->frame_number++;
1420 av_free(buffer_to_free);
1423 av_free_packet(&pkt);
1425 /* dump report by using the output first video and audio streams */
1426 print_report(output_files, ost_table, nb_ostreams, 0);
1430 /* dump report by using the first video and audio streams */
1431 print_report(output_files, ost_table, nb_ostreams, 1);
1433 /* close each encoder */
1434 for(i=0;i<nb_ostreams;i++) {
1436 if (ost->encoding_needed) {
1437 av_freep(&ost->st->codec.stats_in);
1438 avcodec_close(&ost->st->codec);
1442 /* close each decoder */
1443 for(i=0;i<nb_istreams;i++) {
1445 if (ist->decoding_needed) {
1446 avcodec_close(&ist->st->codec);
1451 /* write the trailer if needed and close file */
1452 for(i=0;i<nb_output_files;i++) {
1453 os = output_files[i];
1454 av_write_trailer(os);
1460 av_free(file_table);
1463 for(i=0;i<nb_istreams;i++) {
1470 for(i=0;i<nb_ostreams;i++) {
1474 fclose(ost->logfile);
1475 ost->logfile = NULL;
1477 fifo_free(&ost->fifo); /* works even if fifo is not
1478 initialized but set to zero */
1479 av_free(ost->pict_tmp.data[0]);
1480 if (ost->video_resample)
1481 img_resample_close(ost->img_resample_ctx);
1482 if (ost->audio_resample)
1483 audio_resample_close(ost->resample);
1496 int file_read(const char *filename)
1499 unsigned char buffer[1024];
1502 if (url_open(&h, filename, O_RDONLY) < 0) {
1503 printf("could not open '%s'\n", filename);
1507 len = url_read(h, buffer, sizeof(buffer));
1510 for(i=0;i<len;i++) putchar(buffer[i]);
1517 static void opt_image_format(const char *arg)
1521 for(f = first_image_format; f != NULL; f = f->next) {
1522 if (!strcmp(arg, f->name))
1526 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1532 static void opt_format(const char *arg)
1534 /* compatibility stuff for pgmyuv */
1535 if (!strcmp(arg, "pgmyuv")) {
1536 opt_image_format(arg);
1540 file_iformat = av_find_input_format(arg);
1541 file_oformat = guess_format(arg, NULL, NULL);
1542 if (!file_iformat && !file_oformat) {
1543 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1548 static void opt_video_bitrate(const char *arg)
1550 video_bit_rate = atoi(arg) * 1000;
1553 static void opt_video_bitrate_tolerance(const char *arg)
1555 video_bit_rate_tolerance = atoi(arg) * 1000;
1558 static void opt_video_bitrate_max(const char *arg)
1560 video_rc_max_rate = atoi(arg) * 1000;
1563 static void opt_video_bitrate_min(const char *arg)
1565 video_rc_min_rate = atoi(arg) * 1000;
1568 static void opt_video_buffer_size(const char *arg)
1570 video_rc_buffer_size = atoi(arg) * 1000;
1573 static void opt_video_rc_eq(char *arg)
1578 static void opt_video_rc_override_string(char *arg)
1580 video_rc_override_string = arg;
1584 static void opt_workaround_bugs(const char *arg)
1586 workaround_bugs = atoi(arg);
1589 static void opt_dct_algo(const char *arg)
1591 dct_algo = atoi(arg);
1594 static void opt_idct_algo(const char *arg)
1596 idct_algo = atoi(arg);
1600 static void opt_error_resilience(const char *arg)
1602 error_resilience = atoi(arg);
1605 static void opt_error_concealment(const char *arg)
1607 error_concealment = atoi(arg);
1610 static void opt_debug(const char *arg)
1615 static void opt_verbose(const char *arg)
1617 verbose = atoi(arg);
1620 static void opt_frame_rate(const char *arg)
1622 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1623 fprintf(stderr, "Incorrect frame rate\n");
1628 static void opt_frame_crop_top(const char *arg)
1630 frame_topBand = atoi(arg);
1631 if (frame_topBand < 0) {
1632 fprintf(stderr, "Incorrect top crop size\n");
1635 if ((frame_topBand % 2) != 0) {
1636 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1639 if ((frame_topBand) >= frame_height){
1640 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1643 frame_height -= frame_topBand;
1646 static void opt_frame_crop_bottom(const char *arg)
1648 frame_bottomBand = atoi(arg);
1649 if (frame_bottomBand < 0) {
1650 fprintf(stderr, "Incorrect bottom crop size\n");
1653 if ((frame_bottomBand % 2) != 0) {
1654 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1657 if ((frame_bottomBand) >= frame_height){
1658 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1661 frame_height -= frame_bottomBand;
1664 static void opt_frame_crop_left(const char *arg)
1666 frame_leftBand = atoi(arg);
1667 if (frame_leftBand < 0) {
1668 fprintf(stderr, "Incorrect left crop size\n");
1671 if ((frame_leftBand % 2) != 0) {
1672 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1675 if ((frame_leftBand) >= frame_width){
1676 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1679 frame_width -= frame_leftBand;
1682 static void opt_frame_crop_right(const char *arg)
1684 frame_rightBand = atoi(arg);
1685 if (frame_rightBand < 0) {
1686 fprintf(stderr, "Incorrect right crop size\n");
1689 if ((frame_rightBand % 2) != 0) {
1690 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1693 if ((frame_rightBand) >= frame_width){
1694 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1697 frame_width -= frame_rightBand;
1700 static void opt_frame_size(const char *arg)
1702 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1703 fprintf(stderr, "Incorrect frame size\n");
1706 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1707 fprintf(stderr, "Frame size must be a multiple of 2\n");
1712 static void opt_frame_pix_fmt(const char *arg)
1714 frame_pix_fmt = avcodec_get_pix_fmt(arg);
1717 static void opt_frame_aspect_ratio(const char *arg)
1723 p = strchr(arg, ':');
1725 x = strtol(arg, (char **)&arg, 10);
1727 y = strtol(arg+1, (char **)&arg, 10);
1729 ar = (double)x / (double)y;
1731 ar = strtod(arg, (char **)&arg);
1734 fprintf(stderr, "Incorrect aspect ratio specification.\n");
1737 frame_aspect_ratio = ar;
1740 static void opt_gop_size(const char *arg)
1742 gop_size = atoi(arg);
1745 static void opt_b_frames(const char *arg)
1747 b_frames = atoi(arg);
1748 if (b_frames > FF_MAX_B_FRAMES) {
1749 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1751 } else if (b_frames < 1) {
1752 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1757 static void opt_mb_decision(const char *arg)
1759 mb_decision = atoi(arg);
1762 static void opt_qscale(const char *arg)
1764 video_qscale = atof(arg);
1765 if (video_qscale < 0.01 ||
1766 video_qscale > 255) {
1767 fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1772 static void opt_qmin(const char *arg)
1774 video_qmin = atoi(arg);
1775 if (video_qmin < 0 ||
1777 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1782 static void opt_qmax(const char *arg)
1784 video_qmax = atoi(arg);
1785 if (video_qmax < 0 ||
1787 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1792 static void opt_mb_qmin(const char *arg)
1794 video_mb_qmin = atoi(arg);
1795 if (video_mb_qmin < 0 ||
1796 video_mb_qmin > 31) {
1797 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1802 static void opt_mb_qmax(const char *arg)
1804 video_mb_qmax = atoi(arg);
1805 if (video_mb_qmax < 0 ||
1806 video_mb_qmax > 31) {
1807 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1812 static void opt_qdiff(const char *arg)
1814 video_qdiff = atoi(arg);
1815 if (video_qdiff < 0 ||
1817 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1822 static void opt_qblur(const char *arg)
1824 video_qblur = atof(arg);
1827 static void opt_qcomp(const char *arg)
1829 video_qcomp = atof(arg);
1832 static void opt_rc_initial_cplx(const char *arg)
1834 video_rc_initial_cplx = atof(arg);
1836 static void opt_b_qfactor(const char *arg)
1838 video_b_qfactor = atof(arg);
1840 static void opt_i_qfactor(const char *arg)
1842 video_i_qfactor = atof(arg);
1844 static void opt_b_qoffset(const char *arg)
1846 video_b_qoffset = atof(arg);
1848 static void opt_i_qoffset(const char *arg)
1850 video_i_qoffset = atof(arg);
1853 static void opt_packet_size(const char *arg)
1855 packet_size= atoi(arg);
1858 static void opt_strict(const char *arg)
1863 static void opt_audio_bitrate(const char *arg)
1865 audio_bit_rate = atoi(arg) * 1000;
1868 static void opt_audio_rate(const char *arg)
1870 audio_sample_rate = atoi(arg);
1873 static void opt_audio_channels(const char *arg)
1875 audio_channels = atoi(arg);
1878 static void opt_video_device(const char *arg)
1880 video_device = av_strdup(arg);
1883 static void opt_video_channel(const char *arg)
1885 video_channel = strtol(arg, NULL, 0);
1888 static void opt_video_standard(const char *arg)
1890 video_standard = av_strdup(arg);
1893 static void opt_audio_device(const char *arg)
1895 audio_device = av_strdup(arg);
1898 static void opt_dv1394(const char *arg)
1900 video_grab_format = "dv1394";
1901 audio_grab_format = NULL;
1904 static void opt_audio_codec(const char *arg)
1908 if (!strcmp(arg, "copy")) {
1909 audio_stream_copy = 1;
1913 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1918 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1921 audio_codec_id = p->id;
1926 static void add_frame_hooker(const char *arg)
1931 char *args = av_strdup(arg);
1935 argv[0] = strtok(args, " ");
1936 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1939 i = frame_hook_add(argc, argv);
1942 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1947 const char *motion_str[] = {
1957 static void opt_motion_estimation(const char *arg)
1963 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1966 if (!strcmp(*p, arg))
1970 me_method = (p - motion_str) + 1;
1973 static void opt_video_codec(const char *arg)
1977 if (!strcmp(arg, "copy")) {
1978 video_stream_copy = 1;
1982 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1987 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1990 video_codec_id = p->id;
1995 static void opt_map(const char *arg)
2001 m = &stream_maps[nb_stream_maps++];
2003 m->file_index = strtol(arg, (char **)&p, 0);
2007 m->stream_index = strtol(p, (char **)&p, 0);
2010 static void opt_recording_time(const char *arg)
2012 recording_time = parse_date(arg, 1);
2015 static void opt_start_time(const char *arg)
2017 start_time = parse_date(arg, 1);
2020 static void opt_input_file(const char *filename)
2022 AVFormatContext *ic;
2023 AVFormatParameters params, *ap = ¶ms;
2024 int err, i, ret, rfps, rfps_base;
2026 if (!strcmp(filename, "-"))
2029 using_stdin |= !strcmp(filename, "pipe:" ) ||
2030 !strcmp( filename, "/dev/stdin" );
2032 /* get default parameters from command line */
2033 memset(ap, 0, sizeof(*ap));
2034 ap->sample_rate = audio_sample_rate;
2035 ap->channels = audio_channels;
2036 ap->frame_rate = frame_rate;
2037 ap->frame_rate_base = frame_rate_base;
2038 ap->width = frame_width;
2039 ap->height = frame_height;
2040 ap->image_format = image_format;
2041 ap->pix_fmt = frame_pix_fmt;
2043 /* open the input file with generic libav function */
2044 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2046 print_error(filename, err);
2050 /* If not enough info to get the stream parameters, we decode the
2051 first frames to get it. (used in mpeg case for example) */
2052 ret = av_find_stream_info(ic);
2054 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2058 /* if seeking requested, we execute it */
2059 if (start_time != 0) {
2062 timestamp = start_time;
2063 /* add the stream start time */
2064 if (ic->start_time != AV_NOPTS_VALUE)
2065 timestamp += ic->start_time;
2066 ret = av_seek_frame(ic, -1, timestamp);
2068 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2069 filename, (double)timestamp / AV_TIME_BASE);
2071 /* reset seek info */
2075 /* update the current parameters so that they match the one of the input stream */
2076 for(i=0;i<ic->nb_streams;i++) {
2077 AVCodecContext *enc = &ic->streams[i]->codec;
2078 switch(enc->codec_type) {
2079 case CODEC_TYPE_AUDIO:
2080 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2081 audio_channels = enc->channels;
2082 audio_sample_rate = enc->sample_rate;
2084 case CODEC_TYPE_VIDEO:
2085 frame_height = enc->height;
2086 frame_width = enc->width;
2087 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2088 frame_pix_fmt = enc->pix_fmt;
2089 rfps = ic->streams[i]->r_frame_rate;
2090 rfps_base = ic->streams[i]->r_frame_rate_base;
2091 enc->workaround_bugs = workaround_bugs;
2092 enc->error_resilience = error_resilience;
2093 enc->error_concealment = error_concealment;
2094 enc->idct_algo= idct_algo;
2097 enc->flags|= CODEC_FLAG_BITEXACT;
2099 assert(enc->frame_rate_base == rfps_base); // should be true for now
2100 if (enc->frame_rate != rfps) {
2101 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2102 i, (float)enc->frame_rate / enc->frame_rate_base,
2103 (float)rfps / rfps_base);
2105 /* update the current frame rate to match the stream frame rate */
2107 frame_rate_base = rfps_base;
2109 enc->rate_emu = rate_emu;
2111 case CODEC_TYPE_DATA:
2118 input_files[nb_input_files] = ic;
2119 /* dump the file content */
2120 dump_format(ic, nb_input_files, filename, 0);
2122 file_iformat = NULL;
2123 file_oformat = NULL;
2124 image_format = NULL;
2129 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2131 int has_video, has_audio, i, j;
2132 AVFormatContext *ic;
2136 for(j=0;j<nb_input_files;j++) {
2137 ic = input_files[j];
2138 for(i=0;i<ic->nb_streams;i++) {
2139 AVCodecContext *enc = &ic->streams[i]->codec;
2140 switch(enc->codec_type) {
2141 case CODEC_TYPE_AUDIO:
2144 case CODEC_TYPE_VIDEO:
2152 *has_video_ptr = has_video;
2153 *has_audio_ptr = has_audio;
2156 static void opt_output_file(const char *filename)
2159 AVFormatContext *oc;
2160 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2162 AVFormatParameters params, *ap = ¶ms;
2164 if (!strcmp(filename, "-"))
2167 oc = av_mallocz(sizeof(AVFormatContext));
2169 if (!file_oformat) {
2170 file_oformat = guess_format(NULL, filename, NULL);
2171 if (!file_oformat) {
2172 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2178 oc->oformat = file_oformat;
2180 if (!strcmp(file_oformat->name, "ffm") &&
2181 strstart(filename, "http:", NULL)) {
2182 /* special case for files sent to ffserver: we get the stream
2183 parameters from ffserver */
2184 if (read_ffserver_streams(oc, filename) < 0) {
2185 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2189 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2190 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2192 /* disable if no corresponding type found and at least one
2194 if (nb_input_files > 0) {
2195 check_audio_video_inputs(&input_has_video, &input_has_audio);
2196 if (!input_has_video)
2198 if (!input_has_audio)
2202 /* manual disable */
2203 if (audio_disable) {
2206 if (video_disable) {
2212 AVCodecContext *video_enc;
2214 st = av_mallocz(sizeof(AVStream));
2216 fprintf(stderr, "Could not alloc stream\n");
2219 avcodec_get_context_defaults(&st->codec);
2221 video_enc = &st->codec;
2223 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2224 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2225 if (video_stream_copy) {
2226 st->stream_copy = 1;
2227 video_enc->codec_type = CODEC_TYPE_VIDEO;
2232 codec_id = file_oformat->video_codec;
2233 if (video_codec_id != CODEC_ID_NONE)
2234 codec_id = video_codec_id;
2236 video_enc->codec_id = codec_id;
2238 video_enc->bit_rate = video_bit_rate;
2239 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2240 video_enc->frame_rate = frame_rate;
2241 video_enc->frame_rate_base = frame_rate_base;
2243 video_enc->width = frame_width;
2244 video_enc->height = frame_height;
2245 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2246 video_enc->pix_fmt = frame_pix_fmt;
2249 video_enc->gop_size = gop_size;
2251 video_enc->gop_size = 0;
2252 if (video_qscale || same_quality) {
2253 video_enc->flags |= CODEC_FLAG_QSCALE;
2254 st->quality = FF_QP2LAMBDA * video_qscale;
2258 video_enc->intra_matrix = intra_matrix;
2260 video_enc->inter_matrix = inter_matrix;
2263 video_enc->flags |= CODEC_FLAG_BITEXACT;
2265 video_enc->mb_decision = mb_decision;
2268 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2271 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2274 video_enc->flags |= CODEC_FLAG_H263P_AIV;
2277 video_enc->flags |= CODEC_FLAG_4MV;
2280 video_enc->flags |= CODEC_FLAG_OBMC;
2284 video_enc->flags |= CODEC_FLAG_PART;
2287 video_enc->max_b_frames = b_frames;
2288 video_enc->b_frame_strategy = 0;
2289 video_enc->b_quant_factor = 2.0;
2292 video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2294 video_enc->qmin = video_qmin;
2295 video_enc->qmax = video_qmax;
2296 video_enc->mb_qmin = video_mb_qmin;
2297 video_enc->mb_qmax = video_mb_qmax;
2298 video_enc->max_qdiff = video_qdiff;
2299 video_enc->qblur = video_qblur;
2300 video_enc->qcompress = video_qcomp;
2301 video_enc->rc_eq = video_rc_eq;
2302 video_enc->debug= debug;
2304 p= video_rc_override_string;
2307 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2309 fprintf(stderr, "error parsing rc_override\n");
2312 video_enc->rc_override=
2313 av_realloc(video_enc->rc_override,
2314 sizeof(RcOverride)*(i+1));
2315 video_enc->rc_override[i].start_frame= start;
2316 video_enc->rc_override[i].end_frame = end;
2318 video_enc->rc_override[i].qscale= q;
2319 video_enc->rc_override[i].quality_factor= 1.0;
2322 video_enc->rc_override[i].qscale= 0;
2323 video_enc->rc_override[i].quality_factor= -q/100.0;
2328 video_enc->rc_override_count=i;
2330 video_enc->rc_max_rate = video_rc_max_rate;
2331 video_enc->rc_min_rate = video_rc_min_rate;
2332 video_enc->rc_buffer_size = video_rc_buffer_size;
2333 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2334 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2335 video_enc->i_quant_factor = video_i_qfactor;
2336 video_enc->b_quant_factor = video_b_qfactor;
2337 video_enc->i_quant_offset = video_i_qoffset;
2338 video_enc->b_quant_offset = video_b_qoffset;
2339 video_enc->dct_algo = dct_algo;
2340 video_enc->idct_algo = idct_algo;
2341 video_enc->strict_std_compliance = strict;
2343 video_enc->rtp_mode= 1;
2344 video_enc->rtp_payload_size= packet_size;
2348 video_enc->flags|= CODEC_FLAG_PSNR;
2350 video_enc->me_method = me_method;
2355 video_enc->flags |= CODEC_FLAG_PASS1;
2357 video_enc->flags |= CODEC_FLAG_PASS2;
2361 oc->streams[nb_streams] = st;
2366 AVCodecContext *audio_enc;
2368 st = av_mallocz(sizeof(AVStream));
2370 fprintf(stderr, "Could not alloc stream\n");
2373 avcodec_get_context_defaults(&st->codec);
2375 audio_enc = &st->codec;
2376 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2378 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2379 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2380 if (audio_stream_copy) {
2381 st->stream_copy = 1;
2383 codec_id = file_oformat->audio_codec;
2384 if (audio_codec_id != CODEC_ID_NONE)
2385 codec_id = audio_codec_id;
2386 audio_enc->codec_id = codec_id;
2388 audio_enc->bit_rate = audio_bit_rate;
2389 audio_enc->sample_rate = audio_sample_rate;
2390 /* For audio codecs other than AC3 we limit */
2391 /* the number of coded channels to stereo */
2392 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2393 audio_enc->channels = 2;
2395 audio_enc->channels = audio_channels;
2397 oc->streams[nb_streams] = st;
2401 oc->nb_streams = nb_streams;
2404 fprintf(stderr, "No audio or video streams available\n");
2409 pstrcpy(oc->title, sizeof(oc->title), str_title);
2411 pstrcpy(oc->author, sizeof(oc->author), str_author);
2413 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2415 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2418 output_files[nb_output_files++] = oc;
2420 strcpy(oc->filename, filename);
2422 /* check filename in case of an image number is expected */
2423 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2424 if (filename_number_test(oc->filename) < 0) {
2425 print_error(oc->filename, AVERROR_NUMEXPECTED);
2430 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2431 /* test if it already exists to avoid loosing precious files */
2432 if (!file_overwrite &&
2433 (strchr(filename, ':') == NULL ||
2434 strstart(filename, "file:", NULL))) {
2435 if (url_exist(filename)) {
2438 if ( !using_stdin ) {
2439 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2442 if (toupper(c) != 'Y') {
2443 fprintf(stderr, "Not overwriting - exiting\n");
2448 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2455 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2456 fprintf(stderr, "Could not open '%s'\n", filename);
2461 memset(ap, 0, sizeof(*ap));
2462 ap->image_format = image_format;
2463 if (av_set_parameters(oc, ap) < 0) {
2464 fprintf(stderr, "%s: Invalid encoding parameters\n",
2469 /* reset some options */
2470 file_oformat = NULL;
2471 file_iformat = NULL;
2472 image_format = NULL;
2475 audio_codec_id = CODEC_ID_NONE;
2476 video_codec_id = CODEC_ID_NONE;
2477 audio_stream_copy = 0;
2478 video_stream_copy = 0;
2481 /* prepare dummy protocols for grab */
2482 static void prepare_grab(void)
2484 int has_video, has_audio, i, j;
2485 AVFormatContext *oc;
2486 AVFormatContext *ic;
2487 AVFormatParameters vp1, *vp = &vp1;
2488 AVFormatParameters ap1, *ap = &ap1;
2490 /* see if audio/video inputs are needed */
2493 memset(ap, 0, sizeof(*ap));
2494 memset(vp, 0, sizeof(*vp));
2495 for(j=0;j<nb_output_files;j++) {
2496 oc = output_files[j];
2497 for(i=0;i<oc->nb_streams;i++) {
2498 AVCodecContext *enc = &oc->streams[i]->codec;
2499 switch(enc->codec_type) {
2500 case CODEC_TYPE_AUDIO:
2501 if (enc->sample_rate > ap->sample_rate)
2502 ap->sample_rate = enc->sample_rate;
2503 if (enc->channels > ap->channels)
2504 ap->channels = enc->channels;
2507 case CODEC_TYPE_VIDEO:
2508 if (enc->width > vp->width)
2509 vp->width = enc->width;
2510 if (enc->height > vp->height)
2511 vp->height = enc->height;
2513 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2514 if (enc->frame_rate > vp->frame_rate){
2515 vp->frame_rate = enc->frame_rate;
2516 vp->frame_rate_base = enc->frame_rate_base;
2526 if (has_video == 0 && has_audio == 0) {
2527 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2532 AVInputFormat *fmt1;
2533 fmt1 = av_find_input_format(video_grab_format);
2534 vp->device = video_device;
2535 vp->channel = video_channel;
2536 vp->standard = video_standard;
2537 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2538 fprintf(stderr, "Could not find video grab device\n");
2541 /* If not enough info to get the stream parameters, we decode the
2542 first frames to get it. */
2543 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2544 fprintf(stderr, "Could not find video grab parameters\n");
2547 /* by now video grab has one stream */
2548 ic->streams[0]->r_frame_rate = vp->frame_rate;
2549 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2550 input_files[nb_input_files] = ic;
2551 dump_format(ic, nb_input_files, "", 0);
2554 if (has_audio && audio_grab_format) {
2555 AVInputFormat *fmt1;
2556 fmt1 = av_find_input_format(audio_grab_format);
2557 ap->device = audio_device;
2558 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2559 fprintf(stderr, "Could not find audio grab device\n");
2562 input_files[nb_input_files] = ic;
2563 dump_format(ic, nb_input_files, "", 0);
2568 /* same option as mencoder */
2569 static void opt_pass(const char *pass_str)
2572 pass = atoi(pass_str);
2573 if (pass != 1 && pass != 2) {
2574 fprintf(stderr, "pass number can be only 1 or 2\n");
2580 #if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2581 static int64_t getutime(void)
2583 return av_gettime();
2586 static int64_t getutime(void)
2588 struct rusage rusage;
2590 getrusage(RUSAGE_SELF, &rusage);
2591 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2595 extern int ffm_nopts;
2597 static void opt_bitexact(void)
2600 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2604 static void show_formats(void)
2606 AVInputFormat *ifmt;
2607 AVOutputFormat *ofmt;
2608 AVImageFormat *image_fmt;
2613 printf("Output audio/video file formats:");
2614 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2615 printf(" %s", ofmt->name);
2619 printf("Input audio/video file formats:");
2620 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2621 printf(" %s", ifmt->name);
2625 printf("Output image formats:");
2626 for(image_fmt = first_image_format; image_fmt != NULL;
2627 image_fmt = image_fmt->next) {
2628 if (image_fmt->img_write)
2629 printf(" %s", image_fmt->name);
2633 printf("Input image formats:");
2634 for(image_fmt = first_image_format; image_fmt != NULL;
2635 image_fmt = image_fmt->next) {
2636 if (image_fmt->img_read)
2637 printf(" %s", image_fmt->name);
2641 printf("Codecs:\n");
2642 printf(" Encoders:");
2643 for(p = first_avcodec; p != NULL; p = p->next) {
2645 printf(" %s", p->name);
2649 printf(" Decoders:");
2650 for(p = first_avcodec; p != NULL; p = p->next) {
2652 printf(" %s", p->name);
2656 printf("Supported file protocols:");
2657 for(up = first_protocol; up != NULL; up = up->next)
2658 printf(" %s:", up->name);
2661 printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2662 printf("Motion estimation methods:");
2666 if ((pp - motion_str + 1) == ME_ZERO)
2667 printf("(fastest)");
2668 else if ((pp - motion_str + 1) == ME_FULL)
2669 printf("(slowest)");
2670 else if ((pp - motion_str + 1) == ME_EPZS)
2671 printf("(default)");
2678 void parse_matrix_coeffs(uint16_t *dest, const char *str)
2681 const char *p = str;
2688 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2695 void opt_inter_matrix(const char *arg)
2697 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2698 parse_matrix_coeffs(inter_matrix, arg);
2701 void opt_intra_matrix(const char *arg)
2703 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2704 parse_matrix_coeffs(intra_matrix, arg);
2707 static void opt_target(const char *arg)
2711 if(!strncmp(arg, "pal-", 4)) {
2714 } else if(!strncmp(arg, "ntsc-", 5)) {
2719 /* Calculate FR via float to avoid int overflow */
2720 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2723 } else if((fr == 29970) || (fr == 23976)) {
2726 /* Try to determine PAL/NTSC by peeking in the input files */
2727 if(nb_input_files) {
2729 for(j = 0; j < nb_input_files; j++) {
2730 for(i = 0; i < input_files[j]->nb_streams; i++) {
2731 AVCodecContext *c = &input_files[j]->streams[i]->codec;
2732 if(c->codec_type != CODEC_TYPE_VIDEO)
2734 fr = c->frame_rate * 1000 / c->frame_rate_base;
2738 } else if((fr == 29970) || (fr == 23976)) {
2748 if(verbose && norm >= 0)
2749 printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2753 fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2754 fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2755 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2759 if(!strcmp(arg, "vcd")) {
2761 opt_video_codec("mpeg1video");
2762 opt_audio_codec("mp2");
2765 opt_frame_size(norm ? "352x240" : "352x288");
2767 video_bit_rate = 1150000;
2768 video_rc_max_rate = 1150000;
2769 video_rc_min_rate = 1150000;
2771 audio_bit_rate = 224000;
2772 audio_sample_rate = 44100;
2774 } else if(!strcmp(arg, "svcd")) {
2776 opt_video_codec("mpeg2video");
2777 opt_audio_codec("mp2");
2780 opt_frame_size(norm ? "480x480" : "480x576");
2781 opt_gop_size(norm ? "18" : "15");
2783 video_bit_rate = 2040000;
2784 video_rc_max_rate = 2516000;
2785 video_rc_min_rate = 1145000;
2787 audio_bit_rate = 224000;
2788 audio_sample_rate = 44100;
2790 } else if(!strcmp(arg, "dvd")) {
2792 opt_video_codec("mpeg2video");
2793 opt_audio_codec("ac3");
2796 opt_frame_size(norm ? "720x480" : "720x576");
2797 opt_gop_size(norm ? "18" : "15");
2799 video_bit_rate = 6000000;
2800 video_rc_max_rate = 9000000;
2801 video_rc_min_rate = 1500000;
2803 audio_bit_rate = 448000;
2804 audio_sample_rate = 48000;
2807 fprintf(stderr, "Unknown target: %s\n", arg);
2812 const OptionDef options[] = {
2814 { "L", 0, {(void*)show_license}, "show license" },
2815 { "h", 0, {(void*)show_help}, "show help" },
2816 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2817 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2818 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2819 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2820 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2821 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2822 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2823 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2824 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2825 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2826 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2827 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2828 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2829 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2830 "add timings for benchmarking" },
2831 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
2832 "dump each input packet" },
2833 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2834 "when dumping packets, also dump the payload" },
2835 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2836 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2837 { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2838 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2839 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2842 { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2843 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2844 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2845 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2846 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2847 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2848 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2849 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2850 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2851 { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2852 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2853 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2854 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2855 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2856 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2857 { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2858 { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2859 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2860 { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2861 { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2862 { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2863 { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2864 { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2865 { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2866 { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2867 // { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2868 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2869 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2870 { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2871 { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2872 { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2873 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2874 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2875 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
2877 { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2878 { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2879 { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience", "n" },
2880 { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment", "bit_mask" },
2881 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2882 { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2883 { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2884 { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
2885 { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
2886 { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
2887 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2888 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2889 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2890 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
2891 "use same video quality as source (implies VBR)" },
2892 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2893 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2894 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
2895 "deinterlace pictures" },
2896 { "interlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace},
2897 "force interlacing support in encoder (MPEG2/MPEG4)" },
2898 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2899 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
2900 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2901 { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2902 { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
2903 { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2904 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
2905 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
2908 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2909 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2910 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2911 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2912 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2915 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2916 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2917 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2918 { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2919 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2923 static void show_banner(void)
2925 printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2928 static void show_license(void)
2932 "This library is free software; you can redistribute it and/or\n"
2933 "modify it under the terms of the GNU Lesser General Public\n"
2934 "License as published by the Free Software Foundation; either\n"
2935 "version 2 of the License, or (at your option) any later version.\n"
2937 "This library is distributed in the hope that it will be useful,\n"
2938 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2939 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
2940 "Lesser General Public License for more details.\n"
2942 "You should have received a copy of the GNU Lesser General Public\n"
2943 "License along with this library; if not, write to the Free Software\n"
2944 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
2949 static void show_help(void)
2952 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2953 "Hyper fast Audio and Video encoder\n");
2955 show_help_options(options, "Main options:\n",
2956 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
2957 show_help_options(options, "\nVideo options:\n",
2958 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2960 show_help_options(options, "\nAdvanced Video options:\n",
2961 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2962 OPT_VIDEO | OPT_EXPERT);
2963 show_help_options(options, "\nAudio options:\n",
2964 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2966 show_help_options(options, "\nAdvanced Audio options:\n",
2967 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2968 OPT_AUDIO | OPT_EXPERT);
2969 show_help_options(options, "\nAudio/Video grab options:\n",
2972 show_help_options(options, "\nAdvanced options:\n",
2973 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2978 void parse_arg_file(const char *filename)
2980 opt_output_file(filename);
2983 int main(int argc, char **argv)
2994 parse_options(argc, argv, options);
2996 /* file converter / grab */
2997 if (nb_output_files <= 0) {
2998 fprintf(stderr, "Must supply at least one output file\n");
3002 if (nb_input_files == 0) {
3007 av_encode(output_files, nb_output_files, input_files, nb_input_files,
3008 stream_maps, nb_stream_maps);
3009 ti = getutime() - ti;
3011 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3015 for(i=0;i<nb_output_files;i++) {
3016 /* maybe av_close_output_file ??? */
3017 AVFormatContext *s = output_files[i];
3019 if (!(s->oformat->flags & AVFMT_NOFILE))
3021 for(j=0;j<s->nb_streams;j++)
3022 av_free(s->streams[j]);
3025 for(i=0;i<nb_input_files;i++)
3026 av_close_input_file(input_files[i]);
3031 av_free(intra_matrix);
3033 av_free(inter_matrix);
3035 #ifdef POWERPC_PERFORMANCE_REPORT
3036 extern void powerpc_display_perf_report(void);
3037 powerpc_display_perf_report();
3038 #endif /* POWERPC_PERFORMANCE_REPORT */
3040 #ifndef CONFIG_WIN32
3041 if (received_sigterm) {
3043 "Received signal %d: terminating.\n",
3044 (int) received_sigterm);
3048 exit(0); /* not all OS-es handle main() return value */