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 mb_cmp = FF_CMP_SAD;
115 static int sub_cmp = FF_CMP_SAD;
116 static int cmp = FF_CMP_SAD;
117 static int use_4mv = 0;
118 static int use_obmc = 0;
119 static int use_aic = 0;
120 static int use_aiv = 0;
121 static int use_umv = 0;
122 static int use_alt_scan = 0;
123 static int use_trell = 0;
124 static int use_scan_offset = 0;
125 static int do_deinterlace = 0;
126 static int do_interlace_dct = 0;
127 static int do_interlace_me = 0;
128 static int workaround_bugs = FF_BUG_AUTODETECT;
129 static int error_resilience = 2;
130 static int error_concealment = 3;
131 static int dct_algo = 0;
132 static int idct_algo = 0;
133 static int use_part = 0;
134 static int packet_size = 0;
135 static int error_rate = 0;
136 static int strict = 0;
137 static int top_field_first = -1;
138 static int noise_reduction = 0;
139 static int debug = 0;
140 static int debug_mv = 0;
141 extern int loop_input; /* currently a hack */
143 static int gop_size = 12;
144 static int intra_only = 0;
145 static int audio_sample_rate = 44100;
146 static int audio_bit_rate = 64000;
147 static int audio_disable = 0;
148 static int audio_channels = 1;
149 static int audio_codec_id = CODEC_ID_NONE;
151 static int64_t recording_time = 0;
152 static int64_t start_time = 0;
153 static int file_overwrite = 0;
154 static char *str_title = NULL;
155 static char *str_author = NULL;
156 static char *str_copyright = NULL;
157 static char *str_comment = NULL;
158 static int do_benchmark = 0;
159 static int do_hex_dump = 0;
160 static int do_pkt_dump = 0;
161 static int do_psnr = 0;
162 static int do_vstats = 0;
163 static int do_pass = 0;
164 static int bitexact = 0;
165 static char *pass_logfilename = NULL;
166 static int audio_stream_copy = 0;
167 static int video_stream_copy = 0;
169 static int rate_emu = 0;
171 static char *video_grab_format = "video4linux";
172 static char *video_device = NULL;
173 static int video_channel = 0;
174 static char *video_standard = "ntsc";
176 static char *audio_grab_format = "audio_device";
177 static char *audio_device = NULL;
179 static int using_stdin = 0;
180 static int using_vhook = 0;
181 static int verbose = 1;
183 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
185 typedef struct AVOutputStream {
186 int file_index; /* file index */
187 int index; /* stream index in the output file */
188 int source_index; /* AVInputStream index */
189 AVStream *st; /* stream in the output file */
190 int encoding_needed; /* true if encoding needed for this stream */
192 /* input pts and corresponding output pts
195 double sync_ipts_offset;
198 int video_resample; /* video_resample and video_crop are mutually exclusive */
199 AVPicture pict_tmp; /* temporary image for resampling */
200 ImgReSampleContext *img_resample_ctx; /* for image resampling */
202 int video_crop; /* video_resample and video_crop are mutually exclusive */
203 int topBand; /* cropping area sizes */
208 ReSampleContext *resample; /* for audio resampling */
209 FifoBuffer fifo; /* for compression: one audio fifo per codec */
213 typedef struct AVInputStream {
217 int discard; /* true if stream data should be discarded */
218 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
219 int64_t sample_index; /* current sample */
221 int64_t start; /* time when read started */
222 unsigned long frame; /* current frame */
223 int64_t next_pts; /* synthetic pts for cases where pkt.pts
225 int64_t pts; /* current pts */
228 typedef struct AVInputFile {
229 int eof_reached; /* true if eof reached */
230 int ist_index; /* index of first stream in ist_table */
231 int buffer_size; /* current total buffer size */
232 int buffer_size_max; /* buffer size at which we consider we can stop
234 int nb_streams; /* nb streams we are aware of */
239 /* init terminal so that we can grab keys */
240 static struct termios oldtty;
242 static void term_exit(void)
244 tcsetattr (0, TCSANOW, &oldtty);
247 static volatile sig_atomic_t received_sigterm = 0;
250 sigterm_handler(int sig)
252 received_sigterm = sig;
256 static void term_init(void)
263 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
264 |INLCR|IGNCR|ICRNL|IXON);
265 tty.c_oflag |= OPOST;
266 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
267 tty.c_cflag &= ~(CSIZE|PARENB);
272 tcsetattr (0, TCSANOW, &tty);
274 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
275 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
276 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
278 register a function to be called at normal program termination
281 #ifdef CONFIG_BEOS_NETSERVER
282 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
286 /* read a key without blocking */
287 static int read_key(void)
291 #ifndef CONFIG_BEOS_NETSERVER
299 n = select(1, &rfds, NULL, NULL, &tv);
313 static volatile int received_sigterm = 0;
315 /* no interactive support */
316 static void term_exit(void)
320 static void term_init(void)
324 static int read_key(void)
331 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
336 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
339 /* copy stream format */
340 s->nb_streams = ic->nb_streams;
341 for(i=0;i<ic->nb_streams;i++) {
344 st = av_mallocz(sizeof(AVStream));
345 memcpy(st, ic->streams[i], sizeof(AVStream));
349 av_close_input_file(ic);
353 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
355 static void do_audio_out(AVFormatContext *s,
358 unsigned char *buf, int size)
361 static uint8_t *audio_buf = NULL;
362 static uint8_t *audio_out = NULL;
363 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
365 int size_out, frame_bytes, ret;
368 /* SC: dynamic allocation of buffers */
370 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
372 audio_out = av_malloc(audio_out_size);
373 if (!audio_buf || !audio_out)
374 return; /* Should signal an error ! */
377 enc = &ost->st->codec;
379 if (ost->audio_resample) {
381 size_out = audio_resample(ost->resample,
382 (short *)buftmp, (short *)buf,
383 size / (ist->st->codec.channels * 2));
384 size_out = size_out * enc->channels * 2;
390 /* now encode as many frames as possible */
391 if (enc->frame_size > 1) {
392 /* output resampled raw samples */
393 fifo_write(&ost->fifo, buftmp, size_out,
396 frame_bytes = enc->frame_size * 2 * enc->channels;
398 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
399 &ost->fifo.rptr) == 0) {
400 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
402 av_write_frame(s, ost->index, audio_out, ret);
405 /* output a pcm frame */
406 /* XXX: change encoding codec API to avoid this ? */
407 switch(enc->codec->id) {
408 case CODEC_ID_PCM_S16LE:
409 case CODEC_ID_PCM_S16BE:
410 case CODEC_ID_PCM_U16LE:
411 case CODEC_ID_PCM_U16BE:
414 size_out = size_out >> 1;
417 ret = avcodec_encode_audio(enc, audio_out, size_out,
419 av_write_frame(s, ost->index, audio_out, ret);
423 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
427 AVPicture picture_tmp;
430 dec = &ist->st->codec;
432 /* deinterlace : must be done before any resize */
433 if (do_deinterlace || using_vhook) {
436 /* create temporary picture */
437 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
438 buf = av_malloc(size);
442 picture2 = &picture_tmp;
443 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
446 if(avpicture_deinterlace(picture2, picture,
447 dec->pix_fmt, dec->width, dec->height) < 0) {
448 /* if error, do not deinterlace */
454 if (img_convert(picture2, dec->pix_fmt, picture,
455 dec->pix_fmt, dec->width, dec->height) < 0) {
456 /* if error, do not copy */
466 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
468 if (picture != picture2)
469 *picture = *picture2;
473 /* we begin to correct av delay at this threshold */
474 #define AV_DELAY_MAX 0.100
476 static void do_video_out(AVFormatContext *s,
480 int *frame_size, AVOutputStream *audio_sync)
482 int nb_frames, i, ret;
483 AVPicture *final_picture, *formatted_picture;
484 AVPicture picture_format_temp, picture_crop_temp;
485 static uint8_t *video_buffer;
486 uint8_t *buf = NULL, *buf1 = NULL;
487 AVCodecContext *enc, *dec;
488 enum PixelFormat target_pixfmt;
490 #define VIDEO_BUFFER_SIZE (1024*1024)
492 enc = &ost->st->codec;
493 dec = &ist->st->codec;
495 /* by default, we output a single frame */
500 /* NOTE: the A/V sync is always done by considering the audio is
501 the master clock. It is suffisant for transcoding or playing,
502 but not for the general case */
504 /* compute the A-V delay and duplicate/remove frames if needed */
505 double adelta, vdelta, av_delay;
507 adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts *
508 s->pts_num / s->pts_den);
510 vdelta = ost->sync_ipts - ((double)ost->sync_opts *
511 s->pts_num / s->pts_den);
513 av_delay = adelta - vdelta;
514 // printf("delay=%f\n", av_delay);
515 if (av_delay < -AV_DELAY_MAX)
517 else if (av_delay > AV_DELAY_MAX)
522 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
523 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
524 if (vdelta < -AV_DELAY_MAX)
526 else if (vdelta > AV_DELAY_MAX)
529 ost->sync_ipts_offset -= vdelta;
530 if (!ost->sync_ipts_offset)
531 ost->sync_ipts_offset = 0.000001; /* one microsecond */
535 #if defined(AVSYNC_DEBUG)
537 static char *action[] = { "drop frame", "copy frame", "dup frame" };
539 fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
540 (double) audio_sync->sync_ipts,
541 (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
542 fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
543 (double) ost->sync_ipts,
544 (double) ost->st->pts.val * s->pts_num / s->pts_den,
553 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
557 /* convert pixel format if needed */
558 target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
559 if (dec->pix_fmt != target_pixfmt) {
562 /* create temporary picture */
563 size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
564 buf = av_malloc(size);
567 formatted_picture = &picture_format_temp;
568 avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
570 if (img_convert(formatted_picture, target_pixfmt,
571 (AVPicture *)in_picture, dec->pix_fmt,
572 dec->width, dec->height) < 0) {
573 fprintf(stderr, "pixel format conversion not handled\n");
577 formatted_picture = (AVPicture *)in_picture;
580 /* XXX: resampling could be done before raw format convertion in
581 some cases to go faster */
582 /* XXX: only works for YUV420P */
583 if (ost->video_resample) {
584 final_picture = &ost->pict_tmp;
585 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
586 if (enc->pix_fmt != PIX_FMT_YUV420P) {
590 /* create temporary picture */
591 size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
592 buf = av_malloc(size);
595 final_picture = &picture_format_temp;
596 avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
598 if (img_convert(final_picture, enc->pix_fmt,
599 &ost->pict_tmp, PIX_FMT_YUV420P,
600 enc->width, enc->height) < 0) {
601 fprintf(stderr, "pixel format conversion not handled\n");
605 } else if (ost->video_crop) {
606 picture_crop_temp.data[0] = formatted_picture->data[0] +
607 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
609 picture_crop_temp.data[1] = formatted_picture->data[1] +
610 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
611 (ost->leftBand >> 1);
613 picture_crop_temp.data[2] = formatted_picture->data[2] +
614 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
615 (ost->leftBand >> 1);
617 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
618 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
619 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
620 final_picture = &picture_crop_temp;
622 final_picture = formatted_picture;
624 /* duplicates frame if needed */
625 /* XXX: pb because no interleaving */
626 for(i=0;i<nb_frames;i++) {
627 if (s->oformat->flags & AVFMT_RAWPICTURE) {
628 /* raw pictures are written as AVPicture structure to
629 avoid any copies. We support temorarily the older
631 AVFrame* old_frame = enc->coded_frame;
632 enc->coded_frame = dec->coded_frame;
633 av_write_frame(s, ost->index,
634 (uint8_t *)final_picture, sizeof(AVPicture));
635 enc->coded_frame = old_frame;
639 memset(&big_picture, 0, sizeof(AVFrame));
640 *(AVPicture*)&big_picture= *final_picture;
641 /* better than nothing: use input picture interlaced
643 big_picture.interlaced_frame = in_picture->interlaced_frame;
644 if(do_interlace_me || do_interlace_dct){
645 if(top_field_first == -1)
646 big_picture.top_field_first = in_picture->top_field_first;
648 big_picture.top_field_first = 1;
651 /* handles sameq here. This is not correct because it may
652 not be a global option */
654 big_picture.quality = ist->st->quality;
656 big_picture.quality = ost->st->quality;
658 ret = avcodec_encode_video(enc,
659 video_buffer, VIDEO_BUFFER_SIZE,
661 //enc->frame_number = enc->real_pict_num;
662 av_write_frame(s, ost->index, video_buffer, ret);
664 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
665 // enc->frame_number-1, enc->real_pict_num, ret,
667 /* if two pass, output log */
668 if (ost->logfile && enc->stats_out) {
669 fprintf(ost->logfile, "%s", enc->stats_out);
679 static double psnr(double d){
680 if(d==0) return INFINITY;
681 return -10.0*log(d)/log(10.0);
684 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
687 static FILE *fvstats=NULL;
688 static int64_t total_size = 0;
695 double ti1, bitrate, avg_bitrate;
699 today = localtime(&today2);
700 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
703 fvstats = fopen(filename,"w");
711 enc = &ost->st->codec;
712 total_size += frame_size;
713 if (enc->codec_type == CODEC_TYPE_VIDEO) {
714 frame_number = ost->frame_number;
715 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
716 if (enc->flags&CODEC_FLAG_PSNR)
717 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
719 fprintf(fvstats,"f_size= %6d ", frame_size);
720 /* compute pts value */
721 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
725 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
726 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
727 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
728 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
729 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
733 static void print_report(AVFormatContext **output_files,
734 AVOutputStream **ost_table, int nb_ostreams,
739 AVFormatContext *oc, *os;
742 int frame_number, vid, i;
743 double bitrate, ti1, pts;
744 static int64_t last_time = -1;
746 if (!is_last_report) {
748 /* display the report every 0.5 seconds */
749 cur_time = av_gettime();
750 if (last_time == -1) {
751 last_time = cur_time;
754 if ((cur_time - last_time) < 500000)
756 last_time = cur_time;
760 oc = output_files[0];
762 total_size = url_ftell(&oc->pb);
767 for(i=0;i<nb_ostreams;i++) {
769 os = output_files[ost->file_index];
770 enc = &ost->st->codec;
771 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
772 sprintf(buf + strlen(buf), "q=%2.1f ",
773 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
775 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
776 frame_number = ost->frame_number;
777 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
778 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
780 sprintf(buf + strlen(buf), "L");
781 if (enc->flags&CODEC_FLAG_PSNR){
783 double error, error_sum=0;
784 double scale, scale_sum=0;
785 char type[3]= {'Y','U','V'};
786 sprintf(buf + strlen(buf), "PSNR=");
789 error= enc->error[j];
790 scale= enc->width*enc->height*255.0*255.0*frame_number;
792 error= enc->coded_frame->error[j];
793 scale= enc->width*enc->height*255.0*255.0;
798 sprintf(buf + strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
800 sprintf(buf + strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
804 /* compute min output value */
805 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
806 if ((pts < ti1) && (pts > 0))
812 if (verbose || is_last_report) {
813 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
815 sprintf(buf + strlen(buf),
816 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
817 (double)total_size / 1024, ti1, bitrate);
819 fprintf(stderr, "%s \r", buf);
824 fprintf(stderr, "\n");
827 /* pkt = NULL means EOF (needed to flush decoder buffers) */
828 static int output_packet(AVInputStream *ist, int ist_index,
829 AVOutputStream **ost_table, int nb_ostreams,
837 int data_size, got_picture;
839 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
840 void *buffer_to_free;
842 if (pkt && pkt->pts != AV_NOPTS_VALUE) {
845 ist->pts = ist->next_pts;
859 /* decode the packet if needed */
860 data_buf = NULL; /* fail safe */
862 if (ist->decoding_needed) {
863 switch(ist->st->codec.codec_type) {
864 case CODEC_TYPE_AUDIO:
865 /* XXX: could avoid copy if PCM 16 bits with same
867 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
873 /* Some bug in mpeg audio decoder gives */
874 /* data_size < 0, it seems they are overflows */
875 if (data_size <= 0) {
879 data_buf = (uint8_t *)samples;
880 ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) /
881 (2 * ist->st->codec.channels);
883 case CODEC_TYPE_VIDEO:
884 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
885 /* XXX: allocate picture correctly */
886 memset(&picture, 0, sizeof(picture));
887 ret = avcodec_decode_video(&ist->st->codec,
888 &picture, &got_picture, ptr, len);
889 ist->st->quality= picture.quality;
896 if (ist->st->codec.frame_rate_base != 0) {
897 ist->next_pts += ((int64_t)AV_TIME_BASE *
898 ist->st->codec.frame_rate_base) /
899 ist->st->codec.frame_rate;
913 buffer_to_free = NULL;
914 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
915 pre_process_video_frame(ist, (AVPicture *)&picture,
919 /* frame rate emulation */
920 if (ist->st->codec.rate_emu) {
921 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
922 int64_t now = av_gettime() - ist->start;
930 /* mpeg PTS deordering : if it is a P or I frame, the PTS
931 is the one of the next displayed one */
932 /* XXX: add mpeg4 too ? */
933 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
934 if (ist->st->codec.pict_type != B_TYPE) {
936 tmp = ist->last_ip_pts;
937 ist->last_ip_pts = ist->frac_pts.val;
938 ist->frac_pts.val = tmp;
942 /* if output time reached then transcode raw format,
943 encode packets and output them */
944 if (start_time == 0 || ist->pts >= start_time)
945 for(i=0;i<nb_ostreams;i++) {
949 if (ost->source_index == ist_index) {
950 os = output_files[ost->file_index];
953 printf("%d: got pts=%0.3f %0.3f\n", i,
954 (double)pkt->pts / AV_TIME_BASE,
955 ((double)ist->pts / AV_TIME_BASE) -
956 ((double)ost->st->pts.val * os->pts_num / os->pts_den));
958 /* set the input output pts pairs */
959 ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
960 /* XXX: take into account the various fifos,
961 in particular for audio */
962 ost->sync_opts = ost->st->pts.val;
963 //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);
965 if (ost->encoding_needed) {
966 switch(ost->st->codec.codec_type) {
967 case CODEC_TYPE_AUDIO:
968 do_audio_out(os, ost, ist, data_buf, data_size);
970 case CODEC_TYPE_VIDEO:
971 /* find an audio stream for synchro */
974 AVOutputStream *audio_sync, *ost1;
976 for(i=0;i<nb_ostreams;i++) {
978 if (ost1->file_index == ost->file_index &&
979 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
985 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
986 if (do_vstats && frame_size)
987 do_video_stats(os, ost, frame_size);
996 /* no reencoding needed : output the packet directly */
997 /* force the input stream PTS */
999 memset(&avframe, 0, sizeof(AVFrame));
1000 ost->st->codec.coded_frame= &avframe;
1001 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1003 av_write_frame(os, ost->index, data_buf, data_size);
1004 ost->st->codec.frame_number++;
1005 ost->frame_number++;
1009 av_free(buffer_to_free);
1019 * The following code is the main loop of the file converter
1021 static int av_encode(AVFormatContext **output_files,
1022 int nb_output_files,
1023 AVFormatContext **input_files,
1025 AVStreamMap *stream_maps, int nb_stream_maps)
1027 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1028 AVFormatContext *is, *os;
1029 AVCodecContext *codec, *icodec;
1030 AVOutputStream *ost, **ost_table = NULL;
1031 AVInputStream *ist, **ist_table = NULL;
1032 AVInputFile *file_table;
1033 AVFormatContext *stream_no_data;
1036 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1040 /* input stream init */
1042 for(i=0;i<nb_input_files;i++) {
1043 is = input_files[i];
1044 file_table[i].ist_index = j;
1045 file_table[i].nb_streams = is->nb_streams;
1046 j += is->nb_streams;
1050 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1054 for(i=0;i<nb_istreams;i++) {
1055 ist = av_mallocz(sizeof(AVInputStream));
1061 for(i=0;i<nb_input_files;i++) {
1062 is = input_files[i];
1063 for(k=0;k<is->nb_streams;k++) {
1064 ist = ist_table[j++];
1065 ist->st = is->streams[k];
1066 ist->file_index = i;
1068 ist->discard = 1; /* the stream is discarded by default
1071 if (ist->st->codec.rate_emu) {
1072 ist->start = av_gettime();
1078 /* output stream init */
1080 for(i=0;i<nb_output_files;i++) {
1081 os = output_files[i];
1082 nb_ostreams += os->nb_streams;
1084 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1085 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1089 /* Sanity check the mapping args -- do the input files & streams exist? */
1090 for(i=0;i<nb_stream_maps;i++) {
1091 int fi = stream_maps[i].file_index;
1092 int si = stream_maps[i].stream_index;
1094 if (fi < 0 || fi > nb_input_files - 1 ||
1095 si < 0 || si > file_table[fi].nb_streams - 1) {
1096 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1101 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1104 for(i=0;i<nb_ostreams;i++) {
1105 ost = av_mallocz(sizeof(AVOutputStream));
1112 for(k=0;k<nb_output_files;k++) {
1113 os = output_files[k];
1114 for(i=0;i<os->nb_streams;i++) {
1116 ost = ost_table[n++];
1117 ost->file_index = k;
1119 ost->st = os->streams[i];
1120 if (nb_stream_maps > 0) {
1121 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1122 stream_maps[n-1].stream_index;
1124 /* Sanity check that the stream types match */
1125 if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1126 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1127 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1128 ost->file_index, ost->index);
1133 /* get corresponding input stream index : we select the first one with the right type */
1135 for(j=0;j<nb_istreams;j++) {
1138 ist->st->codec.codec_type == ost->st->codec.codec_type) {
1139 ost->source_index = j;
1145 /* try again and reuse existing stream */
1146 for(j=0;j<nb_istreams;j++) {
1148 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1149 ost->source_index = j;
1154 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1155 ost->file_index, ost->index);
1160 ist = ist_table[ost->source_index];
1165 /* for each output stream, we compute the right encoding parameters */
1166 for(i=0;i<nb_ostreams;i++) {
1168 ist = ist_table[ost->source_index];
1170 codec = &ost->st->codec;
1171 icodec = &ist->st->codec;
1173 if (ost->st->stream_copy) {
1174 /* if stream_copy is selected, no need to decode or encode */
1175 codec->codec_id = icodec->codec_id;
1176 codec->codec_type = icodec->codec_type;
1177 codec->codec_tag = icodec->codec_tag;
1178 codec->bit_rate = icodec->bit_rate;
1179 switch(codec->codec_type) {
1180 case CODEC_TYPE_AUDIO:
1181 codec->sample_rate = icodec->sample_rate;
1182 codec->channels = icodec->channels;
1184 case CODEC_TYPE_VIDEO:
1185 codec->frame_rate = icodec->frame_rate;
1186 codec->frame_rate_base = icodec->frame_rate_base;
1187 codec->width = icodec->width;
1188 codec->height = icodec->height;
1194 switch(codec->codec_type) {
1195 case CODEC_TYPE_AUDIO:
1196 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1199 if (codec->channels == icodec->channels &&
1200 codec->sample_rate == icodec->sample_rate) {
1201 ost->audio_resample = 0;
1203 if (codec->channels != icodec->channels &&
1204 icodec->codec_id == CODEC_ID_AC3) {
1205 /* Special case for 5:1 AC3 input */
1206 /* and mono or stereo output */
1207 /* Request specific number of channels */
1208 icodec->channels = codec->channels;
1209 if (codec->sample_rate == icodec->sample_rate)
1210 ost->audio_resample = 0;
1212 ost->audio_resample = 1;
1213 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1215 icodec->sample_rate);
1218 printf("Can't resample. Aborting.\n");
1222 /* Request specific number of channels */
1223 icodec->channels = codec->channels;
1225 ost->audio_resample = 1;
1226 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1228 icodec->sample_rate);
1231 printf("Can't resample. Aborting.\n");
1236 ist->decoding_needed = 1;
1237 ost->encoding_needed = 1;
1239 case CODEC_TYPE_VIDEO:
1240 if (codec->width == icodec->width &&
1241 codec->height == icodec->height &&
1242 frame_topBand == 0 &&
1243 frame_bottomBand == 0 &&
1244 frame_leftBand == 0 &&
1245 frame_rightBand == 0)
1247 ost->video_resample = 0;
1248 ost->video_crop = 0;
1249 } else if ((codec->width == icodec->width -
1250 (frame_leftBand + frame_rightBand)) &&
1251 (codec->height == icodec->height -
1252 (frame_topBand + frame_bottomBand)))
1254 ost->video_resample = 0;
1255 ost->video_crop = 1;
1256 ost->topBand = frame_topBand;
1257 ost->leftBand = frame_leftBand;
1260 ost->video_resample = 1;
1261 ost->video_crop = 0; // cropping is handled as part of resample
1262 buf = av_malloc((codec->width * codec->height * 3) / 2);
1265 ost->pict_tmp.data[0] = buf;
1266 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1267 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1268 ost->pict_tmp.linesize[0] = codec->width;
1269 ost->pict_tmp.linesize[1] = codec->width / 2;
1270 ost->pict_tmp.linesize[2] = codec->width / 2;
1272 ost->img_resample_ctx = img_resample_full_init(
1273 ost->st->codec.width, ost->st->codec.height,
1274 ist->st->codec.width, ist->st->codec.height,
1275 frame_topBand, frame_bottomBand,
1276 frame_leftBand, frame_rightBand);
1278 ost->encoding_needed = 1;
1279 ist->decoding_needed = 1;
1285 if (ost->encoding_needed &&
1286 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1287 char logfilename[1024];
1292 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1294 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1295 if (codec->flags & CODEC_FLAG_PASS1) {
1296 f = fopen(logfilename, "w");
1298 perror(logfilename);
1303 /* read the log file */
1304 f = fopen(logfilename, "r");
1306 perror(logfilename);
1309 fseek(f, 0, SEEK_END);
1311 fseek(f, 0, SEEK_SET);
1312 logbuffer = av_malloc(size + 1);
1314 fprintf(stderr, "Could not allocate log buffer\n");
1317 fread(logbuffer, 1, size, f);
1319 logbuffer[size] = '\0';
1320 codec->stats_in = logbuffer;
1326 /* dump the file output parameters - cannot be done before in case
1328 for(i=0;i<nb_output_files;i++) {
1329 dump_format(output_files[i], i, output_files[i]->filename, 1);
1332 /* dump the stream mapping */
1333 fprintf(stderr, "Stream mapping:\n");
1334 for(i=0;i<nb_ostreams;i++) {
1336 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1337 ist_table[ost->source_index]->file_index,
1338 ist_table[ost->source_index]->index,
1343 /* open each encoder */
1344 for(i=0;i<nb_ostreams;i++) {
1346 if (ost->encoding_needed) {
1348 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1350 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1351 ost->file_index, ost->index);
1354 if (avcodec_open(&ost->st->codec, codec) < 0) {
1355 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1356 ost->file_index, ost->index);
1362 /* open each decoder */
1363 for(i=0;i<nb_istreams;i++) {
1365 if (ist->decoding_needed) {
1367 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1369 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1370 ist->st->codec.codec_id, ist->file_index, ist->index);
1373 if (avcodec_open(&ist->st->codec, codec) < 0) {
1374 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1375 ist->file_index, ist->index);
1378 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1379 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1384 for(i=0;i<nb_istreams;i++) {
1386 is = input_files[ist->file_index];
1391 /* compute buffer size max (should use a complete heuristic) */
1392 for(i=0;i<nb_input_files;i++) {
1393 file_table[i].buffer_size_max = 2048;
1396 /* open files and write file headers */
1397 for(i=0;i<nb_output_files;i++) {
1398 os = output_files[i];
1399 if (av_write_header(os) < 0) {
1400 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1406 #ifndef CONFIG_WIN32
1408 fprintf(stderr, "Press [q] to stop encoding\n");
1415 for(; received_sigterm == 0;) {
1416 int file_index, ist_index;
1421 /* if 'q' pressed, exits */
1423 /* read_key() returns 0 on EOF */
1429 /* select the stream that we must read now by looking at the
1430 smallest output pts */
1433 for(i=0;i<nb_ostreams;i++) {
1436 os = output_files[ost->file_index];
1437 ist = ist_table[ost->source_index];
1438 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1439 if (!file_table[ist->file_index].eof_reached &&
1442 file_index = ist->file_index;
1445 /* if none, if is finished */
1446 if (file_index < 0) {
1450 /* finish if recording time exhausted */
1451 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1454 /* read a frame from it and output it in the fifo */
1455 is = input_files[file_index];
1456 if (av_read_frame(is, &pkt) < 0) {
1457 file_table[file_index].eof_reached = 1;
1461 stream_no_data = is;
1466 av_pkt_dump(stdout, &pkt, do_hex_dump);
1468 /* the following test is needed in case new streams appear
1469 dynamically in stream : we ignore them */
1470 if (pkt.stream_index >= file_table[file_index].nb_streams)
1471 goto discard_packet;
1472 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1473 ist = ist_table[ist_index];
1475 goto discard_packet;
1477 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1478 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1479 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1480 ist->file_index, ist->index);
1481 av_free_packet(&pkt);
1486 av_free_packet(&pkt);
1488 /* dump report by using the output first video and audio streams */
1489 print_report(output_files, ost_table, nb_ostreams, 0);
1492 /* at the end of stream, we must flush the decoder buffers */
1493 for(i=0;i<nb_istreams;i++) {
1495 if (ist->decoding_needed) {
1496 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1502 /* dump report by using the first video and audio streams */
1503 print_report(output_files, ost_table, nb_ostreams, 1);
1505 /* close each encoder */
1506 for(i=0;i<nb_ostreams;i++) {
1508 if (ost->encoding_needed) {
1509 av_freep(&ost->st->codec.stats_in);
1510 avcodec_close(&ost->st->codec);
1514 /* close each decoder */
1515 for(i=0;i<nb_istreams;i++) {
1517 if (ist->decoding_needed) {
1518 avcodec_close(&ist->st->codec);
1523 /* write the trailer if needed and close file */
1524 for(i=0;i<nb_output_files;i++) {
1525 os = output_files[i];
1526 av_write_trailer(os);
1532 av_free(file_table);
1535 for(i=0;i<nb_istreams;i++) {
1542 for(i=0;i<nb_ostreams;i++) {
1546 fclose(ost->logfile);
1547 ost->logfile = NULL;
1549 fifo_free(&ost->fifo); /* works even if fifo is not
1550 initialized but set to zero */
1551 av_free(ost->pict_tmp.data[0]);
1552 if (ost->video_resample)
1553 img_resample_close(ost->img_resample_ctx);
1554 if (ost->audio_resample)
1555 audio_resample_close(ost->resample);
1568 int file_read(const char *filename)
1571 unsigned char buffer[1024];
1574 if (url_open(&h, filename, O_RDONLY) < 0) {
1575 printf("could not open '%s'\n", filename);
1579 len = url_read(h, buffer, sizeof(buffer));
1582 for(i=0;i<len;i++) putchar(buffer[i]);
1589 static void opt_image_format(const char *arg)
1593 for(f = first_image_format; f != NULL; f = f->next) {
1594 if (!strcmp(arg, f->name))
1598 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1604 static void opt_format(const char *arg)
1606 /* compatibility stuff for pgmyuv */
1607 if (!strcmp(arg, "pgmyuv")) {
1608 opt_image_format(arg);
1612 file_iformat = av_find_input_format(arg);
1613 file_oformat = guess_format(arg, NULL, NULL);
1614 if (!file_iformat && !file_oformat) {
1615 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1620 static void opt_video_bitrate(const char *arg)
1622 video_bit_rate = atoi(arg) * 1000;
1625 static void opt_video_bitrate_tolerance(const char *arg)
1627 video_bit_rate_tolerance = atoi(arg) * 1000;
1630 static void opt_video_bitrate_max(const char *arg)
1632 video_rc_max_rate = atoi(arg) * 1000;
1635 static void opt_video_bitrate_min(const char *arg)
1637 video_rc_min_rate = atoi(arg) * 1000;
1640 static void opt_video_buffer_size(const char *arg)
1642 video_rc_buffer_size = atoi(arg) * 1024;
1645 static void opt_video_rc_eq(char *arg)
1650 static void opt_video_rc_override_string(char *arg)
1652 video_rc_override_string = arg;
1656 static void opt_workaround_bugs(const char *arg)
1658 workaround_bugs = atoi(arg);
1661 static void opt_dct_algo(const char *arg)
1663 dct_algo = atoi(arg);
1666 static void opt_idct_algo(const char *arg)
1668 idct_algo = atoi(arg);
1672 static void opt_error_resilience(const char *arg)
1674 error_resilience = atoi(arg);
1677 static void opt_error_concealment(const char *arg)
1679 error_concealment = atoi(arg);
1682 static void opt_debug(const char *arg)
1687 static void opt_vismv(const char *arg)
1689 debug_mv = atoi(arg);
1692 static void opt_verbose(const char *arg)
1694 verbose = atoi(arg);
1697 static void opt_frame_rate(const char *arg)
1699 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1700 fprintf(stderr, "Incorrect frame rate\n");
1705 static void opt_frame_crop_top(const char *arg)
1707 frame_topBand = atoi(arg);
1708 if (frame_topBand < 0) {
1709 fprintf(stderr, "Incorrect top crop size\n");
1712 if ((frame_topBand % 2) != 0) {
1713 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1716 if ((frame_topBand) >= frame_height){
1717 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1720 frame_height -= frame_topBand;
1723 static void opt_frame_crop_bottom(const char *arg)
1725 frame_bottomBand = atoi(arg);
1726 if (frame_bottomBand < 0) {
1727 fprintf(stderr, "Incorrect bottom crop size\n");
1730 if ((frame_bottomBand % 2) != 0) {
1731 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1734 if ((frame_bottomBand) >= frame_height){
1735 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1738 frame_height -= frame_bottomBand;
1741 static void opt_frame_crop_left(const char *arg)
1743 frame_leftBand = atoi(arg);
1744 if (frame_leftBand < 0) {
1745 fprintf(stderr, "Incorrect left crop size\n");
1748 if ((frame_leftBand % 2) != 0) {
1749 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1752 if ((frame_leftBand) >= frame_width){
1753 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1756 frame_width -= frame_leftBand;
1759 static void opt_frame_crop_right(const char *arg)
1761 frame_rightBand = atoi(arg);
1762 if (frame_rightBand < 0) {
1763 fprintf(stderr, "Incorrect right crop size\n");
1766 if ((frame_rightBand % 2) != 0) {
1767 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1770 if ((frame_rightBand) >= frame_width){
1771 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1774 frame_width -= frame_rightBand;
1777 static void opt_frame_size(const char *arg)
1779 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1780 fprintf(stderr, "Incorrect frame size\n");
1783 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1784 fprintf(stderr, "Frame size must be a multiple of 2\n");
1789 static void opt_frame_pix_fmt(const char *arg)
1791 frame_pix_fmt = avcodec_get_pix_fmt(arg);
1794 static void opt_frame_aspect_ratio(const char *arg)
1800 p = strchr(arg, ':');
1802 x = strtol(arg, (char **)&arg, 10);
1804 y = strtol(arg+1, (char **)&arg, 10);
1806 ar = (double)x / (double)y;
1808 ar = strtod(arg, (char **)&arg);
1811 fprintf(stderr, "Incorrect aspect ratio specification.\n");
1814 frame_aspect_ratio = ar;
1817 static void opt_gop_size(const char *arg)
1819 gop_size = atoi(arg);
1822 static void opt_b_frames(const char *arg)
1824 b_frames = atoi(arg);
1825 if (b_frames > FF_MAX_B_FRAMES) {
1826 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1828 } else if (b_frames < 1) {
1829 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1834 static void opt_mb_decision(const char *arg)
1836 mb_decision = atoi(arg);
1839 static void opt_mb_cmp(const char *arg)
1844 static void opt_sub_cmp(const char *arg)
1846 sub_cmp = atoi(arg);
1849 static void opt_cmp(const char *arg)
1854 static void opt_qscale(const char *arg)
1856 video_qscale = atof(arg);
1857 if (video_qscale < 0.01 ||
1858 video_qscale > 255) {
1859 fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1864 static void opt_qmin(const char *arg)
1866 video_qmin = atoi(arg);
1867 if (video_qmin < 0 ||
1869 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1874 static void opt_qmax(const char *arg)
1876 video_qmax = atoi(arg);
1877 if (video_qmax < 0 ||
1879 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1884 static void opt_mb_qmin(const char *arg)
1886 video_mb_qmin = atoi(arg);
1887 if (video_mb_qmin < 0 ||
1888 video_mb_qmin > 31) {
1889 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1894 static void opt_mb_qmax(const char *arg)
1896 video_mb_qmax = atoi(arg);
1897 if (video_mb_qmax < 0 ||
1898 video_mb_qmax > 31) {
1899 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1904 static void opt_qdiff(const char *arg)
1906 video_qdiff = atoi(arg);
1907 if (video_qdiff < 0 ||
1909 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1914 static void opt_qblur(const char *arg)
1916 video_qblur = atof(arg);
1919 static void opt_qcomp(const char *arg)
1921 video_qcomp = atof(arg);
1924 static void opt_rc_initial_cplx(const char *arg)
1926 video_rc_initial_cplx = atof(arg);
1928 static void opt_b_qfactor(const char *arg)
1930 video_b_qfactor = atof(arg);
1932 static void opt_i_qfactor(const char *arg)
1934 video_i_qfactor = atof(arg);
1936 static void opt_b_qoffset(const char *arg)
1938 video_b_qoffset = atof(arg);
1940 static void opt_i_qoffset(const char *arg)
1942 video_i_qoffset = atof(arg);
1945 static void opt_packet_size(const char *arg)
1947 packet_size= atoi(arg);
1950 static void opt_error_rate(const char *arg)
1952 error_rate= atoi(arg);
1955 static void opt_strict(const char *arg)
1960 static void opt_top_field_first(const char *arg)
1962 top_field_first= atoi(arg);
1965 static void opt_noise_reduction(const char *arg)
1967 noise_reduction= atoi(arg);
1970 static void opt_audio_bitrate(const char *arg)
1972 audio_bit_rate = atoi(arg) * 1000;
1975 static void opt_audio_rate(const char *arg)
1977 audio_sample_rate = atoi(arg);
1980 static void opt_audio_channels(const char *arg)
1982 audio_channels = atoi(arg);
1985 static void opt_video_device(const char *arg)
1987 video_device = av_strdup(arg);
1990 static void opt_video_channel(const char *arg)
1992 video_channel = strtol(arg, NULL, 0);
1995 static void opt_video_standard(const char *arg)
1997 video_standard = av_strdup(arg);
2000 static void opt_audio_device(const char *arg)
2002 audio_device = av_strdup(arg);
2005 static void opt_dv1394(const char *arg)
2007 video_grab_format = "dv1394";
2008 audio_grab_format = NULL;
2011 static void opt_audio_codec(const char *arg)
2015 if (!strcmp(arg, "copy")) {
2016 audio_stream_copy = 1;
2020 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
2025 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
2028 audio_codec_id = p->id;
2033 static void add_frame_hooker(const char *arg)
2038 char *args = av_strdup(arg);
2042 argv[0] = strtok(args, " ");
2043 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2046 i = frame_hook_add(argc, argv);
2049 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2054 const char *motion_str[] = {
2064 static void opt_motion_estimation(const char *arg)
2070 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2073 if (!strcmp(*p, arg))
2077 me_method = (p - motion_str) + 1;
2080 static void opt_video_codec(const char *arg)
2084 if (!strcmp(arg, "copy")) {
2085 video_stream_copy = 1;
2089 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2094 fprintf(stderr, "Unknown video codec '%s'\n", arg);
2097 video_codec_id = p->id;
2102 static void opt_map(const char *arg)
2108 m = &stream_maps[nb_stream_maps++];
2110 m->file_index = strtol(arg, (char **)&p, 0);
2114 m->stream_index = strtol(p, (char **)&p, 0);
2117 static void opt_recording_time(const char *arg)
2119 recording_time = parse_date(arg, 1);
2122 static void opt_start_time(const char *arg)
2124 start_time = parse_date(arg, 1);
2127 static void opt_input_file(const char *filename)
2129 AVFormatContext *ic;
2130 AVFormatParameters params, *ap = ¶ms;
2131 int err, i, ret, rfps, rfps_base;
2133 if (!strcmp(filename, "-"))
2136 using_stdin |= !strcmp(filename, "pipe:" ) ||
2137 !strcmp( filename, "/dev/stdin" );
2139 /* get default parameters from command line */
2140 memset(ap, 0, sizeof(*ap));
2141 ap->sample_rate = audio_sample_rate;
2142 ap->channels = audio_channels;
2143 ap->frame_rate = frame_rate;
2144 ap->frame_rate_base = frame_rate_base;
2145 ap->width = frame_width;
2146 ap->height = frame_height;
2147 ap->image_format = image_format;
2148 ap->pix_fmt = frame_pix_fmt;
2150 /* open the input file with generic libav function */
2151 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2153 print_error(filename, err);
2157 /* If not enough info to get the stream parameters, we decode the
2158 first frames to get it. (used in mpeg case for example) */
2159 ret = av_find_stream_info(ic);
2161 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2165 /* if seeking requested, we execute it */
2166 if (start_time != 0) {
2169 timestamp = start_time;
2170 /* add the stream start time */
2171 if (ic->start_time != AV_NOPTS_VALUE)
2172 timestamp += ic->start_time;
2173 ret = av_seek_frame(ic, -1, timestamp);
2175 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2176 filename, (double)timestamp / AV_TIME_BASE);
2178 /* reset seek info */
2182 /* update the current parameters so that they match the one of the input stream */
2183 for(i=0;i<ic->nb_streams;i++) {
2184 AVCodecContext *enc = &ic->streams[i]->codec;
2185 switch(enc->codec_type) {
2186 case CODEC_TYPE_AUDIO:
2187 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2188 audio_channels = enc->channels;
2189 audio_sample_rate = enc->sample_rate;
2191 case CODEC_TYPE_VIDEO:
2192 frame_height = enc->height;
2193 frame_width = enc->width;
2194 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2195 frame_pix_fmt = enc->pix_fmt;
2196 rfps = ic->streams[i]->r_frame_rate;
2197 rfps_base = ic->streams[i]->r_frame_rate_base;
2198 enc->workaround_bugs = workaround_bugs;
2199 enc->error_resilience = error_resilience;
2200 enc->error_concealment = error_concealment;
2201 enc->idct_algo = idct_algo;
2203 enc->debug_mv = debug_mv;
2205 enc->flags|= CODEC_FLAG_BITEXACT;
2207 assert(enc->frame_rate_base == rfps_base); // should be true for now
2208 if (enc->frame_rate != rfps) {
2209 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2210 i, (float)enc->frame_rate / enc->frame_rate_base,
2211 (float)rfps / rfps_base);
2213 /* update the current frame rate to match the stream frame rate */
2215 frame_rate_base = rfps_base;
2217 enc->rate_emu = rate_emu;
2219 case CODEC_TYPE_DATA:
2226 input_files[nb_input_files] = ic;
2227 /* dump the file content */
2228 dump_format(ic, nb_input_files, filename, 0);
2230 file_iformat = NULL;
2231 file_oformat = NULL;
2232 image_format = NULL;
2237 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2239 int has_video, has_audio, i, j;
2240 AVFormatContext *ic;
2244 for(j=0;j<nb_input_files;j++) {
2245 ic = input_files[j];
2246 for(i=0;i<ic->nb_streams;i++) {
2247 AVCodecContext *enc = &ic->streams[i]->codec;
2248 switch(enc->codec_type) {
2249 case CODEC_TYPE_AUDIO:
2252 case CODEC_TYPE_VIDEO:
2260 *has_video_ptr = has_video;
2261 *has_audio_ptr = has_audio;
2264 static void opt_output_file(const char *filename)
2267 AVFormatContext *oc;
2268 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2270 AVFormatParameters params, *ap = ¶ms;
2272 if (!strcmp(filename, "-"))
2275 oc = av_mallocz(sizeof(AVFormatContext));
2277 if (!file_oformat) {
2278 file_oformat = guess_format(NULL, filename, NULL);
2279 if (!file_oformat) {
2280 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2286 oc->oformat = file_oformat;
2288 if (!strcmp(file_oformat->name, "ffm") &&
2289 strstart(filename, "http:", NULL)) {
2290 /* special case for files sent to ffserver: we get the stream
2291 parameters from ffserver */
2292 if (read_ffserver_streams(oc, filename) < 0) {
2293 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2297 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2298 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2300 /* disable if no corresponding type found and at least one
2302 if (nb_input_files > 0) {
2303 check_audio_video_inputs(&input_has_video, &input_has_audio);
2304 if (!input_has_video)
2306 if (!input_has_audio)
2310 /* manual disable */
2311 if (audio_disable) {
2314 if (video_disable) {
2320 AVCodecContext *video_enc;
2322 st = av_mallocz(sizeof(AVStream));
2324 fprintf(stderr, "Could not alloc stream\n");
2327 avcodec_get_context_defaults(&st->codec);
2329 video_enc = &st->codec;
2331 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2332 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2333 if (video_stream_copy) {
2334 st->stream_copy = 1;
2335 video_enc->codec_type = CODEC_TYPE_VIDEO;
2340 codec_id = file_oformat->video_codec;
2341 if (video_codec_id != CODEC_ID_NONE)
2342 codec_id = video_codec_id;
2344 video_enc->codec_id = codec_id;
2346 video_enc->bit_rate = video_bit_rate;
2347 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2348 video_enc->frame_rate = frame_rate;
2349 video_enc->frame_rate_base = frame_rate_base;
2351 video_enc->width = frame_width;
2352 video_enc->height = frame_height;
2353 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2354 video_enc->pix_fmt = frame_pix_fmt;
2357 video_enc->gop_size = gop_size;
2359 video_enc->gop_size = 0;
2360 if (video_qscale || same_quality) {
2361 video_enc->flags |= CODEC_FLAG_QSCALE;
2362 st->quality = FF_QP2LAMBDA * video_qscale;
2366 video_enc->intra_matrix = intra_matrix;
2368 video_enc->inter_matrix = inter_matrix;
2371 video_enc->flags |= CODEC_FLAG_BITEXACT;
2373 video_enc->mb_decision = mb_decision;
2374 video_enc->mb_cmp = mb_cmp;
2375 video_enc->me_sub_cmp = sub_cmp;
2376 video_enc->me_cmp = cmp;
2379 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2382 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2385 video_enc->flags |= CODEC_FLAG_H263P_AIV;
2388 video_enc->flags |= CODEC_FLAG_4MV;
2391 video_enc->flags |= CODEC_FLAG_OBMC;
2395 video_enc->flags |= CODEC_FLAG_PART;
2398 video_enc->flags |= CODEC_FLAG_ALT_SCAN;
2401 video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
2403 if (use_scan_offset) {
2404 video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
2407 video_enc->max_b_frames = b_frames;
2408 video_enc->b_frame_strategy = 0;
2409 video_enc->b_quant_factor = 2.0;
2411 if (do_interlace_dct) {
2412 video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2414 if (do_interlace_me) {
2415 video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
2417 video_enc->qmin = video_qmin;
2418 video_enc->qmax = video_qmax;
2419 video_enc->mb_qmin = video_mb_qmin;
2420 video_enc->mb_qmax = video_mb_qmax;
2421 video_enc->max_qdiff = video_qdiff;
2422 video_enc->qblur = video_qblur;
2423 video_enc->qcompress = video_qcomp;
2424 video_enc->rc_eq = video_rc_eq;
2425 video_enc->debug = debug;
2426 video_enc->debug_mv = debug_mv;
2427 p= video_rc_override_string;
2430 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2432 fprintf(stderr, "error parsing rc_override\n");
2435 video_enc->rc_override=
2436 av_realloc(video_enc->rc_override,
2437 sizeof(RcOverride)*(i+1));
2438 video_enc->rc_override[i].start_frame= start;
2439 video_enc->rc_override[i].end_frame = end;
2441 video_enc->rc_override[i].qscale= q;
2442 video_enc->rc_override[i].quality_factor= 1.0;
2445 video_enc->rc_override[i].qscale= 0;
2446 video_enc->rc_override[i].quality_factor= -q/100.0;
2451 video_enc->rc_override_count=i;
2453 video_enc->rc_max_rate = video_rc_max_rate;
2454 video_enc->rc_min_rate = video_rc_min_rate;
2455 video_enc->rc_buffer_size = video_rc_buffer_size;
2456 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2457 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2458 video_enc->i_quant_factor = video_i_qfactor;
2459 video_enc->b_quant_factor = video_b_qfactor;
2460 video_enc->i_quant_offset = video_i_qoffset;
2461 video_enc->b_quant_offset = video_b_qoffset;
2462 video_enc->dct_algo = dct_algo;
2463 video_enc->idct_algo = idct_algo;
2464 video_enc->strict_std_compliance = strict;
2465 video_enc->error_rate = error_rate;
2466 video_enc->noise_reduction= noise_reduction;
2468 video_enc->rtp_mode= 1;
2469 video_enc->rtp_payload_size= packet_size;
2473 video_enc->flags|= CODEC_FLAG_PSNR;
2475 video_enc->me_method = me_method;
2480 video_enc->flags |= CODEC_FLAG_PASS1;
2482 video_enc->flags |= CODEC_FLAG_PASS2;
2486 oc->streams[nb_streams] = st;
2491 AVCodecContext *audio_enc;
2493 st = av_mallocz(sizeof(AVStream));
2495 fprintf(stderr, "Could not alloc stream\n");
2498 avcodec_get_context_defaults(&st->codec);
2500 audio_enc = &st->codec;
2501 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2503 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2504 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2505 if (audio_stream_copy) {
2506 st->stream_copy = 1;
2508 codec_id = file_oformat->audio_codec;
2509 if (audio_codec_id != CODEC_ID_NONE)
2510 codec_id = audio_codec_id;
2511 audio_enc->codec_id = codec_id;
2513 audio_enc->bit_rate = audio_bit_rate;
2514 audio_enc->sample_rate = audio_sample_rate;
2515 /* For audio codecs other than AC3 we limit */
2516 /* the number of coded channels to stereo */
2517 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2518 audio_enc->channels = 2;
2520 audio_enc->channels = audio_channels;
2522 oc->streams[nb_streams] = st;
2526 oc->nb_streams = nb_streams;
2529 fprintf(stderr, "No audio or video streams available\n");
2534 pstrcpy(oc->title, sizeof(oc->title), str_title);
2536 pstrcpy(oc->author, sizeof(oc->author), str_author);
2538 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2540 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2543 output_files[nb_output_files++] = oc;
2545 strcpy(oc->filename, filename);
2547 /* check filename in case of an image number is expected */
2548 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2549 if (filename_number_test(oc->filename) < 0) {
2550 print_error(oc->filename, AVERROR_NUMEXPECTED);
2555 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2556 /* test if it already exists to avoid loosing precious files */
2557 if (!file_overwrite &&
2558 (strchr(filename, ':') == NULL ||
2559 strstart(filename, "file:", NULL))) {
2560 if (url_exist(filename)) {
2563 if ( !using_stdin ) {
2564 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2567 if (toupper(c) != 'Y') {
2568 fprintf(stderr, "Not overwriting - exiting\n");
2573 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2580 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2581 fprintf(stderr, "Could not open '%s'\n", filename);
2586 memset(ap, 0, sizeof(*ap));
2587 ap->image_format = image_format;
2588 if (av_set_parameters(oc, ap) < 0) {
2589 fprintf(stderr, "%s: Invalid encoding parameters\n",
2594 /* reset some options */
2595 file_oformat = NULL;
2596 file_iformat = NULL;
2597 image_format = NULL;
2600 audio_codec_id = CODEC_ID_NONE;
2601 video_codec_id = CODEC_ID_NONE;
2602 audio_stream_copy = 0;
2603 video_stream_copy = 0;
2606 /* prepare dummy protocols for grab */
2607 static void prepare_grab(void)
2609 int has_video, has_audio, i, j;
2610 AVFormatContext *oc;
2611 AVFormatContext *ic;
2612 AVFormatParameters vp1, *vp = &vp1;
2613 AVFormatParameters ap1, *ap = &ap1;
2615 /* see if audio/video inputs are needed */
2618 memset(ap, 0, sizeof(*ap));
2619 memset(vp, 0, sizeof(*vp));
2620 for(j=0;j<nb_output_files;j++) {
2621 oc = output_files[j];
2622 for(i=0;i<oc->nb_streams;i++) {
2623 AVCodecContext *enc = &oc->streams[i]->codec;
2624 switch(enc->codec_type) {
2625 case CODEC_TYPE_AUDIO:
2626 if (enc->sample_rate > ap->sample_rate)
2627 ap->sample_rate = enc->sample_rate;
2628 if (enc->channels > ap->channels)
2629 ap->channels = enc->channels;
2632 case CODEC_TYPE_VIDEO:
2633 if (enc->width > vp->width)
2634 vp->width = enc->width;
2635 if (enc->height > vp->height)
2636 vp->height = enc->height;
2638 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2639 if (enc->frame_rate > vp->frame_rate){
2640 vp->frame_rate = enc->frame_rate;
2641 vp->frame_rate_base = enc->frame_rate_base;
2651 if (has_video == 0 && has_audio == 0) {
2652 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2657 AVInputFormat *fmt1;
2658 fmt1 = av_find_input_format(video_grab_format);
2659 vp->device = video_device;
2660 vp->channel = video_channel;
2661 vp->standard = video_standard;
2662 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2663 fprintf(stderr, "Could not find video grab device\n");
2666 /* If not enough info to get the stream parameters, we decode the
2667 first frames to get it. */
2668 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2669 fprintf(stderr, "Could not find video grab parameters\n");
2672 /* by now video grab has one stream */
2673 ic->streams[0]->r_frame_rate = vp->frame_rate;
2674 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2675 input_files[nb_input_files] = ic;
2676 dump_format(ic, nb_input_files, "", 0);
2679 if (has_audio && audio_grab_format) {
2680 AVInputFormat *fmt1;
2681 fmt1 = av_find_input_format(audio_grab_format);
2682 ap->device = audio_device;
2683 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2684 fprintf(stderr, "Could not find audio grab device\n");
2687 input_files[nb_input_files] = ic;
2688 dump_format(ic, nb_input_files, "", 0);
2693 /* same option as mencoder */
2694 static void opt_pass(const char *pass_str)
2697 pass = atoi(pass_str);
2698 if (pass != 1 && pass != 2) {
2699 fprintf(stderr, "pass number can be only 1 or 2\n");
2705 #if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2706 static int64_t getutime(void)
2708 return av_gettime();
2711 static int64_t getutime(void)
2713 struct rusage rusage;
2715 getrusage(RUSAGE_SELF, &rusage);
2716 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2720 extern int ffm_nopts;
2722 static void opt_bitexact(void)
2725 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2729 static void show_formats(void)
2731 AVInputFormat *ifmt;
2732 AVOutputFormat *ofmt;
2733 AVImageFormat *image_fmt;
2738 printf("Output audio/video file formats:");
2739 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2740 printf(" %s", ofmt->name);
2744 printf("Input audio/video file formats:");
2745 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2746 printf(" %s", ifmt->name);
2750 printf("Output image formats:");
2751 for(image_fmt = first_image_format; image_fmt != NULL;
2752 image_fmt = image_fmt->next) {
2753 if (image_fmt->img_write)
2754 printf(" %s", image_fmt->name);
2758 printf("Input image formats:");
2759 for(image_fmt = first_image_format; image_fmt != NULL;
2760 image_fmt = image_fmt->next) {
2761 if (image_fmt->img_read)
2762 printf(" %s", image_fmt->name);
2766 printf("Codecs:\n");
2767 printf(" Encoders:");
2768 for(p = first_avcodec; p != NULL; p = p->next) {
2770 printf(" %s", p->name);
2774 printf(" Decoders:");
2775 for(p = first_avcodec; p != NULL; p = p->next) {
2777 printf(" %s", p->name);
2781 printf("Supported file protocols:");
2782 for(up = first_protocol; up != NULL; up = up->next)
2783 printf(" %s:", up->name);
2786 printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2787 printf("Motion estimation methods:");
2791 if ((pp - motion_str + 1) == ME_ZERO)
2792 printf("(fastest)");
2793 else if ((pp - motion_str + 1) == ME_FULL)
2794 printf("(slowest)");
2795 else if ((pp - motion_str + 1) == ME_EPZS)
2796 printf("(default)");
2803 void parse_matrix_coeffs(uint16_t *dest, const char *str)
2806 const char *p = str;
2813 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2820 void opt_inter_matrix(const char *arg)
2822 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2823 parse_matrix_coeffs(inter_matrix, arg);
2826 void opt_intra_matrix(const char *arg)
2828 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2829 parse_matrix_coeffs(intra_matrix, arg);
2832 static void opt_target(const char *arg)
2836 if(!strncmp(arg, "pal-", 4)) {
2839 } else if(!strncmp(arg, "ntsc-", 5)) {
2844 /* Calculate FR via float to avoid int overflow */
2845 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2848 } else if((fr == 29970) || (fr == 23976)) {
2851 /* Try to determine PAL/NTSC by peeking in the input files */
2852 if(nb_input_files) {
2854 for(j = 0; j < nb_input_files; j++) {
2855 for(i = 0; i < input_files[j]->nb_streams; i++) {
2856 AVCodecContext *c = &input_files[j]->streams[i]->codec;
2857 if(c->codec_type != CODEC_TYPE_VIDEO)
2859 fr = c->frame_rate * 1000 / c->frame_rate_base;
2863 } else if((fr == 29970) || (fr == 23976)) {
2873 if(verbose && norm >= 0)
2874 printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2878 fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2879 fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2880 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2884 if(!strcmp(arg, "vcd")) {
2886 opt_video_codec("mpeg1video");
2887 opt_audio_codec("mp2");
2890 opt_frame_size(norm ? "352x240" : "352x288");
2892 video_bit_rate = 1150000;
2893 video_rc_max_rate = 1150000;
2894 video_rc_min_rate = 1150000;
2895 video_rc_buffer_size = 40*1024*8;
2897 audio_bit_rate = 224000;
2898 audio_sample_rate = 44100;
2900 } else if(!strcmp(arg, "svcd")) {
2902 opt_video_codec("mpeg2video");
2903 opt_audio_codec("mp2");
2906 opt_frame_size(norm ? "480x480" : "480x576");
2907 opt_gop_size(norm ? "18" : "15");
2909 video_bit_rate = 2040000;
2910 video_rc_max_rate = 2516000;
2911 video_rc_min_rate = 0; //1145000;
2912 video_rc_buffer_size = 224*1024*8;
2913 use_scan_offset = 1;
2915 audio_bit_rate = 224000;
2916 audio_sample_rate = 44100;
2918 } else if(!strcmp(arg, "dvd")) {
2920 opt_video_codec("mpeg2video");
2921 opt_audio_codec("ac3");
2924 opt_frame_size(norm ? "720x480" : "720x576");
2925 opt_gop_size(norm ? "18" : "15");
2927 video_bit_rate = 6000000;
2928 video_rc_max_rate = 9000000;
2929 video_rc_min_rate = 0; //1500000;
2930 video_rc_buffer_size = 224*1024*8;
2932 audio_bit_rate = 448000;
2933 audio_sample_rate = 48000;
2936 fprintf(stderr, "Unknown target: %s\n", arg);
2941 const OptionDef options[] = {
2943 { "L", 0, {(void*)show_license}, "show license" },
2944 { "h", 0, {(void*)show_help}, "show help" },
2945 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2946 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2947 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2948 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2949 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2950 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2951 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2952 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2953 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2954 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2955 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2956 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2957 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2958 { "vismv", HAS_ARG | OPT_EXPERT, {(void*)opt_vismv}, "visualize motion vectors", "" },
2959 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2960 "add timings for benchmarking" },
2961 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
2962 "dump each input packet" },
2963 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2964 "when dumping packets, also dump the payload" },
2965 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2966 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2967 { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2968 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2969 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2972 { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2973 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2974 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2975 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2976 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2977 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2978 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2979 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2980 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2981 { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2982 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2983 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2984 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2985 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2986 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2987 { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2988 { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2989 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2990 { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2991 { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2992 { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2993 { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2994 { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2995 { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2996 { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2997 // { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2998 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2999 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3000 { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
3001 { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
3002 { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
3003 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
3004 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3005 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
3007 { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo", "algo" },
3008 { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo", "algo" },
3009 { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience", "n" },
3010 { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment", "bit_mask" },
3011 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3012 { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
3013 { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
3014 { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
3015 { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
3016 { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
3017 { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
3018 { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
3019 { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
3020 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3021 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3022 { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3023 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
3024 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3025 "use same video quality as source (implies VBR)" },
3026 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3027 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3028 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3029 "deinterlace pictures" },
3030 { "ildct", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_dct},
3031 "force interlaced dct support in encoder (MPEG2/MPEG4)" },
3032 { "ilme", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace_me},
3033 "force interlacied me support in encoder MPEG2" },
3034 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3035 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
3036 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3037 { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
3038 { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
3039 { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
3040 { "alt", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_alt_scan}, "enable alternate scantable (mpeg2)" },
3041 { "trell", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_trell}, "enable trellis quantization" },
3042 { "scan_offset", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_scan_offset}, "enable SVCD Scan Offset placeholder" },
3043 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3044 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3045 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3046 { "nr", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_noise_reduction}, "noise reduction", "" },
3049 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3050 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3051 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3052 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3053 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3056 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3057 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3058 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3059 { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
3060 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3064 static void show_banner(void)
3066 printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
3069 static void show_license(void)
3073 "This library is free software; you can redistribute it and/or\n"
3074 "modify it under the terms of the GNU Lesser General Public\n"
3075 "License as published by the Free Software Foundation; either\n"
3076 "version 2 of the License, or (at your option) any later version.\n"
3078 "This library is distributed in the hope that it will be useful,\n"
3079 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3080 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
3081 "Lesser General Public License for more details.\n"
3083 "You should have received a copy of the GNU Lesser General Public\n"
3084 "License along with this library; if not, write to the Free Software\n"
3085 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
3090 static void show_help(void)
3093 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3094 "Hyper fast Audio and Video encoder\n");
3096 show_help_options(options, "Main options:\n",
3097 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3098 show_help_options(options, "\nVideo options:\n",
3099 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3101 show_help_options(options, "\nAdvanced Video options:\n",
3102 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3103 OPT_VIDEO | OPT_EXPERT);
3104 show_help_options(options, "\nAudio options:\n",
3105 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3107 show_help_options(options, "\nAdvanced Audio options:\n",
3108 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3109 OPT_AUDIO | OPT_EXPERT);
3110 show_help_options(options, "\nAudio/Video grab options:\n",
3113 show_help_options(options, "\nAdvanced options:\n",
3114 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3119 void parse_arg_file(const char *filename)
3121 opt_output_file(filename);
3124 int main(int argc, char **argv)
3135 parse_options(argc, argv, options);
3137 /* file converter / grab */
3138 if (nb_output_files <= 0) {
3139 fprintf(stderr, "Must supply at least one output file\n");
3143 if (nb_input_files == 0) {
3148 av_encode(output_files, nb_output_files, input_files, nb_input_files,
3149 stream_maps, nb_stream_maps);
3150 ti = getutime() - ti;
3152 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3156 for(i=0;i<nb_output_files;i++) {
3157 /* maybe av_close_output_file ??? */
3158 AVFormatContext *s = output_files[i];
3160 if (!(s->oformat->flags & AVFMT_NOFILE))
3162 for(j=0;j<s->nb_streams;j++)
3163 av_free(s->streams[j]);
3166 for(i=0;i<nb_input_files;i++)
3167 av_close_input_file(input_files[i]);
3172 av_free(intra_matrix);
3174 av_free(inter_matrix);
3176 #ifdef POWERPC_PERFORMANCE_REPORT
3177 extern void powerpc_display_perf_report(void);
3178 powerpc_display_perf_report();
3179 #endif /* POWERPC_PERFORMANCE_REPORT */
3181 #ifndef CONFIG_WIN32
3182 if (received_sigterm) {
3184 "Received signal %d: terminating.\n",
3185 (int) received_sigterm);
3189 exit(0); /* not all OS-es handle main() return value */