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_aic = 0;
116 static int use_umv = 0;
117 static int do_deinterlace = 0;
118 static int workaround_bugs = FF_BUG_AUTODETECT;
119 static int error_resilience = 2;
120 static int error_concealment = 3;
121 static int dct_algo = 0;
122 static int idct_algo = 0;
123 static int use_part = 0;
124 static int packet_size = 0;
125 static int strict = 0;
126 static int debug = 0;
127 extern int loop_input; /* currently a hack */
129 static int gop_size = 12;
130 static int intra_only = 0;
131 static int audio_sample_rate = 44100;
132 static int audio_bit_rate = 64000;
133 static int audio_disable = 0;
134 static int audio_channels = 1;
135 static int audio_codec_id = CODEC_ID_NONE;
137 static int64_t recording_time = 0;
138 static int64_t start_time = 0;
139 static int file_overwrite = 0;
140 static char *str_title = NULL;
141 static char *str_author = NULL;
142 static char *str_copyright = NULL;
143 static char *str_comment = NULL;
144 static int do_benchmark = 0;
145 static int do_hex_dump = 0;
146 static int do_pkt_dump = 0;
147 static int do_psnr = 0;
148 static int do_vstats = 0;
149 static int do_pass = 0;
150 static int bitexact = 0;
151 static char *pass_logfilename = NULL;
152 static int audio_stream_copy = 0;
153 static int video_stream_copy = 0;
155 static int rate_emu = 0;
157 static char *video_grab_format = "video4linux";
158 static char *video_device = NULL;
159 static int video_channel = 0;
160 static char *video_standard = "ntsc";
162 static char *audio_grab_format = "audio_device";
163 static char *audio_device = NULL;
165 static int using_stdin = 0;
166 static int using_vhook = 0;
167 static int verbose = 1;
169 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
171 typedef struct AVOutputStream {
172 int file_index; /* file index */
173 int index; /* stream index in the output file */
174 int source_index; /* AVInputStream index */
175 AVStream *st; /* stream in the output file */
176 int encoding_needed; /* true if encoding needed for this stream */
178 /* input pts and corresponding output pts
181 double sync_ipts_offset;
184 int video_resample; /* video_resample and video_crop are mutually exclusive */
185 AVPicture pict_tmp; /* temporary image for resampling */
186 ImgReSampleContext *img_resample_ctx; /* for image resampling */
188 int video_crop; /* video_resample and video_crop are mutually exclusive */
189 int topBand; /* cropping area sizes */
194 ReSampleContext *resample; /* for audio resampling */
195 FifoBuffer fifo; /* for compression: one audio fifo per codec */
199 typedef struct AVInputStream {
203 int discard; /* true if stream data should be discarded */
204 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
205 int64_t sample_index; /* current sample */
207 int64_t start; /* time when read started */
208 unsigned long frame; /* current frame */
209 int64_t next_pts; /* synthetic pts for cases where pkt.pts
211 int64_t pts; /* current pts */
214 typedef struct AVInputFile {
215 int eof_reached; /* true if eof reached */
216 int ist_index; /* index of first stream in ist_table */
217 int buffer_size; /* current total buffer size */
218 int buffer_size_max; /* buffer size at which we consider we can stop
220 int nb_streams; /* nb streams we are aware of */
225 /* init terminal so that we can grab keys */
226 static struct termios oldtty;
228 static void term_exit(void)
230 tcsetattr (0, TCSANOW, &oldtty);
233 static volatile sig_atomic_t received_sigterm = 0;
236 sigterm_handler(int sig)
238 received_sigterm = sig;
242 static void term_init(void)
249 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
250 |INLCR|IGNCR|ICRNL|IXON);
251 tty.c_oflag |= OPOST;
252 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
253 tty.c_cflag &= ~(CSIZE|PARENB);
258 tcsetattr (0, TCSANOW, &tty);
260 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
261 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
262 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
264 register a function to be called at normal program termination
267 #ifdef CONFIG_BEOS_NETSERVER
268 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
272 /* read a key without blocking */
273 static int read_key(void)
277 #ifndef CONFIG_BEOS_NETSERVER
285 n = select(1, &rfds, NULL, NULL, &tv);
299 static volatile int received_sigterm = 0;
301 /* no interactive support */
302 static void term_exit(void)
306 static void term_init(void)
310 static int read_key(void)
317 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
322 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
325 /* copy stream format */
326 s->nb_streams = ic->nb_streams;
327 for(i=0;i<ic->nb_streams;i++) {
330 st = av_mallocz(sizeof(AVStream));
331 memcpy(st, ic->streams[i], sizeof(AVStream));
335 av_close_input_file(ic);
339 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
341 static void do_audio_out(AVFormatContext *s,
344 unsigned char *buf, int size)
347 static uint8_t *audio_buf = NULL;
348 static uint8_t *audio_out = NULL;
349 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
351 int size_out, frame_bytes, ret;
354 /* SC: dynamic allocation of buffers */
356 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
358 audio_out = av_malloc(audio_out_size);
359 if (!audio_buf || !audio_out)
360 return; /* Should signal an error ! */
363 enc = &ost->st->codec;
365 if (ost->audio_resample) {
367 size_out = audio_resample(ost->resample,
368 (short *)buftmp, (short *)buf,
369 size / (ist->st->codec.channels * 2));
370 size_out = size_out * enc->channels * 2;
376 /* now encode as many frames as possible */
377 if (enc->frame_size > 1) {
378 /* output resampled raw samples */
379 fifo_write(&ost->fifo, buftmp, size_out,
382 frame_bytes = enc->frame_size * 2 * enc->channels;
384 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
385 &ost->fifo.rptr) == 0) {
386 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
388 av_write_frame(s, ost->index, audio_out, ret);
391 /* output a pcm frame */
392 /* XXX: change encoding codec API to avoid this ? */
393 switch(enc->codec->id) {
394 case CODEC_ID_PCM_S16LE:
395 case CODEC_ID_PCM_S16BE:
396 case CODEC_ID_PCM_U16LE:
397 case CODEC_ID_PCM_U16BE:
400 size_out = size_out >> 1;
403 ret = avcodec_encode_audio(enc, audio_out, size_out,
405 av_write_frame(s, ost->index, audio_out, ret);
409 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
413 AVPicture picture_tmp;
416 dec = &ist->st->codec;
418 /* deinterlace : must be done before any resize */
419 if (do_deinterlace || using_vhook) {
422 /* create temporary picture */
423 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
424 buf = av_malloc(size);
428 picture2 = &picture_tmp;
429 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
432 if(avpicture_deinterlace(picture2, picture,
433 dec->pix_fmt, dec->width, dec->height) < 0) {
434 /* if error, do not deinterlace */
440 if (img_convert(picture2, dec->pix_fmt, picture,
441 dec->pix_fmt, dec->width, dec->height) < 0) {
442 /* if error, do not copy */
452 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
454 if (picture != picture2)
455 *picture = *picture2;
459 /* we begin to correct av delay at this threshold */
460 #define AV_DELAY_MAX 0.100
462 static void do_video_out(AVFormatContext *s,
465 AVPicture *in_picture,
466 int *frame_size, AVOutputStream *audio_sync)
468 int nb_frames, i, ret;
469 AVPicture *final_picture, *formatted_picture;
470 AVPicture picture_format_temp, picture_crop_temp;
471 static uint8_t *video_buffer;
472 uint8_t *buf = NULL, *buf1 = NULL;
473 AVCodecContext *enc, *dec;
474 enum PixelFormat target_pixfmt;
476 #define VIDEO_BUFFER_SIZE (1024*1024)
478 enc = &ost->st->codec;
479 dec = &ist->st->codec;
481 /* by default, we output a single frame */
486 /* NOTE: the A/V sync is always done by considering the audio is
487 the master clock. It is suffisant for transcoding or playing,
488 but not for the general case */
490 /* compute the A-V delay and duplicate/remove frames if needed */
491 double adelta, vdelta, av_delay;
493 adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts *
494 s->pts_num / s->pts_den);
496 vdelta = ost->sync_ipts - ((double)ost->sync_opts *
497 s->pts_num / s->pts_den);
499 av_delay = adelta - vdelta;
500 // printf("delay=%f\n", av_delay);
501 if (av_delay < -AV_DELAY_MAX)
503 else if (av_delay > AV_DELAY_MAX)
508 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
509 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
510 if (vdelta < -AV_DELAY_MAX)
512 else if (vdelta > AV_DELAY_MAX)
515 ost->sync_ipts_offset -= vdelta;
516 if (!ost->sync_ipts_offset)
517 ost->sync_ipts_offset = 0.000001; /* one microsecond */
521 #if defined(AVSYNC_DEBUG)
523 static char *action[] = { "drop frame", "copy frame", "dup frame" };
525 fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
526 (double) audio_sync->sync_ipts,
527 (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
528 fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
529 (double) ost->sync_ipts,
530 (double) ost->st->pts.val * s->pts_num / s->pts_den,
539 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
543 /* convert pixel format if needed */
544 target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
545 if (dec->pix_fmt != target_pixfmt) {
548 /* create temporary picture */
549 size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
550 buf = av_malloc(size);
553 formatted_picture = &picture_format_temp;
554 avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
556 if (img_convert(formatted_picture, target_pixfmt,
557 in_picture, dec->pix_fmt,
558 dec->width, dec->height) < 0) {
559 fprintf(stderr, "pixel format conversion not handled\n");
563 formatted_picture = in_picture;
566 /* XXX: resampling could be done before raw format convertion in
567 some cases to go faster */
568 /* XXX: only works for YUV420P */
569 if (ost->video_resample) {
570 final_picture = &ost->pict_tmp;
571 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
572 if (enc->pix_fmt != PIX_FMT_YUV420P) {
576 /* create temporary picture */
577 size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
578 buf = av_malloc(size);
581 final_picture = &picture_format_temp;
582 avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
584 if (img_convert(final_picture, enc->pix_fmt,
585 &ost->pict_tmp, PIX_FMT_YUV420P,
586 enc->width, enc->height) < 0) {
587 fprintf(stderr, "pixel format conversion not handled\n");
591 } else if (ost->video_crop) {
592 picture_crop_temp.data[0] = formatted_picture->data[0] +
593 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
595 picture_crop_temp.data[1] = formatted_picture->data[1] +
596 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
597 (ost->leftBand >> 1);
599 picture_crop_temp.data[2] = formatted_picture->data[2] +
600 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
601 (ost->leftBand >> 1);
603 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
604 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
605 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
606 final_picture = &picture_crop_temp;
608 final_picture = formatted_picture;
610 /* duplicates frame if needed */
611 /* XXX: pb because no interleaving */
612 for(i=0;i<nb_frames;i++) {
613 if (s->oformat->flags & AVFMT_RAWPICTURE) {
614 /* raw pictures are written as AVPicture structure to
615 avoid any copies. We support temorarily the older
617 AVFrame* old_frame = enc->coded_frame;
618 enc->coded_frame = dec->coded_frame;
619 av_write_frame(s, ost->index,
620 (uint8_t *)final_picture, sizeof(AVPicture));
621 enc->coded_frame = old_frame;
625 memset(&big_picture, 0, sizeof(AVFrame));
626 *(AVPicture*)&big_picture= *final_picture;
628 /* handles sameq here. This is not correct because it may
629 not be a global option */
631 big_picture.quality = ist->st->quality;
633 big_picture.quality = ost->st->quality;
635 ret = avcodec_encode_video(enc,
636 video_buffer, VIDEO_BUFFER_SIZE,
638 //enc->frame_number = enc->real_pict_num;
639 av_write_frame(s, ost->index, video_buffer, ret);
641 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
642 // enc->frame_number-1, enc->real_pict_num, ret,
644 /* if two pass, output log */
645 if (ost->logfile && enc->stats_out) {
646 fprintf(ost->logfile, "%s", enc->stats_out);
656 static double psnr(double d){
657 if(d==0) return INFINITY;
658 return -10.0*log(d)/log(10.0);
661 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
664 static FILE *fvstats=NULL;
665 static int64_t total_size = 0;
672 double ti1, bitrate, avg_bitrate;
676 today = localtime(&today2);
677 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
680 fvstats = fopen(filename,"w");
688 enc = &ost->st->codec;
689 total_size += frame_size;
690 if (enc->codec_type == CODEC_TYPE_VIDEO) {
691 frame_number = ost->frame_number;
692 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
693 if (enc->flags&CODEC_FLAG_PSNR)
694 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
696 fprintf(fvstats,"f_size= %6d ", frame_size);
697 /* compute pts value */
698 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
702 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
703 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
704 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
705 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
706 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
710 static void print_report(AVFormatContext **output_files,
711 AVOutputStream **ost_table, int nb_ostreams,
716 AVFormatContext *oc, *os;
719 int frame_number, vid, i;
720 double bitrate, ti1, pts;
721 static int64_t last_time = -1;
723 if (!is_last_report) {
725 /* display the report every 0.5 seconds */
726 cur_time = av_gettime();
727 if (last_time == -1) {
728 last_time = cur_time;
731 if ((cur_time - last_time) < 500000)
733 last_time = cur_time;
737 oc = output_files[0];
739 total_size = url_ftell(&oc->pb);
744 for(i=0;i<nb_ostreams;i++) {
746 os = output_files[ost->file_index];
747 enc = &ost->st->codec;
748 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
749 sprintf(buf + strlen(buf), "q=%2.1f ",
750 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
752 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
753 frame_number = ost->frame_number;
754 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
755 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
756 if (enc->flags&CODEC_FLAG_PSNR)
757 sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
760 /* compute min output value */
761 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
762 if ((pts < ti1) && (pts > 0))
768 if (verbose || is_last_report) {
769 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
771 sprintf(buf + strlen(buf),
772 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
773 (double)total_size / 1024, ti1, bitrate);
775 fprintf(stderr, "%s \r", buf);
780 fprintf(stderr, "\n");
784 * The following code is the main loop of the file converter
786 static int av_encode(AVFormatContext **output_files,
788 AVFormatContext **input_files,
790 AVStreamMap *stream_maps, int nb_stream_maps)
792 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
793 AVFormatContext *is, *os;
794 AVCodecContext *codec, *icodec;
795 AVOutputStream *ost, **ost_table = NULL;
796 AVInputStream *ist, **ist_table = NULL;
797 AVInputFile *file_table;
798 AVFormatContext *stream_no_data;
801 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
805 /* input stream init */
807 for(i=0;i<nb_input_files;i++) {
809 file_table[i].ist_index = j;
810 file_table[i].nb_streams = is->nb_streams;
815 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
819 for(i=0;i<nb_istreams;i++) {
820 ist = av_mallocz(sizeof(AVInputStream));
826 for(i=0;i<nb_input_files;i++) {
828 for(k=0;k<is->nb_streams;k++) {
829 ist = ist_table[j++];
830 ist->st = is->streams[k];
833 ist->discard = 1; /* the stream is discarded by default
836 if (ist->st->codec.rate_emu) {
837 ist->start = av_gettime();
843 /* output stream init */
845 for(i=0;i<nb_output_files;i++) {
846 os = output_files[i];
847 nb_ostreams += os->nb_streams;
849 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
850 fprintf(stderr, "Number of stream maps must match number of output streams\n");
854 /* Sanity check the mapping args -- do the input files & streams exist? */
855 for(i=0;i<nb_stream_maps;i++) {
856 int fi = stream_maps[i].file_index;
857 int si = stream_maps[i].stream_index;
859 if (fi < 0 || fi > nb_input_files - 1 ||
860 si < 0 || si > file_table[fi].nb_streams - 1) {
861 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
866 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
869 for(i=0;i<nb_ostreams;i++) {
870 ost = av_mallocz(sizeof(AVOutputStream));
877 for(k=0;k<nb_output_files;k++) {
878 os = output_files[k];
879 for(i=0;i<os->nb_streams;i++) {
881 ost = ost_table[n++];
884 ost->st = os->streams[i];
885 if (nb_stream_maps > 0) {
886 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
887 stream_maps[n-1].stream_index;
889 /* Sanity check that the stream types match */
890 if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
891 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
892 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
893 ost->file_index, ost->index);
898 /* get corresponding input stream index : we select the first one with the right type */
900 for(j=0;j<nb_istreams;j++) {
903 ist->st->codec.codec_type == ost->st->codec.codec_type) {
904 ost->source_index = j;
910 /* try again and reuse existing stream */
911 for(j=0;j<nb_istreams;j++) {
913 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
914 ost->source_index = j;
919 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
920 ost->file_index, ost->index);
925 ist = ist_table[ost->source_index];
930 /* for each output stream, we compute the right encoding parameters */
931 for(i=0;i<nb_ostreams;i++) {
933 ist = ist_table[ost->source_index];
935 codec = &ost->st->codec;
936 icodec = &ist->st->codec;
938 if (ost->st->stream_copy) {
939 /* if stream_copy is selected, no need to decode or encode */
940 codec->codec_id = icodec->codec_id;
941 codec->codec_type = icodec->codec_type;
942 codec->codec_tag = icodec->codec_tag;
943 codec->bit_rate = icodec->bit_rate;
944 switch(codec->codec_type) {
945 case CODEC_TYPE_AUDIO:
946 codec->sample_rate = icodec->sample_rate;
947 codec->channels = icodec->channels;
949 case CODEC_TYPE_VIDEO:
950 codec->frame_rate = icodec->frame_rate;
951 codec->frame_rate_base = icodec->frame_rate_base;
952 codec->width = icodec->width;
953 codec->height = icodec->height;
959 switch(codec->codec_type) {
960 case CODEC_TYPE_AUDIO:
961 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
964 if (codec->channels == icodec->channels &&
965 codec->sample_rate == icodec->sample_rate) {
966 ost->audio_resample = 0;
968 if (codec->channels != icodec->channels &&
969 icodec->codec_id == CODEC_ID_AC3) {
970 /* Special case for 5:1 AC3 input */
971 /* and mono or stereo output */
972 /* Request specific number of channels */
973 icodec->channels = codec->channels;
974 if (codec->sample_rate == icodec->sample_rate)
975 ost->audio_resample = 0;
977 ost->audio_resample = 1;
978 ost->resample = audio_resample_init(codec->channels, icodec->channels,
980 icodec->sample_rate);
983 printf("Can't resample. Aborting.\n");
987 /* Request specific number of channels */
988 icodec->channels = codec->channels;
990 ost->audio_resample = 1;
991 ost->resample = audio_resample_init(codec->channels, icodec->channels,
993 icodec->sample_rate);
996 printf("Can't resample. Aborting.\n");
1001 ist->decoding_needed = 1;
1002 ost->encoding_needed = 1;
1004 case CODEC_TYPE_VIDEO:
1005 if (codec->width == icodec->width &&
1006 codec->height == icodec->height &&
1007 frame_topBand == 0 &&
1008 frame_bottomBand == 0 &&
1009 frame_leftBand == 0 &&
1010 frame_rightBand == 0)
1012 ost->video_resample = 0;
1013 ost->video_crop = 0;
1014 } else if ((codec->width == icodec->width -
1015 (frame_leftBand + frame_rightBand)) &&
1016 (codec->height == icodec->height -
1017 (frame_topBand + frame_bottomBand)))
1019 ost->video_resample = 0;
1020 ost->video_crop = 1;
1021 ost->topBand = frame_topBand;
1022 ost->leftBand = frame_leftBand;
1025 ost->video_resample = 1;
1026 ost->video_crop = 0; // cropping is handled as part of resample
1027 buf = av_malloc((codec->width * codec->height * 3) / 2);
1030 ost->pict_tmp.data[0] = buf;
1031 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1032 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1033 ost->pict_tmp.linesize[0] = codec->width;
1034 ost->pict_tmp.linesize[1] = codec->width / 2;
1035 ost->pict_tmp.linesize[2] = codec->width / 2;
1037 ost->img_resample_ctx = img_resample_full_init(
1038 ost->st->codec.width, ost->st->codec.height,
1039 ist->st->codec.width, ist->st->codec.height,
1040 frame_topBand, frame_bottomBand,
1041 frame_leftBand, frame_rightBand);
1043 ost->encoding_needed = 1;
1044 ist->decoding_needed = 1;
1050 if (ost->encoding_needed &&
1051 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1052 char logfilename[1024];
1057 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1059 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1060 if (codec->flags & CODEC_FLAG_PASS1) {
1061 f = fopen(logfilename, "w");
1063 perror(logfilename);
1068 /* read the log file */
1069 f = fopen(logfilename, "r");
1071 perror(logfilename);
1074 fseek(f, 0, SEEK_END);
1076 fseek(f, 0, SEEK_SET);
1077 logbuffer = av_malloc(size + 1);
1079 fprintf(stderr, "Could not allocate log buffer\n");
1082 fread(logbuffer, 1, size, f);
1084 logbuffer[size] = '\0';
1085 codec->stats_in = logbuffer;
1091 /* dump the file output parameters - cannot be done before in case
1093 for(i=0;i<nb_output_files;i++) {
1094 dump_format(output_files[i], i, output_files[i]->filename, 1);
1097 /* dump the stream mapping */
1098 fprintf(stderr, "Stream mapping:\n");
1099 for(i=0;i<nb_ostreams;i++) {
1101 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1102 ist_table[ost->source_index]->file_index,
1103 ist_table[ost->source_index]->index,
1108 /* open each encoder */
1109 for(i=0;i<nb_ostreams;i++) {
1111 if (ost->encoding_needed) {
1113 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1115 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1116 ost->file_index, ost->index);
1119 if (avcodec_open(&ost->st->codec, codec) < 0) {
1120 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1121 ost->file_index, ost->index);
1127 /* open each decoder */
1128 for(i=0;i<nb_istreams;i++) {
1130 if (ist->decoding_needed) {
1132 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1134 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1135 ist->st->codec.codec_id, ist->file_index, ist->index);
1138 if (avcodec_open(&ist->st->codec, codec) < 0) {
1139 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1140 ist->file_index, ist->index);
1143 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1144 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1149 for(i=0;i<nb_istreams;i++) {
1151 is = input_files[ist->file_index];
1156 /* compute buffer size max (should use a complete heuristic) */
1157 for(i=0;i<nb_input_files;i++) {
1158 file_table[i].buffer_size_max = 2048;
1161 /* open files and write file headers */
1162 for(i=0;i<nb_output_files;i++) {
1163 os = output_files[i];
1164 if (av_write_header(os) < 0) {
1165 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1171 #ifndef CONFIG_WIN32
1173 fprintf(stderr, "Press [q] to stop encoding\n");
1180 for(; received_sigterm == 0;) {
1181 int file_index, ist_index;
1186 int data_size, got_picture;
1188 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1189 void *buffer_to_free;
1193 /* if 'q' pressed, exits */
1195 /* read_key() returns 0 on EOF */
1201 /* select the stream that we must read now by looking at the
1202 smallest output pts */
1205 for(i=0;i<nb_ostreams;i++) {
1208 os = output_files[ost->file_index];
1209 ist = ist_table[ost->source_index];
1210 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1211 if (!file_table[ist->file_index].eof_reached &&
1214 file_index = ist->file_index;
1217 /* if none, if is finished */
1218 if (file_index < 0) {
1222 /* finish if recording time exhausted */
1223 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1226 /* read a frame from it and output it in the fifo */
1227 is = input_files[file_index];
1228 if (av_read_frame(is, &pkt) < 0) {
1229 file_table[file_index].eof_reached = 1;
1233 stream_no_data = is;
1238 av_pkt_dump(stdout, &pkt, do_hex_dump);
1240 /* the following test is needed in case new streams appear
1241 dynamically in stream : we ignore them */
1242 if (pkt.stream_index >= file_table[file_index].nb_streams)
1243 goto discard_packet;
1244 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1245 ist = ist_table[ist_index];
1247 goto discard_packet;
1249 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1251 if (pkt.pts != AV_NOPTS_VALUE) {
1254 ist->pts = ist->next_pts;
1260 /* decode the packet if needed */
1261 data_buf = NULL; /* fail safe */
1263 if (ist->decoding_needed) {
1264 switch(ist->st->codec.codec_type) {
1265 case CODEC_TYPE_AUDIO:
1266 /* XXX: could avoid copy if PCM 16 bits with same
1267 endianness as CPU */
1268 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1274 /* Some bug in mpeg audio decoder gives */
1275 /* data_size < 0, it seems they are overflows */
1276 if (data_size <= 0) {
1277 /* no audio frame */
1280 data_buf = (uint8_t *)samples;
1281 ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) /
1282 (2 * ist->st->codec.channels);
1284 case CODEC_TYPE_VIDEO:
1286 AVFrame big_picture;
1288 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1289 ret = avcodec_decode_video(&ist->st->codec,
1290 &big_picture, &got_picture, ptr, len);
1291 picture= *(AVPicture*)&big_picture;
1292 ist->st->quality= big_picture.quality;
1295 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1296 ist->file_index, ist->index);
1297 av_free_packet(&pkt);
1301 /* no picture yet */
1302 goto discard_packet;
1304 if (ist->st->codec.frame_rate_base != 0) {
1305 ist->next_pts += ((int64_t)AV_TIME_BASE *
1306 ist->st->codec.frame_rate_base) /
1307 ist->st->codec.frame_rate;
1322 buffer_to_free = NULL;
1323 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1324 pre_process_video_frame(ist, &picture, &buffer_to_free);
1327 /* frame rate emulation */
1328 if (ist->st->codec.rate_emu) {
1329 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
1330 int64_t now = av_gettime() - ist->start;
1338 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1339 is the one of the next displayed one */
1340 /* XXX: add mpeg4 too ? */
1341 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1342 if (ist->st->codec.pict_type != B_TYPE) {
1344 tmp = ist->last_ip_pts;
1345 ist->last_ip_pts = ist->frac_pts.val;
1346 ist->frac_pts.val = tmp;
1350 /* if output time reached then transcode raw format,
1351 encode packets and output them */
1352 if (start_time == 0 || ist->pts >= start_time)
1353 for(i=0;i<nb_ostreams;i++) {
1357 if (ost->source_index == ist_index) {
1358 os = output_files[ost->file_index];
1361 printf("%d: got pts=%0.3f %0.3f\n", i,
1362 (double)pkt.pts / AV_TIME_BASE,
1363 ((double)ist->pts / AV_TIME_BASE) -
1364 ((double)ost->st->pts.val * os->pts_num / os->pts_den));
1366 /* set the input output pts pairs */
1367 ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
1368 /* XXX: take into account the various fifos,
1369 in particular for audio */
1370 ost->sync_opts = ost->st->pts.val;
1371 //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);
1373 if (ost->encoding_needed) {
1374 switch(ost->st->codec.codec_type) {
1375 case CODEC_TYPE_AUDIO:
1376 do_audio_out(os, ost, ist, data_buf, data_size);
1378 case CODEC_TYPE_VIDEO:
1379 /* find an audio stream for synchro */
1382 AVOutputStream *audio_sync, *ost1;
1384 for(i=0;i<nb_ostreams;i++) {
1385 ost1 = ost_table[i];
1386 if (ost1->file_index == ost->file_index &&
1387 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1393 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1394 if (do_vstats && frame_size)
1395 do_video_stats(os, ost, frame_size);
1404 /* no reencoding needed : output the packet directly */
1405 /* force the input stream PTS */
1407 memset(&avframe, 0, sizeof(AVFrame));
1408 ost->st->codec.coded_frame= &avframe;
1409 avframe.key_frame = pkt.flags & PKT_FLAG_KEY;
1411 av_write_frame(os, ost->index, data_buf, data_size);
1412 ost->st->codec.frame_number++;
1413 ost->frame_number++;
1417 av_free(buffer_to_free);
1420 av_free_packet(&pkt);
1422 /* dump report by using the output first video and audio streams */
1423 print_report(output_files, ost_table, nb_ostreams, 0);
1427 /* dump report by using the first video and audio streams */
1428 print_report(output_files, ost_table, nb_ostreams, 1);
1430 /* close each encoder */
1431 for(i=0;i<nb_ostreams;i++) {
1433 if (ost->encoding_needed) {
1434 av_freep(&ost->st->codec.stats_in);
1435 avcodec_close(&ost->st->codec);
1439 /* close each decoder */
1440 for(i=0;i<nb_istreams;i++) {
1442 if (ist->decoding_needed) {
1443 avcodec_close(&ist->st->codec);
1448 /* write the trailer if needed and close file */
1449 for(i=0;i<nb_output_files;i++) {
1450 os = output_files[i];
1451 av_write_trailer(os);
1457 av_free(file_table);
1460 for(i=0;i<nb_istreams;i++) {
1467 for(i=0;i<nb_ostreams;i++) {
1471 fclose(ost->logfile);
1472 ost->logfile = NULL;
1474 fifo_free(&ost->fifo); /* works even if fifo is not
1475 initialized but set to zero */
1476 av_free(ost->pict_tmp.data[0]);
1477 if (ost->video_resample)
1478 img_resample_close(ost->img_resample_ctx);
1479 if (ost->audio_resample)
1480 audio_resample_close(ost->resample);
1493 int file_read(const char *filename)
1496 unsigned char buffer[1024];
1499 if (url_open(&h, filename, O_RDONLY) < 0) {
1500 printf("could not open '%s'\n", filename);
1504 len = url_read(h, buffer, sizeof(buffer));
1507 for(i=0;i<len;i++) putchar(buffer[i]);
1514 static void opt_image_format(const char *arg)
1518 for(f = first_image_format; f != NULL; f = f->next) {
1519 if (!strcmp(arg, f->name))
1523 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1529 static void opt_format(const char *arg)
1531 /* compatibility stuff for pgmyuv */
1532 if (!strcmp(arg, "pgmyuv")) {
1533 opt_image_format(arg);
1537 file_iformat = av_find_input_format(arg);
1538 file_oformat = guess_format(arg, NULL, NULL);
1539 if (!file_iformat && !file_oformat) {
1540 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1545 static void opt_video_bitrate(const char *arg)
1547 video_bit_rate = atoi(arg) * 1000;
1550 static void opt_video_bitrate_tolerance(const char *arg)
1552 video_bit_rate_tolerance = atoi(arg) * 1000;
1555 static void opt_video_bitrate_max(const char *arg)
1557 video_rc_max_rate = atoi(arg) * 1000;
1560 static void opt_video_bitrate_min(const char *arg)
1562 video_rc_min_rate = atoi(arg) * 1000;
1565 static void opt_video_buffer_size(const char *arg)
1567 video_rc_buffer_size = atoi(arg) * 1000;
1570 static void opt_video_rc_eq(char *arg)
1575 static void opt_video_rc_override_string(char *arg)
1577 video_rc_override_string = arg;
1581 static void opt_workaround_bugs(const char *arg)
1583 workaround_bugs = atoi(arg);
1586 static void opt_dct_algo(const char *arg)
1588 dct_algo = atoi(arg);
1591 static void opt_idct_algo(const char *arg)
1593 idct_algo = atoi(arg);
1597 static void opt_error_resilience(const char *arg)
1599 error_resilience = atoi(arg);
1602 static void opt_error_concealment(const char *arg)
1604 error_concealment = atoi(arg);
1607 static void opt_debug(const char *arg)
1612 static void opt_verbose(const char *arg)
1614 verbose = atoi(arg);
1617 static void opt_frame_rate(const char *arg)
1619 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1620 fprintf(stderr, "Incorrect frame rate\n");
1625 static void opt_frame_crop_top(const char *arg)
1627 frame_topBand = atoi(arg);
1628 if (frame_topBand < 0) {
1629 fprintf(stderr, "Incorrect top crop size\n");
1632 if ((frame_topBand % 2) != 0) {
1633 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1636 if ((frame_topBand) >= frame_height){
1637 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1640 frame_height -= frame_topBand;
1643 static void opt_frame_crop_bottom(const char *arg)
1645 frame_bottomBand = atoi(arg);
1646 if (frame_bottomBand < 0) {
1647 fprintf(stderr, "Incorrect bottom crop size\n");
1650 if ((frame_bottomBand % 2) != 0) {
1651 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1654 if ((frame_bottomBand) >= frame_height){
1655 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1658 frame_height -= frame_bottomBand;
1661 static void opt_frame_crop_left(const char *arg)
1663 frame_leftBand = atoi(arg);
1664 if (frame_leftBand < 0) {
1665 fprintf(stderr, "Incorrect left crop size\n");
1668 if ((frame_leftBand % 2) != 0) {
1669 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1672 if ((frame_leftBand) >= frame_width){
1673 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1676 frame_width -= frame_leftBand;
1679 static void opt_frame_crop_right(const char *arg)
1681 frame_rightBand = atoi(arg);
1682 if (frame_rightBand < 0) {
1683 fprintf(stderr, "Incorrect right crop size\n");
1686 if ((frame_rightBand % 2) != 0) {
1687 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1690 if ((frame_rightBand) >= frame_width){
1691 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1694 frame_width -= frame_rightBand;
1697 static void opt_frame_size(const char *arg)
1699 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1700 fprintf(stderr, "Incorrect frame size\n");
1703 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1704 fprintf(stderr, "Frame size must be a multiple of 2\n");
1709 static void opt_frame_pix_fmt(const char *arg)
1711 frame_pix_fmt = avcodec_get_pix_fmt(arg);
1714 static void opt_frame_aspect_ratio(const char *arg)
1720 p = strchr(arg, ':');
1722 x = strtol(arg, (char **)&arg, 10);
1724 y = strtol(arg+1, (char **)&arg, 10);
1726 ar = (double)x / (double)y;
1728 ar = strtod(arg, (char **)&arg);
1731 fprintf(stderr, "Incorrect aspect ratio specification.\n");
1734 frame_aspect_ratio = ar;
1737 static void opt_gop_size(const char *arg)
1739 gop_size = atoi(arg);
1742 static void opt_b_frames(const char *arg)
1744 b_frames = atoi(arg);
1745 if (b_frames > FF_MAX_B_FRAMES) {
1746 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1748 } else if (b_frames < 1) {
1749 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1754 static void opt_mb_decision(const char *arg)
1756 mb_decision = atoi(arg);
1759 static void opt_qscale(const char *arg)
1761 video_qscale = atof(arg);
1762 if (video_qscale < 0.01 ||
1763 video_qscale > 255) {
1764 fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1769 static void opt_qmin(const char *arg)
1771 video_qmin = atoi(arg);
1772 if (video_qmin < 0 ||
1774 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1779 static void opt_qmax(const char *arg)
1781 video_qmax = atoi(arg);
1782 if (video_qmax < 0 ||
1784 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1789 static void opt_mb_qmin(const char *arg)
1791 video_mb_qmin = atoi(arg);
1792 if (video_mb_qmin < 0 ||
1793 video_mb_qmin > 31) {
1794 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1799 static void opt_mb_qmax(const char *arg)
1801 video_mb_qmax = atoi(arg);
1802 if (video_mb_qmax < 0 ||
1803 video_mb_qmax > 31) {
1804 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1809 static void opt_qdiff(const char *arg)
1811 video_qdiff = atoi(arg);
1812 if (video_qdiff < 0 ||
1814 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1819 static void opt_qblur(const char *arg)
1821 video_qblur = atof(arg);
1824 static void opt_qcomp(const char *arg)
1826 video_qcomp = atof(arg);
1829 static void opt_rc_initial_cplx(const char *arg)
1831 video_rc_initial_cplx = atof(arg);
1833 static void opt_b_qfactor(const char *arg)
1835 video_b_qfactor = atof(arg);
1837 static void opt_i_qfactor(const char *arg)
1839 video_i_qfactor = atof(arg);
1841 static void opt_b_qoffset(const char *arg)
1843 video_b_qoffset = atof(arg);
1845 static void opt_i_qoffset(const char *arg)
1847 video_i_qoffset = atof(arg);
1850 static void opt_packet_size(const char *arg)
1852 packet_size= atoi(arg);
1855 static void opt_strict(const char *arg)
1860 static void opt_audio_bitrate(const char *arg)
1862 audio_bit_rate = atoi(arg) * 1000;
1865 static void opt_audio_rate(const char *arg)
1867 audio_sample_rate = atoi(arg);
1870 static void opt_audio_channels(const char *arg)
1872 audio_channels = atoi(arg);
1875 static void opt_video_device(const char *arg)
1877 video_device = av_strdup(arg);
1880 static void opt_video_channel(const char *arg)
1882 video_channel = strtol(arg, NULL, 0);
1885 static void opt_video_standard(const char *arg)
1887 video_standard = av_strdup(arg);
1890 static void opt_audio_device(const char *arg)
1892 audio_device = av_strdup(arg);
1895 static void opt_dv1394(const char *arg)
1897 video_grab_format = "dv1394";
1898 audio_grab_format = NULL;
1901 static void opt_audio_codec(const char *arg)
1905 if (!strcmp(arg, "copy")) {
1906 audio_stream_copy = 1;
1910 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1915 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1918 audio_codec_id = p->id;
1923 static void add_frame_hooker(const char *arg)
1928 char *args = av_strdup(arg);
1932 argv[0] = strtok(args, " ");
1933 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1936 i = frame_hook_add(argc, argv);
1939 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1944 const char *motion_str[] = {
1954 static void opt_motion_estimation(const char *arg)
1960 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1963 if (!strcmp(*p, arg))
1967 me_method = (p - motion_str) + 1;
1970 static void opt_video_codec(const char *arg)
1974 if (!strcmp(arg, "copy")) {
1975 video_stream_copy = 1;
1979 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1984 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1987 video_codec_id = p->id;
1992 static void opt_map(const char *arg)
1998 m = &stream_maps[nb_stream_maps++];
2000 m->file_index = strtol(arg, (char **)&p, 0);
2004 m->stream_index = strtol(p, (char **)&p, 0);
2007 static void opt_recording_time(const char *arg)
2009 recording_time = parse_date(arg, 1);
2012 static void opt_start_time(const char *arg)
2014 start_time = parse_date(arg, 1);
2017 static void opt_input_file(const char *filename)
2019 AVFormatContext *ic;
2020 AVFormatParameters params, *ap = ¶ms;
2021 int err, i, ret, rfps, rfps_base;
2023 if (!strcmp(filename, "-"))
2026 using_stdin |= !strcmp(filename, "pipe:" ) ||
2027 !strcmp( filename, "/dev/stdin" );
2029 /* get default parameters from command line */
2030 memset(ap, 0, sizeof(*ap));
2031 ap->sample_rate = audio_sample_rate;
2032 ap->channels = audio_channels;
2033 ap->frame_rate = frame_rate;
2034 ap->frame_rate_base = frame_rate_base;
2035 ap->width = frame_width;
2036 ap->height = frame_height;
2037 ap->image_format = image_format;
2038 ap->pix_fmt = frame_pix_fmt;
2040 /* open the input file with generic libav function */
2041 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2043 print_error(filename, err);
2047 /* If not enough info to get the stream parameters, we decode the
2048 first frames to get it. (used in mpeg case for example) */
2049 ret = av_find_stream_info(ic);
2051 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2055 /* if seeking requested, we execute it */
2056 if (start_time != 0) {
2059 timestamp = start_time;
2060 /* add the stream start time */
2061 if (ic->start_time != AV_NOPTS_VALUE)
2062 timestamp += ic->start_time;
2063 ret = av_seek_frame(ic, -1, timestamp);
2065 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2066 filename, (double)timestamp / AV_TIME_BASE);
2068 /* reset seek info */
2072 /* update the current parameters so that they match the one of the input stream */
2073 for(i=0;i<ic->nb_streams;i++) {
2074 AVCodecContext *enc = &ic->streams[i]->codec;
2075 switch(enc->codec_type) {
2076 case CODEC_TYPE_AUDIO:
2077 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2078 audio_channels = enc->channels;
2079 audio_sample_rate = enc->sample_rate;
2081 case CODEC_TYPE_VIDEO:
2082 frame_height = enc->height;
2083 frame_width = enc->width;
2084 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2085 frame_pix_fmt = enc->pix_fmt;
2086 rfps = ic->streams[i]->r_frame_rate;
2087 rfps_base = ic->streams[i]->r_frame_rate_base;
2088 enc->workaround_bugs = workaround_bugs;
2089 enc->error_resilience = error_resilience;
2090 enc->error_concealment = error_concealment;
2091 enc->idct_algo= idct_algo;
2094 enc->flags|= CODEC_FLAG_BITEXACT;
2096 assert(enc->frame_rate_base == rfps_base); // should be true for now
2097 if (enc->frame_rate != rfps) {
2098 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2099 i, (float)enc->frame_rate / enc->frame_rate_base,
2100 (float)rfps / rfps_base);
2102 /* update the current frame rate to match the stream frame rate */
2104 frame_rate_base = rfps_base;
2106 enc->rate_emu = rate_emu;
2108 case CODEC_TYPE_DATA:
2115 input_files[nb_input_files] = ic;
2116 /* dump the file content */
2117 dump_format(ic, nb_input_files, filename, 0);
2119 file_iformat = NULL;
2120 file_oformat = NULL;
2121 image_format = NULL;
2126 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2128 int has_video, has_audio, i, j;
2129 AVFormatContext *ic;
2133 for(j=0;j<nb_input_files;j++) {
2134 ic = input_files[j];
2135 for(i=0;i<ic->nb_streams;i++) {
2136 AVCodecContext *enc = &ic->streams[i]->codec;
2137 switch(enc->codec_type) {
2138 case CODEC_TYPE_AUDIO:
2141 case CODEC_TYPE_VIDEO:
2149 *has_video_ptr = has_video;
2150 *has_audio_ptr = has_audio;
2153 static void opt_output_file(const char *filename)
2156 AVFormatContext *oc;
2157 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2159 AVFormatParameters params, *ap = ¶ms;
2161 if (!strcmp(filename, "-"))
2164 oc = av_mallocz(sizeof(AVFormatContext));
2166 if (!file_oformat) {
2167 file_oformat = guess_format(NULL, filename, NULL);
2168 if (!file_oformat) {
2169 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2175 oc->oformat = file_oformat;
2177 if (!strcmp(file_oformat->name, "ffm") &&
2178 strstart(filename, "http:", NULL)) {
2179 /* special case for files sent to ffserver: we get the stream
2180 parameters from ffserver */
2181 if (read_ffserver_streams(oc, filename) < 0) {
2182 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2186 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2187 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2189 /* disable if no corresponding type found and at least one
2191 if (nb_input_files > 0) {
2192 check_audio_video_inputs(&input_has_video, &input_has_audio);
2193 if (!input_has_video)
2195 if (!input_has_audio)
2199 /* manual disable */
2200 if (audio_disable) {
2203 if (video_disable) {
2209 AVCodecContext *video_enc;
2211 st = av_mallocz(sizeof(AVStream));
2213 fprintf(stderr, "Could not alloc stream\n");
2216 avcodec_get_context_defaults(&st->codec);
2218 video_enc = &st->codec;
2220 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2221 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2222 if (video_stream_copy) {
2223 st->stream_copy = 1;
2224 video_enc->codec_type = CODEC_TYPE_VIDEO;
2229 codec_id = file_oformat->video_codec;
2230 if (video_codec_id != CODEC_ID_NONE)
2231 codec_id = video_codec_id;
2233 video_enc->codec_id = codec_id;
2235 video_enc->bit_rate = video_bit_rate;
2236 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2237 video_enc->frame_rate = frame_rate;
2238 video_enc->frame_rate_base = frame_rate_base;
2240 video_enc->width = frame_width;
2241 video_enc->height = frame_height;
2242 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2243 video_enc->pix_fmt = frame_pix_fmt;
2246 video_enc->gop_size = gop_size;
2248 video_enc->gop_size = 0;
2249 if (video_qscale || same_quality) {
2250 video_enc->flags |= CODEC_FLAG_QSCALE;
2251 st->quality = FF_QP2LAMBDA * video_qscale;
2255 video_enc->intra_matrix = intra_matrix;
2257 video_enc->inter_matrix = inter_matrix;
2260 video_enc->flags |= CODEC_FLAG_BITEXACT;
2262 video_enc->mb_decision = mb_decision;
2265 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2268 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2271 video_enc->flags |= CODEC_FLAG_4MV;
2275 video_enc->flags |= CODEC_FLAG_PART;
2279 video_enc->max_b_frames = b_frames;
2280 video_enc->b_frame_strategy = 0;
2281 video_enc->b_quant_factor = 2.0;
2284 video_enc->qmin = video_qmin;
2285 video_enc->qmax = video_qmax;
2286 video_enc->mb_qmin = video_mb_qmin;
2287 video_enc->mb_qmax = video_mb_qmax;
2288 video_enc->max_qdiff = video_qdiff;
2289 video_enc->qblur = video_qblur;
2290 video_enc->qcompress = video_qcomp;
2291 video_enc->rc_eq = video_rc_eq;
2292 video_enc->debug= debug;
2294 p= video_rc_override_string;
2297 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2299 fprintf(stderr, "error parsing rc_override\n");
2302 video_enc->rc_override=
2303 av_realloc(video_enc->rc_override,
2304 sizeof(RcOverride)*(i+1));
2305 video_enc->rc_override[i].start_frame= start;
2306 video_enc->rc_override[i].end_frame = end;
2308 video_enc->rc_override[i].qscale= q;
2309 video_enc->rc_override[i].quality_factor= 1.0;
2312 video_enc->rc_override[i].qscale= 0;
2313 video_enc->rc_override[i].quality_factor= -q/100.0;
2318 video_enc->rc_override_count=i;
2320 video_enc->rc_max_rate = video_rc_max_rate;
2321 video_enc->rc_min_rate = video_rc_min_rate;
2322 video_enc->rc_buffer_size = video_rc_buffer_size;
2323 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2324 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2325 video_enc->i_quant_factor = video_i_qfactor;
2326 video_enc->b_quant_factor = video_b_qfactor;
2327 video_enc->i_quant_offset = video_i_qoffset;
2328 video_enc->b_quant_offset = video_b_qoffset;
2329 video_enc->dct_algo = dct_algo;
2330 video_enc->idct_algo = idct_algo;
2331 video_enc->strict_std_compliance = strict;
2333 video_enc->rtp_mode= 1;
2334 video_enc->rtp_payload_size= packet_size;
2338 video_enc->flags|= CODEC_FLAG_PSNR;
2340 video_enc->me_method = me_method;
2345 video_enc->flags |= CODEC_FLAG_PASS1;
2347 video_enc->flags |= CODEC_FLAG_PASS2;
2351 oc->streams[nb_streams] = st;
2356 AVCodecContext *audio_enc;
2358 st = av_mallocz(sizeof(AVStream));
2360 fprintf(stderr, "Could not alloc stream\n");
2363 avcodec_get_context_defaults(&st->codec);
2365 audio_enc = &st->codec;
2366 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2368 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2369 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2370 if (audio_stream_copy) {
2371 st->stream_copy = 1;
2373 codec_id = file_oformat->audio_codec;
2374 if (audio_codec_id != CODEC_ID_NONE)
2375 codec_id = audio_codec_id;
2376 audio_enc->codec_id = codec_id;
2378 audio_enc->bit_rate = audio_bit_rate;
2379 audio_enc->sample_rate = audio_sample_rate;
2380 /* For audio codecs other than AC3 we limit */
2381 /* the number of coded channels to stereo */
2382 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2383 audio_enc->channels = 2;
2385 audio_enc->channels = audio_channels;
2387 oc->streams[nb_streams] = st;
2391 oc->nb_streams = nb_streams;
2394 fprintf(stderr, "No audio or video streams available\n");
2399 pstrcpy(oc->title, sizeof(oc->title), str_title);
2401 pstrcpy(oc->author, sizeof(oc->author), str_author);
2403 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2405 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2408 output_files[nb_output_files++] = oc;
2410 strcpy(oc->filename, filename);
2412 /* check filename in case of an image number is expected */
2413 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2414 if (filename_number_test(oc->filename) < 0) {
2415 print_error(oc->filename, AVERROR_NUMEXPECTED);
2420 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2421 /* test if it already exists to avoid loosing precious files */
2422 if (!file_overwrite &&
2423 (strchr(filename, ':') == NULL ||
2424 strstart(filename, "file:", NULL))) {
2425 if (url_exist(filename)) {
2428 if ( !using_stdin ) {
2429 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2432 if (toupper(c) != 'Y') {
2433 fprintf(stderr, "Not overwriting - exiting\n");
2438 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2445 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2446 fprintf(stderr, "Could not open '%s'\n", filename);
2451 memset(ap, 0, sizeof(*ap));
2452 ap->image_format = image_format;
2453 if (av_set_parameters(oc, ap) < 0) {
2454 fprintf(stderr, "%s: Invalid encoding parameters\n",
2459 /* reset some options */
2460 file_oformat = NULL;
2461 file_iformat = NULL;
2462 image_format = NULL;
2465 audio_codec_id = CODEC_ID_NONE;
2466 video_codec_id = CODEC_ID_NONE;
2467 audio_stream_copy = 0;
2468 video_stream_copy = 0;
2471 /* prepare dummy protocols for grab */
2472 static void prepare_grab(void)
2474 int has_video, has_audio, i, j;
2475 AVFormatContext *oc;
2476 AVFormatContext *ic;
2477 AVFormatParameters vp1, *vp = &vp1;
2478 AVFormatParameters ap1, *ap = &ap1;
2480 /* see if audio/video inputs are needed */
2483 memset(ap, 0, sizeof(*ap));
2484 memset(vp, 0, sizeof(*vp));
2485 for(j=0;j<nb_output_files;j++) {
2486 oc = output_files[j];
2487 for(i=0;i<oc->nb_streams;i++) {
2488 AVCodecContext *enc = &oc->streams[i]->codec;
2489 switch(enc->codec_type) {
2490 case CODEC_TYPE_AUDIO:
2491 if (enc->sample_rate > ap->sample_rate)
2492 ap->sample_rate = enc->sample_rate;
2493 if (enc->channels > ap->channels)
2494 ap->channels = enc->channels;
2497 case CODEC_TYPE_VIDEO:
2498 if (enc->width > vp->width)
2499 vp->width = enc->width;
2500 if (enc->height > vp->height)
2501 vp->height = enc->height;
2503 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2504 if (enc->frame_rate > vp->frame_rate){
2505 vp->frame_rate = enc->frame_rate;
2506 vp->frame_rate_base = enc->frame_rate_base;
2516 if (has_video == 0 && has_audio == 0) {
2517 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2522 AVInputFormat *fmt1;
2523 fmt1 = av_find_input_format(video_grab_format);
2524 vp->device = video_device;
2525 vp->channel = video_channel;
2526 vp->standard = video_standard;
2527 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2528 fprintf(stderr, "Could not find video grab device\n");
2531 /* If not enough info to get the stream parameters, we decode the
2532 first frames to get it. */
2533 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2534 fprintf(stderr, "Could not find video grab parameters\n");
2537 /* by now video grab has one stream */
2538 ic->streams[0]->r_frame_rate = vp->frame_rate;
2539 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2540 input_files[nb_input_files] = ic;
2541 dump_format(ic, nb_input_files, "", 0);
2544 if (has_audio && audio_grab_format) {
2545 AVInputFormat *fmt1;
2546 fmt1 = av_find_input_format(audio_grab_format);
2547 ap->device = audio_device;
2548 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2549 fprintf(stderr, "Could not find audio grab device\n");
2552 input_files[nb_input_files] = ic;
2553 dump_format(ic, nb_input_files, "", 0);
2558 /* same option as mencoder */
2559 static void opt_pass(const char *pass_str)
2562 pass = atoi(pass_str);
2563 if (pass != 1 && pass != 2) {
2564 fprintf(stderr, "pass number can be only 1 or 2\n");
2570 #if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2571 static int64_t getutime(void)
2573 return av_gettime();
2576 static int64_t getutime(void)
2578 struct rusage rusage;
2580 getrusage(RUSAGE_SELF, &rusage);
2581 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2585 extern int ffm_nopts;
2587 static void opt_bitexact(void)
2590 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2594 static void show_formats(void)
2596 AVInputFormat *ifmt;
2597 AVOutputFormat *ofmt;
2598 AVImageFormat *image_fmt;
2603 printf("Output audio/video file formats:");
2604 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2605 printf(" %s", ofmt->name);
2609 printf("Input audio/video file formats:");
2610 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2611 printf(" %s", ifmt->name);
2615 printf("Output image formats:");
2616 for(image_fmt = first_image_format; image_fmt != NULL;
2617 image_fmt = image_fmt->next) {
2618 if (image_fmt->img_write)
2619 printf(" %s", image_fmt->name);
2623 printf("Input image formats:");
2624 for(image_fmt = first_image_format; image_fmt != NULL;
2625 image_fmt = image_fmt->next) {
2626 if (image_fmt->img_read)
2627 printf(" %s", image_fmt->name);
2631 printf("Codecs:\n");
2632 printf(" Encoders:");
2633 for(p = first_avcodec; p != NULL; p = p->next) {
2635 printf(" %s", p->name);
2639 printf(" Decoders:");
2640 for(p = first_avcodec; p != NULL; p = p->next) {
2642 printf(" %s", p->name);
2646 printf("Supported file protocols:");
2647 for(up = first_protocol; up != NULL; up = up->next)
2648 printf(" %s:", up->name);
2651 printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2652 printf("Motion estimation methods:");
2656 if ((pp - motion_str + 1) == ME_ZERO)
2657 printf("(fastest)");
2658 else if ((pp - motion_str + 1) == ME_FULL)
2659 printf("(slowest)");
2660 else if ((pp - motion_str + 1) == ME_EPZS)
2661 printf("(default)");
2668 void parse_matrix_coeffs(uint16_t *dest, const char *str)
2671 const char *p = str;
2678 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2685 void opt_inter_matrix(const char *arg)
2687 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2688 parse_matrix_coeffs(inter_matrix, arg);
2691 void opt_intra_matrix(const char *arg)
2693 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2694 parse_matrix_coeffs(intra_matrix, arg);
2697 static void opt_target(const char *arg)
2701 if(!strncmp(arg, "pal-", 4)) {
2704 } else if(!strncmp(arg, "ntsc-", 5)) {
2709 /* Calculate FR via float to avoid int overflow */
2710 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2713 } else if((fr == 29970) || (fr == 23976)) {
2716 /* Try to determine PAL/NTSC by peeking in the input files */
2717 if(nb_input_files) {
2719 for(j = 0; j < nb_input_files; j++) {
2720 for(i = 0; i < input_files[j]->nb_streams; i++) {
2721 AVCodecContext *c = &input_files[j]->streams[i]->codec;
2722 if(c->codec_type != CODEC_TYPE_VIDEO)
2724 fr = c->frame_rate * 1000 / c->frame_rate_base;
2728 } else if((fr == 29970) || (fr == 23976)) {
2738 if(verbose && norm >= 0)
2739 printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2743 fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2744 fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2745 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2749 if(!strcmp(arg, "vcd")) {
2751 opt_video_codec("mpeg1video");
2752 opt_audio_codec("mp2");
2755 opt_frame_size(norm ? "352x240" : "352x288");
2757 video_bit_rate = 1150000;
2758 video_rc_max_rate = 1150000;
2759 video_rc_min_rate = 1150000;
2761 audio_bit_rate = 224000;
2762 audio_sample_rate = 44100;
2764 } else if(!strcmp(arg, "svcd")) {
2766 opt_video_codec("mpeg2video");
2767 opt_audio_codec("mp2");
2770 opt_frame_size(norm ? "480x480" : "480x576");
2771 opt_gop_size(norm ? "18" : "15");
2773 video_bit_rate = 2040000;
2774 video_rc_max_rate = 2516000;
2775 video_rc_min_rate = 1145000;
2777 audio_bit_rate = 224000;
2778 audio_sample_rate = 44100;
2780 } else if(!strcmp(arg, "dvd")) {
2782 opt_video_codec("mpeg2video");
2783 opt_audio_codec("ac3");
2786 opt_frame_size(norm ? "720x480" : "720x576");
2787 opt_gop_size(norm ? "18" : "15");
2789 video_bit_rate = 6000000;
2790 video_rc_max_rate = 9000000;
2791 video_rc_min_rate = 1500000;
2793 audio_bit_rate = 448000;
2794 audio_sample_rate = 48000;
2797 fprintf(stderr, "Unknown target: %s\n", arg);
2802 const OptionDef options[] = {
2804 { "L", 0, {(void*)show_license}, "show license" },
2805 { "h", 0, {(void*)show_help}, "show help" },
2806 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2807 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2808 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2809 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2810 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2811 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2812 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2813 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2814 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2815 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2816 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2817 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2818 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2819 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2820 "add timings for benchmarking" },
2821 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
2822 "dump each input packet" },
2823 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2824 "when dumping packets, also dump the payload" },
2825 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2826 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2827 { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2828 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2829 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2832 { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2833 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2834 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2835 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2836 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2837 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2838 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2839 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2840 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2841 { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2842 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2843 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2844 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2845 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2846 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2847 { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2848 { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2849 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2850 { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2851 { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2852 { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2853 { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2854 { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2855 { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2856 { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2857 // { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2858 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2859 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2860 { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2861 { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2862 { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2863 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2864 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2865 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
2867 { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2868 { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2869 { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience", "n" },
2870 { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment", "bit_mask" },
2871 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2872 { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2873 { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2874 { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2875 { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2876 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2877 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2878 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2879 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
2880 "use same video quality as source (implies VBR)" },
2881 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2882 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2883 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
2884 "deinterlace pictures" },
2885 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2886 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
2887 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2888 { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2889 { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2890 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
2891 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
2894 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2895 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2896 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2897 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2898 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2901 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2902 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2903 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2904 { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2905 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2909 static void show_banner(void)
2911 printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2914 static void show_license(void)
2918 "This library is free software; you can redistribute it and/or\n"
2919 "modify it under the terms of the GNU Lesser General Public\n"
2920 "License as published by the Free Software Foundation; either\n"
2921 "version 2 of the License, or (at your option) any later version.\n"
2923 "This library is distributed in the hope that it will be useful,\n"
2924 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
2925 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
2926 "Lesser General Public License for more details.\n"
2928 "You should have received a copy of the GNU Lesser General Public\n"
2929 "License along with this library; if not, write to the Free Software\n"
2930 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
2935 static void show_help(void)
2938 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2939 "Hyper fast Audio and Video encoder\n");
2941 show_help_options(options, "Main options:\n",
2942 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
2943 show_help_options(options, "\nVideo options:\n",
2944 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2946 show_help_options(options, "\nAdvanced Video options:\n",
2947 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2948 OPT_VIDEO | OPT_EXPERT);
2949 show_help_options(options, "\nAudio options:\n",
2950 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2952 show_help_options(options, "\nAdvanced Audio options:\n",
2953 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2954 OPT_AUDIO | OPT_EXPERT);
2955 show_help_options(options, "\nAudio/Video grab options:\n",
2958 show_help_options(options, "\nAdvanced options:\n",
2959 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
2964 void parse_arg_file(const char *filename)
2966 opt_output_file(filename);
2969 int main(int argc, char **argv)
2980 parse_options(argc, argv, options);
2982 /* file converter / grab */
2983 if (nb_output_files <= 0) {
2984 fprintf(stderr, "Must supply at least one output file\n");
2988 if (nb_input_files == 0) {
2993 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2994 stream_maps, nb_stream_maps);
2995 ti = getutime() - ti;
2997 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3001 for(i=0;i<nb_output_files;i++) {
3002 /* maybe av_close_output_file ??? */
3003 AVFormatContext *s = output_files[i];
3005 if (!(s->oformat->flags & AVFMT_NOFILE))
3007 for(j=0;j<s->nb_streams;j++)
3008 av_free(s->streams[j]);
3011 for(i=0;i<nb_input_files;i++)
3012 av_close_input_file(input_files[i]);
3017 av_free(intra_matrix);
3019 av_free(inter_matrix);
3021 #ifdef POWERPC_PERFORMANCE_REPORT
3022 extern void powerpc_display_perf_report(void);
3023 powerpc_display_perf_report();
3024 #endif /* POWERPC_PERFORMANCE_REPORT */
3026 #ifndef CONFIG_WIN32
3027 if (received_sigterm) {
3029 "Received signal %d: terminating.\n",
3030 (int) received_sigterm);
3034 exit(0); /* not all OS-es handle main() return value */