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 do_deinterlace = 0;
123 static int do_interlace = 0;
124 static int workaround_bugs = FF_BUG_AUTODETECT;
125 static int error_resilience = 2;
126 static int error_concealment = 3;
127 static int dct_algo = 0;
128 static int idct_algo = 0;
129 static int use_part = 0;
130 static int packet_size = 0;
131 static int error_rate = 0;
132 static int strict = 0;
133 static int debug = 0;
134 extern int loop_input; /* currently a hack */
136 static int gop_size = 12;
137 static int intra_only = 0;
138 static int audio_sample_rate = 44100;
139 static int audio_bit_rate = 64000;
140 static int audio_disable = 0;
141 static int audio_channels = 1;
142 static int audio_codec_id = CODEC_ID_NONE;
144 static int64_t recording_time = 0;
145 static int64_t start_time = 0;
146 static int file_overwrite = 0;
147 static char *str_title = NULL;
148 static char *str_author = NULL;
149 static char *str_copyright = NULL;
150 static char *str_comment = NULL;
151 static int do_benchmark = 0;
152 static int do_hex_dump = 0;
153 static int do_pkt_dump = 0;
154 static int do_psnr = 0;
155 static int do_vstats = 0;
156 static int do_pass = 0;
157 static int bitexact = 0;
158 static char *pass_logfilename = NULL;
159 static int audio_stream_copy = 0;
160 static int video_stream_copy = 0;
162 static int rate_emu = 0;
164 static char *video_grab_format = "video4linux";
165 static char *video_device = NULL;
166 static int video_channel = 0;
167 static char *video_standard = "ntsc";
169 static char *audio_grab_format = "audio_device";
170 static char *audio_device = NULL;
172 static int using_stdin = 0;
173 static int using_vhook = 0;
174 static int verbose = 1;
176 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
178 typedef struct AVOutputStream {
179 int file_index; /* file index */
180 int index; /* stream index in the output file */
181 int source_index; /* AVInputStream index */
182 AVStream *st; /* stream in the output file */
183 int encoding_needed; /* true if encoding needed for this stream */
185 /* input pts and corresponding output pts
188 double sync_ipts_offset;
191 int video_resample; /* video_resample and video_crop are mutually exclusive */
192 AVPicture pict_tmp; /* temporary image for resampling */
193 ImgReSampleContext *img_resample_ctx; /* for image resampling */
195 int video_crop; /* video_resample and video_crop are mutually exclusive */
196 int topBand; /* cropping area sizes */
201 ReSampleContext *resample; /* for audio resampling */
202 FifoBuffer fifo; /* for compression: one audio fifo per codec */
206 typedef struct AVInputStream {
210 int discard; /* true if stream data should be discarded */
211 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
212 int64_t sample_index; /* current sample */
214 int64_t start; /* time when read started */
215 unsigned long frame; /* current frame */
216 int64_t next_pts; /* synthetic pts for cases where pkt.pts
218 int64_t pts; /* current pts */
221 typedef struct AVInputFile {
222 int eof_reached; /* true if eof reached */
223 int ist_index; /* index of first stream in ist_table */
224 int buffer_size; /* current total buffer size */
225 int buffer_size_max; /* buffer size at which we consider we can stop
227 int nb_streams; /* nb streams we are aware of */
232 /* init terminal so that we can grab keys */
233 static struct termios oldtty;
235 static void term_exit(void)
237 tcsetattr (0, TCSANOW, &oldtty);
240 static volatile sig_atomic_t received_sigterm = 0;
243 sigterm_handler(int sig)
245 received_sigterm = sig;
249 static void term_init(void)
256 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
257 |INLCR|IGNCR|ICRNL|IXON);
258 tty.c_oflag |= OPOST;
259 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
260 tty.c_cflag &= ~(CSIZE|PARENB);
265 tcsetattr (0, TCSANOW, &tty);
267 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
268 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
269 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
271 register a function to be called at normal program termination
274 #ifdef CONFIG_BEOS_NETSERVER
275 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
279 /* read a key without blocking */
280 static int read_key(void)
284 #ifndef CONFIG_BEOS_NETSERVER
292 n = select(1, &rfds, NULL, NULL, &tv);
306 static volatile int received_sigterm = 0;
308 /* no interactive support */
309 static void term_exit(void)
313 static void term_init(void)
317 static int read_key(void)
324 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
329 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
332 /* copy stream format */
333 s->nb_streams = ic->nb_streams;
334 for(i=0;i<ic->nb_streams;i++) {
337 st = av_mallocz(sizeof(AVStream));
338 memcpy(st, ic->streams[i], sizeof(AVStream));
342 av_close_input_file(ic);
346 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
348 static void do_audio_out(AVFormatContext *s,
351 unsigned char *buf, int size)
354 static uint8_t *audio_buf = NULL;
355 static uint8_t *audio_out = NULL;
356 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
358 int size_out, frame_bytes, ret;
361 /* SC: dynamic allocation of buffers */
363 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
365 audio_out = av_malloc(audio_out_size);
366 if (!audio_buf || !audio_out)
367 return; /* Should signal an error ! */
370 enc = &ost->st->codec;
372 if (ost->audio_resample) {
374 size_out = audio_resample(ost->resample,
375 (short *)buftmp, (short *)buf,
376 size / (ist->st->codec.channels * 2));
377 size_out = size_out * enc->channels * 2;
383 /* now encode as many frames as possible */
384 if (enc->frame_size > 1) {
385 /* output resampled raw samples */
386 fifo_write(&ost->fifo, buftmp, size_out,
389 frame_bytes = enc->frame_size * 2 * enc->channels;
391 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
392 &ost->fifo.rptr) == 0) {
393 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
395 av_write_frame(s, ost->index, audio_out, ret);
398 /* output a pcm frame */
399 /* XXX: change encoding codec API to avoid this ? */
400 switch(enc->codec->id) {
401 case CODEC_ID_PCM_S16LE:
402 case CODEC_ID_PCM_S16BE:
403 case CODEC_ID_PCM_U16LE:
404 case CODEC_ID_PCM_U16BE:
407 size_out = size_out >> 1;
410 ret = avcodec_encode_audio(enc, audio_out, size_out,
412 av_write_frame(s, ost->index, audio_out, ret);
416 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
420 AVPicture picture_tmp;
423 dec = &ist->st->codec;
425 /* deinterlace : must be done before any resize */
426 if (do_deinterlace || using_vhook) {
429 /* create temporary picture */
430 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
431 buf = av_malloc(size);
435 picture2 = &picture_tmp;
436 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
439 if(avpicture_deinterlace(picture2, picture,
440 dec->pix_fmt, dec->width, dec->height) < 0) {
441 /* if error, do not deinterlace */
447 if (img_convert(picture2, dec->pix_fmt, picture,
448 dec->pix_fmt, dec->width, dec->height) < 0) {
449 /* if error, do not copy */
459 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
461 if (picture != picture2)
462 *picture = *picture2;
466 /* we begin to correct av delay at this threshold */
467 #define AV_DELAY_MAX 0.100
469 static void do_video_out(AVFormatContext *s,
473 int *frame_size, AVOutputStream *audio_sync)
475 int nb_frames, i, ret;
476 AVPicture *final_picture, *formatted_picture;
477 AVPicture picture_format_temp, picture_crop_temp;
478 static uint8_t *video_buffer;
479 uint8_t *buf = NULL, *buf1 = NULL;
480 AVCodecContext *enc, *dec;
481 enum PixelFormat target_pixfmt;
483 #define VIDEO_BUFFER_SIZE (1024*1024)
485 enc = &ost->st->codec;
486 dec = &ist->st->codec;
488 /* by default, we output a single frame */
493 /* NOTE: the A/V sync is always done by considering the audio is
494 the master clock. It is suffisant for transcoding or playing,
495 but not for the general case */
497 /* compute the A-V delay and duplicate/remove frames if needed */
498 double adelta, vdelta, av_delay;
500 adelta = audio_sync->sync_ipts - ((double)audio_sync->sync_opts *
501 s->pts_num / s->pts_den);
503 vdelta = ost->sync_ipts - ((double)ost->sync_opts *
504 s->pts_num / s->pts_den);
506 av_delay = adelta - vdelta;
507 // printf("delay=%f\n", av_delay);
508 if (av_delay < -AV_DELAY_MAX)
510 else if (av_delay > AV_DELAY_MAX)
515 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - (ost->sync_ipts - ost->sync_ipts_offset);
516 if (vdelta < 100 && vdelta > -100 && ost->sync_ipts_offset) {
517 if (vdelta < -AV_DELAY_MAX)
519 else if (vdelta > AV_DELAY_MAX)
522 ost->sync_ipts_offset -= vdelta;
523 if (!ost->sync_ipts_offset)
524 ost->sync_ipts_offset = 0.000001; /* one microsecond */
528 #if defined(AVSYNC_DEBUG)
530 static char *action[] = { "drop frame", "copy frame", "dup frame" };
532 fprintf(stderr, "Input APTS %12.6f, output APTS %12.6f, ",
533 (double) audio_sync->sync_ipts,
534 (double) audio_sync->st->pts.val * s->pts_num / s->pts_den);
535 fprintf(stderr, "Input VPTS %12.6f, output VPTS %12.6f: %s\n",
536 (double) ost->sync_ipts,
537 (double) ost->st->pts.val * s->pts_num / s->pts_den,
546 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
550 /* convert pixel format if needed */
551 target_pixfmt = ost->video_resample ? PIX_FMT_YUV420P : enc->pix_fmt;
552 if (dec->pix_fmt != target_pixfmt) {
555 /* create temporary picture */
556 size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
557 buf = av_malloc(size);
560 formatted_picture = &picture_format_temp;
561 avpicture_fill(formatted_picture, buf, target_pixfmt, dec->width, dec->height);
563 if (img_convert(formatted_picture, target_pixfmt,
564 (AVPicture *)in_picture, dec->pix_fmt,
565 dec->width, dec->height) < 0) {
566 fprintf(stderr, "pixel format conversion not handled\n");
570 formatted_picture = (AVPicture *)in_picture;
573 /* XXX: resampling could be done before raw format convertion in
574 some cases to go faster */
575 /* XXX: only works for YUV420P */
576 if (ost->video_resample) {
577 final_picture = &ost->pict_tmp;
578 img_resample(ost->img_resample_ctx, final_picture, formatted_picture);
579 if (enc->pix_fmt != PIX_FMT_YUV420P) {
583 /* create temporary picture */
584 size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
585 buf = av_malloc(size);
588 final_picture = &picture_format_temp;
589 avpicture_fill(final_picture, buf, enc->pix_fmt, enc->width, enc->height);
591 if (img_convert(final_picture, enc->pix_fmt,
592 &ost->pict_tmp, PIX_FMT_YUV420P,
593 enc->width, enc->height) < 0) {
594 fprintf(stderr, "pixel format conversion not handled\n");
598 } else if (ost->video_crop) {
599 picture_crop_temp.data[0] = formatted_picture->data[0] +
600 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
602 picture_crop_temp.data[1] = formatted_picture->data[1] +
603 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
604 (ost->leftBand >> 1);
606 picture_crop_temp.data[2] = formatted_picture->data[2] +
607 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
608 (ost->leftBand >> 1);
610 picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
611 picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
612 picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
613 final_picture = &picture_crop_temp;
615 final_picture = formatted_picture;
617 /* duplicates frame if needed */
618 /* XXX: pb because no interleaving */
619 for(i=0;i<nb_frames;i++) {
620 if (s->oformat->flags & AVFMT_RAWPICTURE) {
621 /* raw pictures are written as AVPicture structure to
622 avoid any copies. We support temorarily the older
624 AVFrame* old_frame = enc->coded_frame;
625 enc->coded_frame = dec->coded_frame;
626 av_write_frame(s, ost->index,
627 (uint8_t *)final_picture, sizeof(AVPicture));
628 enc->coded_frame = old_frame;
632 memset(&big_picture, 0, sizeof(AVFrame));
633 *(AVPicture*)&big_picture= *final_picture;
634 /* better than nothing: use input picture interlaced
636 big_picture.interlaced_frame = in_picture->interlaced_frame;
637 big_picture.top_field_first = in_picture->top_field_first;
639 /* handles sameq here. This is not correct because it may
640 not be a global option */
642 big_picture.quality = ist->st->quality;
644 big_picture.quality = ost->st->quality;
646 ret = avcodec_encode_video(enc,
647 video_buffer, VIDEO_BUFFER_SIZE,
649 //enc->frame_number = enc->real_pict_num;
650 av_write_frame(s, ost->index, video_buffer, ret);
652 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
653 // enc->frame_number-1, enc->real_pict_num, ret,
655 /* if two pass, output log */
656 if (ost->logfile && enc->stats_out) {
657 fprintf(ost->logfile, "%s", enc->stats_out);
667 static double psnr(double d){
668 if(d==0) return INFINITY;
669 return -10.0*log(d)/log(10.0);
672 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
675 static FILE *fvstats=NULL;
676 static int64_t total_size = 0;
683 double ti1, bitrate, avg_bitrate;
687 today = localtime(&today2);
688 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
691 fvstats = fopen(filename,"w");
699 enc = &ost->st->codec;
700 total_size += frame_size;
701 if (enc->codec_type == CODEC_TYPE_VIDEO) {
702 frame_number = ost->frame_number;
703 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
704 if (enc->flags&CODEC_FLAG_PSNR)
705 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
707 fprintf(fvstats,"f_size= %6d ", frame_size);
708 /* compute pts value */
709 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
713 bitrate = (double)(frame_size * 8) * enc->frame_rate / enc->frame_rate_base / 1000.0;
714 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
715 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
716 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
717 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
721 static void print_report(AVFormatContext **output_files,
722 AVOutputStream **ost_table, int nb_ostreams,
727 AVFormatContext *oc, *os;
730 int frame_number, vid, i;
731 double bitrate, ti1, pts;
732 static int64_t last_time = -1;
734 if (!is_last_report) {
736 /* display the report every 0.5 seconds */
737 cur_time = av_gettime();
738 if (last_time == -1) {
739 last_time = cur_time;
742 if ((cur_time - last_time) < 500000)
744 last_time = cur_time;
748 oc = output_files[0];
750 total_size = url_ftell(&oc->pb);
755 for(i=0;i<nb_ostreams;i++) {
757 os = output_files[ost->file_index];
758 enc = &ost->st->codec;
759 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
760 sprintf(buf + strlen(buf), "q=%2.1f ",
761 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
763 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
764 frame_number = ost->frame_number;
765 sprintf(buf + strlen(buf), "frame=%5d q=%2.1f ",
766 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
767 if (enc->flags&CODEC_FLAG_PSNR)
768 sprintf(buf + strlen(buf), "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
771 /* compute min output value */
772 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
773 if ((pts < ti1) && (pts > 0))
779 if (verbose || is_last_report) {
780 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
782 sprintf(buf + strlen(buf),
783 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
784 (double)total_size / 1024, ti1, bitrate);
786 fprintf(stderr, "%s \r", buf);
791 fprintf(stderr, "\n");
794 /* pkt = NULL means EOF (needed to flush decoder buffers) */
795 static int output_packet(AVInputStream *ist, int ist_index,
796 AVOutputStream **ost_table, int nb_ostreams,
804 int data_size, got_picture;
806 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
807 void *buffer_to_free;
809 if (pkt && pkt->pts != AV_NOPTS_VALUE) {
812 ist->pts = ist->next_pts;
826 /* decode the packet if needed */
827 data_buf = NULL; /* fail safe */
829 if (ist->decoding_needed) {
830 switch(ist->st->codec.codec_type) {
831 case CODEC_TYPE_AUDIO:
832 /* XXX: could avoid copy if PCM 16 bits with same
834 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
840 /* Some bug in mpeg audio decoder gives */
841 /* data_size < 0, it seems they are overflows */
842 if (data_size <= 0) {
846 data_buf = (uint8_t *)samples;
847 ist->next_pts += ((int64_t)AV_TIME_BASE * data_size) /
848 (2 * ist->st->codec.channels);
850 case CODEC_TYPE_VIDEO:
851 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
852 /* XXX: allocate picture correctly */
853 memset(&picture, 0, sizeof(picture));
854 ret = avcodec_decode_video(&ist->st->codec,
855 &picture, &got_picture, ptr, len);
856 ist->st->quality= picture.quality;
863 if (ist->st->codec.frame_rate_base != 0) {
864 ist->next_pts += ((int64_t)AV_TIME_BASE *
865 ist->st->codec.frame_rate_base) /
866 ist->st->codec.frame_rate;
880 buffer_to_free = NULL;
881 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
882 pre_process_video_frame(ist, (AVPicture *)&picture,
886 /* frame rate emulation */
887 if (ist->st->codec.rate_emu) {
888 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);
889 int64_t now = av_gettime() - ist->start;
897 /* mpeg PTS deordering : if it is a P or I frame, the PTS
898 is the one of the next displayed one */
899 /* XXX: add mpeg4 too ? */
900 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
901 if (ist->st->codec.pict_type != B_TYPE) {
903 tmp = ist->last_ip_pts;
904 ist->last_ip_pts = ist->frac_pts.val;
905 ist->frac_pts.val = tmp;
909 /* if output time reached then transcode raw format,
910 encode packets and output them */
911 if (start_time == 0 || ist->pts >= start_time)
912 for(i=0;i<nb_ostreams;i++) {
916 if (ost->source_index == ist_index) {
917 os = output_files[ost->file_index];
920 printf("%d: got pts=%0.3f %0.3f\n", i,
921 (double)pkt->pts / AV_TIME_BASE,
922 ((double)ist->pts / AV_TIME_BASE) -
923 ((double)ost->st->pts.val * os->pts_num / os->pts_den));
925 /* set the input output pts pairs */
926 ost->sync_ipts = (double)ist->pts / AV_TIME_BASE;
927 /* XXX: take into account the various fifos,
928 in particular for audio */
929 ost->sync_opts = ost->st->pts.val;
930 //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);
932 if (ost->encoding_needed) {
933 switch(ost->st->codec.codec_type) {
934 case CODEC_TYPE_AUDIO:
935 do_audio_out(os, ost, ist, data_buf, data_size);
937 case CODEC_TYPE_VIDEO:
938 /* find an audio stream for synchro */
941 AVOutputStream *audio_sync, *ost1;
943 for(i=0;i<nb_ostreams;i++) {
945 if (ost1->file_index == ost->file_index &&
946 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
952 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
953 if (do_vstats && frame_size)
954 do_video_stats(os, ost, frame_size);
963 /* no reencoding needed : output the packet directly */
964 /* force the input stream PTS */
966 memset(&avframe, 0, sizeof(AVFrame));
967 ost->st->codec.coded_frame= &avframe;
968 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
970 av_write_frame(os, ost->index, data_buf, data_size);
971 ost->st->codec.frame_number++;
976 av_free(buffer_to_free);
986 * The following code is the main loop of the file converter
988 static int av_encode(AVFormatContext **output_files,
990 AVFormatContext **input_files,
992 AVStreamMap *stream_maps, int nb_stream_maps)
994 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
995 AVFormatContext *is, *os;
996 AVCodecContext *codec, *icodec;
997 AVOutputStream *ost, **ost_table = NULL;
998 AVInputStream *ist, **ist_table = NULL;
999 AVInputFile *file_table;
1000 AVFormatContext *stream_no_data;
1003 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1007 /* input stream init */
1009 for(i=0;i<nb_input_files;i++) {
1010 is = input_files[i];
1011 file_table[i].ist_index = j;
1012 file_table[i].nb_streams = is->nb_streams;
1013 j += is->nb_streams;
1017 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1021 for(i=0;i<nb_istreams;i++) {
1022 ist = av_mallocz(sizeof(AVInputStream));
1028 for(i=0;i<nb_input_files;i++) {
1029 is = input_files[i];
1030 for(k=0;k<is->nb_streams;k++) {
1031 ist = ist_table[j++];
1032 ist->st = is->streams[k];
1033 ist->file_index = i;
1035 ist->discard = 1; /* the stream is discarded by default
1038 if (ist->st->codec.rate_emu) {
1039 ist->start = av_gettime();
1045 /* output stream init */
1047 for(i=0;i<nb_output_files;i++) {
1048 os = output_files[i];
1049 nb_ostreams += os->nb_streams;
1051 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1052 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1056 /* Sanity check the mapping args -- do the input files & streams exist? */
1057 for(i=0;i<nb_stream_maps;i++) {
1058 int fi = stream_maps[i].file_index;
1059 int si = stream_maps[i].stream_index;
1061 if (fi < 0 || fi > nb_input_files - 1 ||
1062 si < 0 || si > file_table[fi].nb_streams - 1) {
1063 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1068 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1071 for(i=0;i<nb_ostreams;i++) {
1072 ost = av_mallocz(sizeof(AVOutputStream));
1079 for(k=0;k<nb_output_files;k++) {
1080 os = output_files[k];
1081 for(i=0;i<os->nb_streams;i++) {
1083 ost = ost_table[n++];
1084 ost->file_index = k;
1086 ost->st = os->streams[i];
1087 if (nb_stream_maps > 0) {
1088 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1089 stream_maps[n-1].stream_index;
1091 /* Sanity check that the stream types match */
1092 if (ist_table[ost->source_index]->st->codec.codec_type != ost->st->codec.codec_type) {
1093 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1094 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1095 ost->file_index, ost->index);
1100 /* get corresponding input stream index : we select the first one with the right type */
1102 for(j=0;j<nb_istreams;j++) {
1105 ist->st->codec.codec_type == ost->st->codec.codec_type) {
1106 ost->source_index = j;
1112 /* try again and reuse existing stream */
1113 for(j=0;j<nb_istreams;j++) {
1115 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
1116 ost->source_index = j;
1121 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1122 ost->file_index, ost->index);
1127 ist = ist_table[ost->source_index];
1132 /* for each output stream, we compute the right encoding parameters */
1133 for(i=0;i<nb_ostreams;i++) {
1135 ist = ist_table[ost->source_index];
1137 codec = &ost->st->codec;
1138 icodec = &ist->st->codec;
1140 if (ost->st->stream_copy) {
1141 /* if stream_copy is selected, no need to decode or encode */
1142 codec->codec_id = icodec->codec_id;
1143 codec->codec_type = icodec->codec_type;
1144 codec->codec_tag = icodec->codec_tag;
1145 codec->bit_rate = icodec->bit_rate;
1146 switch(codec->codec_type) {
1147 case CODEC_TYPE_AUDIO:
1148 codec->sample_rate = icodec->sample_rate;
1149 codec->channels = icodec->channels;
1151 case CODEC_TYPE_VIDEO:
1152 codec->frame_rate = icodec->frame_rate;
1153 codec->frame_rate_base = icodec->frame_rate_base;
1154 codec->width = icodec->width;
1155 codec->height = icodec->height;
1161 switch(codec->codec_type) {
1162 case CODEC_TYPE_AUDIO:
1163 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1166 if (codec->channels == icodec->channels &&
1167 codec->sample_rate == icodec->sample_rate) {
1168 ost->audio_resample = 0;
1170 if (codec->channels != icodec->channels &&
1171 icodec->codec_id == CODEC_ID_AC3) {
1172 /* Special case for 5:1 AC3 input */
1173 /* and mono or stereo output */
1174 /* Request specific number of channels */
1175 icodec->channels = codec->channels;
1176 if (codec->sample_rate == icodec->sample_rate)
1177 ost->audio_resample = 0;
1179 ost->audio_resample = 1;
1180 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1182 icodec->sample_rate);
1185 printf("Can't resample. Aborting.\n");
1189 /* Request specific number of channels */
1190 icodec->channels = codec->channels;
1192 ost->audio_resample = 1;
1193 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1195 icodec->sample_rate);
1198 printf("Can't resample. Aborting.\n");
1203 ist->decoding_needed = 1;
1204 ost->encoding_needed = 1;
1206 case CODEC_TYPE_VIDEO:
1207 if (codec->width == icodec->width &&
1208 codec->height == icodec->height &&
1209 frame_topBand == 0 &&
1210 frame_bottomBand == 0 &&
1211 frame_leftBand == 0 &&
1212 frame_rightBand == 0)
1214 ost->video_resample = 0;
1215 ost->video_crop = 0;
1216 } else if ((codec->width == icodec->width -
1217 (frame_leftBand + frame_rightBand)) &&
1218 (codec->height == icodec->height -
1219 (frame_topBand + frame_bottomBand)))
1221 ost->video_resample = 0;
1222 ost->video_crop = 1;
1223 ost->topBand = frame_topBand;
1224 ost->leftBand = frame_leftBand;
1227 ost->video_resample = 1;
1228 ost->video_crop = 0; // cropping is handled as part of resample
1229 buf = av_malloc((codec->width * codec->height * 3) / 2);
1232 ost->pict_tmp.data[0] = buf;
1233 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
1234 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
1235 ost->pict_tmp.linesize[0] = codec->width;
1236 ost->pict_tmp.linesize[1] = codec->width / 2;
1237 ost->pict_tmp.linesize[2] = codec->width / 2;
1239 ost->img_resample_ctx = img_resample_full_init(
1240 ost->st->codec.width, ost->st->codec.height,
1241 ist->st->codec.width, ist->st->codec.height,
1242 frame_topBand, frame_bottomBand,
1243 frame_leftBand, frame_rightBand);
1245 ost->encoding_needed = 1;
1246 ist->decoding_needed = 1;
1252 if (ost->encoding_needed &&
1253 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1254 char logfilename[1024];
1259 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1261 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1262 if (codec->flags & CODEC_FLAG_PASS1) {
1263 f = fopen(logfilename, "w");
1265 perror(logfilename);
1270 /* read the log file */
1271 f = fopen(logfilename, "r");
1273 perror(logfilename);
1276 fseek(f, 0, SEEK_END);
1278 fseek(f, 0, SEEK_SET);
1279 logbuffer = av_malloc(size + 1);
1281 fprintf(stderr, "Could not allocate log buffer\n");
1284 fread(logbuffer, 1, size, f);
1286 logbuffer[size] = '\0';
1287 codec->stats_in = logbuffer;
1293 /* dump the file output parameters - cannot be done before in case
1295 for(i=0;i<nb_output_files;i++) {
1296 dump_format(output_files[i], i, output_files[i]->filename, 1);
1299 /* dump the stream mapping */
1300 fprintf(stderr, "Stream mapping:\n");
1301 for(i=0;i<nb_ostreams;i++) {
1303 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1304 ist_table[ost->source_index]->file_index,
1305 ist_table[ost->source_index]->index,
1310 /* open each encoder */
1311 for(i=0;i<nb_ostreams;i++) {
1313 if (ost->encoding_needed) {
1315 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1317 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1318 ost->file_index, ost->index);
1321 if (avcodec_open(&ost->st->codec, codec) < 0) {
1322 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1323 ost->file_index, ost->index);
1329 /* open each decoder */
1330 for(i=0;i<nb_istreams;i++) {
1332 if (ist->decoding_needed) {
1334 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1336 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1337 ist->st->codec.codec_id, ist->file_index, ist->index);
1340 if (avcodec_open(&ist->st->codec, codec) < 0) {
1341 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1342 ist->file_index, ist->index);
1345 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1346 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1351 for(i=0;i<nb_istreams;i++) {
1353 is = input_files[ist->file_index];
1358 /* compute buffer size max (should use a complete heuristic) */
1359 for(i=0;i<nb_input_files;i++) {
1360 file_table[i].buffer_size_max = 2048;
1363 /* open files and write file headers */
1364 for(i=0;i<nb_output_files;i++) {
1365 os = output_files[i];
1366 if (av_write_header(os) < 0) {
1367 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1373 #ifndef CONFIG_WIN32
1375 fprintf(stderr, "Press [q] to stop encoding\n");
1382 for(; received_sigterm == 0;) {
1383 int file_index, ist_index;
1388 /* if 'q' pressed, exits */
1390 /* read_key() returns 0 on EOF */
1396 /* select the stream that we must read now by looking at the
1397 smallest output pts */
1400 for(i=0;i<nb_ostreams;i++) {
1403 os = output_files[ost->file_index];
1404 ist = ist_table[ost->source_index];
1405 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1406 if (!file_table[ist->file_index].eof_reached &&
1409 file_index = ist->file_index;
1412 /* if none, if is finished */
1413 if (file_index < 0) {
1417 /* finish if recording time exhausted */
1418 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1421 /* read a frame from it and output it in the fifo */
1422 is = input_files[file_index];
1423 if (av_read_frame(is, &pkt) < 0) {
1424 file_table[file_index].eof_reached = 1;
1428 stream_no_data = is;
1433 av_pkt_dump(stdout, &pkt, do_hex_dump);
1435 /* the following test is needed in case new streams appear
1436 dynamically in stream : we ignore them */
1437 if (pkt.stream_index >= file_table[file_index].nb_streams)
1438 goto discard_packet;
1439 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1440 ist = ist_table[ist_index];
1442 goto discard_packet;
1444 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1445 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1446 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1447 ist->file_index, ist->index);
1448 av_free_packet(&pkt);
1453 av_free_packet(&pkt);
1455 /* dump report by using the output first video and audio streams */
1456 print_report(output_files, ost_table, nb_ostreams, 0);
1459 /* at the end of stream, we must flush the decoder buffers */
1460 for(i=0;i<nb_istreams;i++) {
1462 if (ist->decoding_needed) {
1463 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1469 /* dump report by using the first video and audio streams */
1470 print_report(output_files, ost_table, nb_ostreams, 1);
1472 /* close each encoder */
1473 for(i=0;i<nb_ostreams;i++) {
1475 if (ost->encoding_needed) {
1476 av_freep(&ost->st->codec.stats_in);
1477 avcodec_close(&ost->st->codec);
1481 /* close each decoder */
1482 for(i=0;i<nb_istreams;i++) {
1484 if (ist->decoding_needed) {
1485 avcodec_close(&ist->st->codec);
1490 /* write the trailer if needed and close file */
1491 for(i=0;i<nb_output_files;i++) {
1492 os = output_files[i];
1493 av_write_trailer(os);
1499 av_free(file_table);
1502 for(i=0;i<nb_istreams;i++) {
1509 for(i=0;i<nb_ostreams;i++) {
1513 fclose(ost->logfile);
1514 ost->logfile = NULL;
1516 fifo_free(&ost->fifo); /* works even if fifo is not
1517 initialized but set to zero */
1518 av_free(ost->pict_tmp.data[0]);
1519 if (ost->video_resample)
1520 img_resample_close(ost->img_resample_ctx);
1521 if (ost->audio_resample)
1522 audio_resample_close(ost->resample);
1535 int file_read(const char *filename)
1538 unsigned char buffer[1024];
1541 if (url_open(&h, filename, O_RDONLY) < 0) {
1542 printf("could not open '%s'\n", filename);
1546 len = url_read(h, buffer, sizeof(buffer));
1549 for(i=0;i<len;i++) putchar(buffer[i]);
1556 static void opt_image_format(const char *arg)
1560 for(f = first_image_format; f != NULL; f = f->next) {
1561 if (!strcmp(arg, f->name))
1565 fprintf(stderr, "Unknown image format: '%s'\n", arg);
1571 static void opt_format(const char *arg)
1573 /* compatibility stuff for pgmyuv */
1574 if (!strcmp(arg, "pgmyuv")) {
1575 opt_image_format(arg);
1579 file_iformat = av_find_input_format(arg);
1580 file_oformat = guess_format(arg, NULL, NULL);
1581 if (!file_iformat && !file_oformat) {
1582 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1587 static void opt_video_bitrate(const char *arg)
1589 video_bit_rate = atoi(arg) * 1000;
1592 static void opt_video_bitrate_tolerance(const char *arg)
1594 video_bit_rate_tolerance = atoi(arg) * 1000;
1597 static void opt_video_bitrate_max(const char *arg)
1599 video_rc_max_rate = atoi(arg) * 1000;
1602 static void opt_video_bitrate_min(const char *arg)
1604 video_rc_min_rate = atoi(arg) * 1000;
1607 static void opt_video_buffer_size(const char *arg)
1609 video_rc_buffer_size = atoi(arg) * 1024;
1612 static void opt_video_rc_eq(char *arg)
1617 static void opt_video_rc_override_string(char *arg)
1619 video_rc_override_string = arg;
1623 static void opt_workaround_bugs(const char *arg)
1625 workaround_bugs = atoi(arg);
1628 static void opt_dct_algo(const char *arg)
1630 dct_algo = atoi(arg);
1633 static void opt_idct_algo(const char *arg)
1635 idct_algo = atoi(arg);
1639 static void opt_error_resilience(const char *arg)
1641 error_resilience = atoi(arg);
1644 static void opt_error_concealment(const char *arg)
1646 error_concealment = atoi(arg);
1649 static void opt_debug(const char *arg)
1654 static void opt_verbose(const char *arg)
1656 verbose = atoi(arg);
1659 static void opt_frame_rate(const char *arg)
1661 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
1662 fprintf(stderr, "Incorrect frame rate\n");
1667 static void opt_frame_crop_top(const char *arg)
1669 frame_topBand = atoi(arg);
1670 if (frame_topBand < 0) {
1671 fprintf(stderr, "Incorrect top crop size\n");
1674 if ((frame_topBand % 2) != 0) {
1675 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1678 if ((frame_topBand) >= frame_height){
1679 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1682 frame_height -= frame_topBand;
1685 static void opt_frame_crop_bottom(const char *arg)
1687 frame_bottomBand = atoi(arg);
1688 if (frame_bottomBand < 0) {
1689 fprintf(stderr, "Incorrect bottom crop size\n");
1692 if ((frame_bottomBand % 2) != 0) {
1693 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1696 if ((frame_bottomBand) >= frame_height){
1697 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1700 frame_height -= frame_bottomBand;
1703 static void opt_frame_crop_left(const char *arg)
1705 frame_leftBand = atoi(arg);
1706 if (frame_leftBand < 0) {
1707 fprintf(stderr, "Incorrect left crop size\n");
1710 if ((frame_leftBand % 2) != 0) {
1711 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1714 if ((frame_leftBand) >= frame_width){
1715 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1718 frame_width -= frame_leftBand;
1721 static void opt_frame_crop_right(const char *arg)
1723 frame_rightBand = atoi(arg);
1724 if (frame_rightBand < 0) {
1725 fprintf(stderr, "Incorrect right crop size\n");
1728 if ((frame_rightBand % 2) != 0) {
1729 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1732 if ((frame_rightBand) >= frame_width){
1733 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1736 frame_width -= frame_rightBand;
1739 static void opt_frame_size(const char *arg)
1741 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
1742 fprintf(stderr, "Incorrect frame size\n");
1745 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1746 fprintf(stderr, "Frame size must be a multiple of 2\n");
1751 static void opt_frame_pix_fmt(const char *arg)
1753 frame_pix_fmt = avcodec_get_pix_fmt(arg);
1756 static void opt_frame_aspect_ratio(const char *arg)
1762 p = strchr(arg, ':');
1764 x = strtol(arg, (char **)&arg, 10);
1766 y = strtol(arg+1, (char **)&arg, 10);
1768 ar = (double)x / (double)y;
1770 ar = strtod(arg, (char **)&arg);
1773 fprintf(stderr, "Incorrect aspect ratio specification.\n");
1776 frame_aspect_ratio = ar;
1779 static void opt_gop_size(const char *arg)
1781 gop_size = atoi(arg);
1784 static void opt_b_frames(const char *arg)
1786 b_frames = atoi(arg);
1787 if (b_frames > FF_MAX_B_FRAMES) {
1788 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1790 } else if (b_frames < 1) {
1791 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1796 static void opt_mb_decision(const char *arg)
1798 mb_decision = atoi(arg);
1801 static void opt_mb_cmp(const char *arg)
1806 static void opt_sub_cmp(const char *arg)
1808 sub_cmp = atoi(arg);
1811 static void opt_cmp(const char *arg)
1816 static void opt_qscale(const char *arg)
1818 video_qscale = atof(arg);
1819 if (video_qscale < 0.01 ||
1820 video_qscale > 255) {
1821 fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
1826 static void opt_qmin(const char *arg)
1828 video_qmin = atoi(arg);
1829 if (video_qmin < 0 ||
1831 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1836 static void opt_qmax(const char *arg)
1838 video_qmax = atoi(arg);
1839 if (video_qmax < 0 ||
1841 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1846 static void opt_mb_qmin(const char *arg)
1848 video_mb_qmin = atoi(arg);
1849 if (video_mb_qmin < 0 ||
1850 video_mb_qmin > 31) {
1851 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1856 static void opt_mb_qmax(const char *arg)
1858 video_mb_qmax = atoi(arg);
1859 if (video_mb_qmax < 0 ||
1860 video_mb_qmax > 31) {
1861 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1866 static void opt_qdiff(const char *arg)
1868 video_qdiff = atoi(arg);
1869 if (video_qdiff < 0 ||
1871 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1876 static void opt_qblur(const char *arg)
1878 video_qblur = atof(arg);
1881 static void opt_qcomp(const char *arg)
1883 video_qcomp = atof(arg);
1886 static void opt_rc_initial_cplx(const char *arg)
1888 video_rc_initial_cplx = atof(arg);
1890 static void opt_b_qfactor(const char *arg)
1892 video_b_qfactor = atof(arg);
1894 static void opt_i_qfactor(const char *arg)
1896 video_i_qfactor = atof(arg);
1898 static void opt_b_qoffset(const char *arg)
1900 video_b_qoffset = atof(arg);
1902 static void opt_i_qoffset(const char *arg)
1904 video_i_qoffset = atof(arg);
1907 static void opt_packet_size(const char *arg)
1909 packet_size= atoi(arg);
1912 static void opt_error_rate(const char *arg)
1914 error_rate= atoi(arg);
1917 static void opt_strict(const char *arg)
1922 static void opt_audio_bitrate(const char *arg)
1924 audio_bit_rate = atoi(arg) * 1000;
1927 static void opt_audio_rate(const char *arg)
1929 audio_sample_rate = atoi(arg);
1932 static void opt_audio_channels(const char *arg)
1934 audio_channels = atoi(arg);
1937 static void opt_video_device(const char *arg)
1939 video_device = av_strdup(arg);
1942 static void opt_video_channel(const char *arg)
1944 video_channel = strtol(arg, NULL, 0);
1947 static void opt_video_standard(const char *arg)
1949 video_standard = av_strdup(arg);
1952 static void opt_audio_device(const char *arg)
1954 audio_device = av_strdup(arg);
1957 static void opt_dv1394(const char *arg)
1959 video_grab_format = "dv1394";
1960 audio_grab_format = NULL;
1963 static void opt_audio_codec(const char *arg)
1967 if (!strcmp(arg, "copy")) {
1968 audio_stream_copy = 1;
1972 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1977 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1980 audio_codec_id = p->id;
1985 static void add_frame_hooker(const char *arg)
1990 char *args = av_strdup(arg);
1994 argv[0] = strtok(args, " ");
1995 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1998 i = frame_hook_add(argc, argv);
2001 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2006 const char *motion_str[] = {
2016 static void opt_motion_estimation(const char *arg)
2022 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2025 if (!strcmp(*p, arg))
2029 me_method = (p - motion_str) + 1;
2032 static void opt_video_codec(const char *arg)
2036 if (!strcmp(arg, "copy")) {
2037 video_stream_copy = 1;
2041 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
2046 fprintf(stderr, "Unknown video codec '%s'\n", arg);
2049 video_codec_id = p->id;
2054 static void opt_map(const char *arg)
2060 m = &stream_maps[nb_stream_maps++];
2062 m->file_index = strtol(arg, (char **)&p, 0);
2066 m->stream_index = strtol(p, (char **)&p, 0);
2069 static void opt_recording_time(const char *arg)
2071 recording_time = parse_date(arg, 1);
2074 static void opt_start_time(const char *arg)
2076 start_time = parse_date(arg, 1);
2079 static void opt_input_file(const char *filename)
2081 AVFormatContext *ic;
2082 AVFormatParameters params, *ap = ¶ms;
2083 int err, i, ret, rfps, rfps_base;
2085 if (!strcmp(filename, "-"))
2088 using_stdin |= !strcmp(filename, "pipe:" ) ||
2089 !strcmp( filename, "/dev/stdin" );
2091 /* get default parameters from command line */
2092 memset(ap, 0, sizeof(*ap));
2093 ap->sample_rate = audio_sample_rate;
2094 ap->channels = audio_channels;
2095 ap->frame_rate = frame_rate;
2096 ap->frame_rate_base = frame_rate_base;
2097 ap->width = frame_width;
2098 ap->height = frame_height;
2099 ap->image_format = image_format;
2100 ap->pix_fmt = frame_pix_fmt;
2102 /* open the input file with generic libav function */
2103 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2105 print_error(filename, err);
2109 /* If not enough info to get the stream parameters, we decode the
2110 first frames to get it. (used in mpeg case for example) */
2111 ret = av_find_stream_info(ic);
2113 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2117 /* if seeking requested, we execute it */
2118 if (start_time != 0) {
2121 timestamp = start_time;
2122 /* add the stream start time */
2123 if (ic->start_time != AV_NOPTS_VALUE)
2124 timestamp += ic->start_time;
2125 ret = av_seek_frame(ic, -1, timestamp);
2127 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2128 filename, (double)timestamp / AV_TIME_BASE);
2130 /* reset seek info */
2134 /* update the current parameters so that they match the one of the input stream */
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:
2139 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2140 audio_channels = enc->channels;
2141 audio_sample_rate = enc->sample_rate;
2143 case CODEC_TYPE_VIDEO:
2144 frame_height = enc->height;
2145 frame_width = enc->width;
2146 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2147 frame_pix_fmt = enc->pix_fmt;
2148 rfps = ic->streams[i]->r_frame_rate;
2149 rfps_base = ic->streams[i]->r_frame_rate_base;
2150 enc->workaround_bugs = workaround_bugs;
2151 enc->error_resilience = error_resilience;
2152 enc->error_concealment = error_concealment;
2153 enc->idct_algo= idct_algo;
2156 enc->flags|= CODEC_FLAG_BITEXACT;
2158 assert(enc->frame_rate_base == rfps_base); // should be true for now
2159 if (enc->frame_rate != rfps) {
2160 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
2161 i, (float)enc->frame_rate / enc->frame_rate_base,
2162 (float)rfps / rfps_base);
2164 /* update the current frame rate to match the stream frame rate */
2166 frame_rate_base = rfps_base;
2168 enc->rate_emu = rate_emu;
2170 case CODEC_TYPE_DATA:
2177 input_files[nb_input_files] = ic;
2178 /* dump the file content */
2179 dump_format(ic, nb_input_files, filename, 0);
2181 file_iformat = NULL;
2182 file_oformat = NULL;
2183 image_format = NULL;
2188 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2190 int has_video, has_audio, i, j;
2191 AVFormatContext *ic;
2195 for(j=0;j<nb_input_files;j++) {
2196 ic = input_files[j];
2197 for(i=0;i<ic->nb_streams;i++) {
2198 AVCodecContext *enc = &ic->streams[i]->codec;
2199 switch(enc->codec_type) {
2200 case CODEC_TYPE_AUDIO:
2203 case CODEC_TYPE_VIDEO:
2211 *has_video_ptr = has_video;
2212 *has_audio_ptr = has_audio;
2215 static void opt_output_file(const char *filename)
2218 AVFormatContext *oc;
2219 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
2221 AVFormatParameters params, *ap = ¶ms;
2223 if (!strcmp(filename, "-"))
2226 oc = av_mallocz(sizeof(AVFormatContext));
2228 if (!file_oformat) {
2229 file_oformat = guess_format(NULL, filename, NULL);
2230 if (!file_oformat) {
2231 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
2237 oc->oformat = file_oformat;
2239 if (!strcmp(file_oformat->name, "ffm") &&
2240 strstart(filename, "http:", NULL)) {
2241 /* special case for files sent to ffserver: we get the stream
2242 parameters from ffserver */
2243 if (read_ffserver_streams(oc, filename) < 0) {
2244 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2248 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2249 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2251 /* disable if no corresponding type found and at least one
2253 if (nb_input_files > 0) {
2254 check_audio_video_inputs(&input_has_video, &input_has_audio);
2255 if (!input_has_video)
2257 if (!input_has_audio)
2261 /* manual disable */
2262 if (audio_disable) {
2265 if (video_disable) {
2271 AVCodecContext *video_enc;
2273 st = av_mallocz(sizeof(AVStream));
2275 fprintf(stderr, "Could not alloc stream\n");
2278 avcodec_get_context_defaults(&st->codec);
2280 video_enc = &st->codec;
2282 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2283 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2284 if (video_stream_copy) {
2285 st->stream_copy = 1;
2286 video_enc->codec_type = CODEC_TYPE_VIDEO;
2291 codec_id = file_oformat->video_codec;
2292 if (video_codec_id != CODEC_ID_NONE)
2293 codec_id = video_codec_id;
2295 video_enc->codec_id = codec_id;
2297 video_enc->bit_rate = video_bit_rate;
2298 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2299 video_enc->frame_rate = frame_rate;
2300 video_enc->frame_rate_base = frame_rate_base;
2302 video_enc->width = frame_width;
2303 video_enc->height = frame_height;
2304 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
2305 video_enc->pix_fmt = frame_pix_fmt;
2308 video_enc->gop_size = gop_size;
2310 video_enc->gop_size = 0;
2311 if (video_qscale || same_quality) {
2312 video_enc->flags |= CODEC_FLAG_QSCALE;
2313 st->quality = FF_QP2LAMBDA * video_qscale;
2317 video_enc->intra_matrix = intra_matrix;
2319 video_enc->inter_matrix = inter_matrix;
2322 video_enc->flags |= CODEC_FLAG_BITEXACT;
2324 video_enc->mb_decision = mb_decision;
2325 video_enc->mb_cmp = mb_cmp;
2326 video_enc->me_sub_cmp = sub_cmp;
2327 video_enc->me_cmp = cmp;
2330 video_enc->flags |= CODEC_FLAG_H263P_UMV;
2333 video_enc->flags |= CODEC_FLAG_H263P_AIC;
2336 video_enc->flags |= CODEC_FLAG_H263P_AIV;
2339 video_enc->flags |= CODEC_FLAG_4MV;
2342 video_enc->flags |= CODEC_FLAG_OBMC;
2346 video_enc->flags |= CODEC_FLAG_PART;
2349 video_enc->max_b_frames = b_frames;
2350 video_enc->b_frame_strategy = 0;
2351 video_enc->b_quant_factor = 2.0;
2354 video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
2356 video_enc->qmin = video_qmin;
2357 video_enc->qmax = video_qmax;
2358 video_enc->mb_qmin = video_mb_qmin;
2359 video_enc->mb_qmax = video_mb_qmax;
2360 video_enc->max_qdiff = video_qdiff;
2361 video_enc->qblur = video_qblur;
2362 video_enc->qcompress = video_qcomp;
2363 video_enc->rc_eq = video_rc_eq;
2364 video_enc->debug= debug;
2366 p= video_rc_override_string;
2369 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2371 fprintf(stderr, "error parsing rc_override\n");
2374 video_enc->rc_override=
2375 av_realloc(video_enc->rc_override,
2376 sizeof(RcOverride)*(i+1));
2377 video_enc->rc_override[i].start_frame= start;
2378 video_enc->rc_override[i].end_frame = end;
2380 video_enc->rc_override[i].qscale= q;
2381 video_enc->rc_override[i].quality_factor= 1.0;
2384 video_enc->rc_override[i].qscale= 0;
2385 video_enc->rc_override[i].quality_factor= -q/100.0;
2390 video_enc->rc_override_count=i;
2392 video_enc->rc_max_rate = video_rc_max_rate;
2393 video_enc->rc_min_rate = video_rc_min_rate;
2394 video_enc->rc_buffer_size = video_rc_buffer_size;
2395 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2396 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2397 video_enc->i_quant_factor = video_i_qfactor;
2398 video_enc->b_quant_factor = video_b_qfactor;
2399 video_enc->i_quant_offset = video_i_qoffset;
2400 video_enc->b_quant_offset = video_b_qoffset;
2401 video_enc->dct_algo = dct_algo;
2402 video_enc->idct_algo = idct_algo;
2403 video_enc->strict_std_compliance = strict;
2404 video_enc->error_rate = error_rate;
2406 video_enc->rtp_mode= 1;
2407 video_enc->rtp_payload_size= packet_size;
2411 video_enc->flags|= CODEC_FLAG_PSNR;
2413 video_enc->me_method = me_method;
2418 video_enc->flags |= CODEC_FLAG_PASS1;
2420 video_enc->flags |= CODEC_FLAG_PASS2;
2424 oc->streams[nb_streams] = st;
2429 AVCodecContext *audio_enc;
2431 st = av_mallocz(sizeof(AVStream));
2433 fprintf(stderr, "Could not alloc stream\n");
2436 avcodec_get_context_defaults(&st->codec);
2438 audio_enc = &st->codec;
2439 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2441 if(!strcmp(file_oformat->name, "mp4") || !strcmp(file_oformat->name, "mov") || !strcmp(file_oformat->name, "3gp"))
2442 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2443 if (audio_stream_copy) {
2444 st->stream_copy = 1;
2446 codec_id = file_oformat->audio_codec;
2447 if (audio_codec_id != CODEC_ID_NONE)
2448 codec_id = audio_codec_id;
2449 audio_enc->codec_id = codec_id;
2451 audio_enc->bit_rate = audio_bit_rate;
2452 audio_enc->sample_rate = audio_sample_rate;
2453 /* For audio codecs other than AC3 we limit */
2454 /* the number of coded channels to stereo */
2455 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2456 audio_enc->channels = 2;
2458 audio_enc->channels = audio_channels;
2460 oc->streams[nb_streams] = st;
2464 oc->nb_streams = nb_streams;
2467 fprintf(stderr, "No audio or video streams available\n");
2472 pstrcpy(oc->title, sizeof(oc->title), str_title);
2474 pstrcpy(oc->author, sizeof(oc->author), str_author);
2476 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2478 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2481 output_files[nb_output_files++] = oc;
2483 strcpy(oc->filename, filename);
2485 /* check filename in case of an image number is expected */
2486 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2487 if (filename_number_test(oc->filename) < 0) {
2488 print_error(oc->filename, AVERROR_NUMEXPECTED);
2493 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2494 /* test if it already exists to avoid loosing precious files */
2495 if (!file_overwrite &&
2496 (strchr(filename, ':') == NULL ||
2497 strstart(filename, "file:", NULL))) {
2498 if (url_exist(filename)) {
2501 if ( !using_stdin ) {
2502 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
2505 if (toupper(c) != 'Y') {
2506 fprintf(stderr, "Not overwriting - exiting\n");
2511 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
2518 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2519 fprintf(stderr, "Could not open '%s'\n", filename);
2524 memset(ap, 0, sizeof(*ap));
2525 ap->image_format = image_format;
2526 if (av_set_parameters(oc, ap) < 0) {
2527 fprintf(stderr, "%s: Invalid encoding parameters\n",
2532 /* reset some options */
2533 file_oformat = NULL;
2534 file_iformat = NULL;
2535 image_format = NULL;
2538 audio_codec_id = CODEC_ID_NONE;
2539 video_codec_id = CODEC_ID_NONE;
2540 audio_stream_copy = 0;
2541 video_stream_copy = 0;
2544 /* prepare dummy protocols for grab */
2545 static void prepare_grab(void)
2547 int has_video, has_audio, i, j;
2548 AVFormatContext *oc;
2549 AVFormatContext *ic;
2550 AVFormatParameters vp1, *vp = &vp1;
2551 AVFormatParameters ap1, *ap = &ap1;
2553 /* see if audio/video inputs are needed */
2556 memset(ap, 0, sizeof(*ap));
2557 memset(vp, 0, sizeof(*vp));
2558 for(j=0;j<nb_output_files;j++) {
2559 oc = output_files[j];
2560 for(i=0;i<oc->nb_streams;i++) {
2561 AVCodecContext *enc = &oc->streams[i]->codec;
2562 switch(enc->codec_type) {
2563 case CODEC_TYPE_AUDIO:
2564 if (enc->sample_rate > ap->sample_rate)
2565 ap->sample_rate = enc->sample_rate;
2566 if (enc->channels > ap->channels)
2567 ap->channels = enc->channels;
2570 case CODEC_TYPE_VIDEO:
2571 if (enc->width > vp->width)
2572 vp->width = enc->width;
2573 if (enc->height > vp->height)
2574 vp->height = enc->height;
2576 assert(enc->frame_rate_base == DEFAULT_FRAME_RATE_BASE);
2577 if (enc->frame_rate > vp->frame_rate){
2578 vp->frame_rate = enc->frame_rate;
2579 vp->frame_rate_base = enc->frame_rate_base;
2589 if (has_video == 0 && has_audio == 0) {
2590 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2595 AVInputFormat *fmt1;
2596 fmt1 = av_find_input_format(video_grab_format);
2597 vp->device = video_device;
2598 vp->channel = video_channel;
2599 vp->standard = video_standard;
2600 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
2601 fprintf(stderr, "Could not find video grab device\n");
2604 /* If not enough info to get the stream parameters, we decode the
2605 first frames to get it. */
2606 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
2607 fprintf(stderr, "Could not find video grab parameters\n");
2610 /* by now video grab has one stream */
2611 ic->streams[0]->r_frame_rate = vp->frame_rate;
2612 ic->streams[0]->r_frame_rate_base = vp->frame_rate_base;
2613 input_files[nb_input_files] = ic;
2614 dump_format(ic, nb_input_files, "", 0);
2617 if (has_audio && audio_grab_format) {
2618 AVInputFormat *fmt1;
2619 fmt1 = av_find_input_format(audio_grab_format);
2620 ap->device = audio_device;
2621 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2622 fprintf(stderr, "Could not find audio grab device\n");
2625 input_files[nb_input_files] = ic;
2626 dump_format(ic, nb_input_files, "", 0);
2631 /* same option as mencoder */
2632 static void opt_pass(const char *pass_str)
2635 pass = atoi(pass_str);
2636 if (pass != 1 && pass != 2) {
2637 fprintf(stderr, "pass number can be only 1 or 2\n");
2643 #if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
2644 static int64_t getutime(void)
2646 return av_gettime();
2649 static int64_t getutime(void)
2651 struct rusage rusage;
2653 getrusage(RUSAGE_SELF, &rusage);
2654 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2658 extern int ffm_nopts;
2660 static void opt_bitexact(void)
2663 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2667 static void show_formats(void)
2669 AVInputFormat *ifmt;
2670 AVOutputFormat *ofmt;
2671 AVImageFormat *image_fmt;
2676 printf("Output audio/video file formats:");
2677 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2678 printf(" %s", ofmt->name);
2682 printf("Input audio/video file formats:");
2683 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2684 printf(" %s", ifmt->name);
2688 printf("Output image formats:");
2689 for(image_fmt = first_image_format; image_fmt != NULL;
2690 image_fmt = image_fmt->next) {
2691 if (image_fmt->img_write)
2692 printf(" %s", image_fmt->name);
2696 printf("Input image formats:");
2697 for(image_fmt = first_image_format; image_fmt != NULL;
2698 image_fmt = image_fmt->next) {
2699 if (image_fmt->img_read)
2700 printf(" %s", image_fmt->name);
2704 printf("Codecs:\n");
2705 printf(" Encoders:");
2706 for(p = first_avcodec; p != NULL; p = p->next) {
2708 printf(" %s", p->name);
2712 printf(" Decoders:");
2713 for(p = first_avcodec; p != NULL; p = p->next) {
2715 printf(" %s", p->name);
2719 printf("Supported file protocols:");
2720 for(up = first_protocol; up != NULL; up = up->next)
2721 printf(" %s:", up->name);
2724 printf("Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
2725 printf("Motion estimation methods:");
2729 if ((pp - motion_str + 1) == ME_ZERO)
2730 printf("(fastest)");
2731 else if ((pp - motion_str + 1) == ME_FULL)
2732 printf("(slowest)");
2733 else if ((pp - motion_str + 1) == ME_EPZS)
2734 printf("(default)");
2741 void parse_matrix_coeffs(uint16_t *dest, const char *str)
2744 const char *p = str;
2751 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
2758 void opt_inter_matrix(const char *arg)
2760 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
2761 parse_matrix_coeffs(inter_matrix, arg);
2764 void opt_intra_matrix(const char *arg)
2766 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
2767 parse_matrix_coeffs(intra_matrix, arg);
2770 static void opt_target(const char *arg)
2774 if(!strncmp(arg, "pal-", 4)) {
2777 } else if(!strncmp(arg, "ntsc-", 5)) {
2782 /* Calculate FR via float to avoid int overflow */
2783 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
2786 } else if((fr == 29970) || (fr == 23976)) {
2789 /* Try to determine PAL/NTSC by peeking in the input files */
2790 if(nb_input_files) {
2792 for(j = 0; j < nb_input_files; j++) {
2793 for(i = 0; i < input_files[j]->nb_streams; i++) {
2794 AVCodecContext *c = &input_files[j]->streams[i]->codec;
2795 if(c->codec_type != CODEC_TYPE_VIDEO)
2797 fr = c->frame_rate * 1000 / c->frame_rate_base;
2801 } else if((fr == 29970) || (fr == 23976)) {
2811 if(verbose && norm >= 0)
2812 printf("Assuming %s for target.\n", norm ? "NTSC" : "PAL");
2816 fprintf(stderr, "Could not determine norm (PAL/NTSC) for target.\n");
2817 fprintf(stderr, "Please prefix target with \"pal-\" or \"ntsc-\",\n");
2818 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
2822 if(!strcmp(arg, "vcd")) {
2824 opt_video_codec("mpeg1video");
2825 opt_audio_codec("mp2");
2828 opt_frame_size(norm ? "352x240" : "352x288");
2830 video_bit_rate = 1150000;
2831 video_rc_max_rate = 1150000;
2832 video_rc_min_rate = 1150000;
2833 video_rc_buffer_size = 40*1024*8;
2835 audio_bit_rate = 224000;
2836 audio_sample_rate = 44100;
2838 } else if(!strcmp(arg, "svcd")) {
2840 opt_video_codec("mpeg2video");
2841 opt_audio_codec("mp2");
2844 opt_frame_size(norm ? "480x480" : "480x576");
2845 opt_gop_size(norm ? "18" : "15");
2847 video_bit_rate = 2040000;
2848 video_rc_max_rate = 2516000;
2849 video_rc_min_rate = 1145000;
2850 video_rc_buffer_size = 224*1024*8;
2852 audio_bit_rate = 224000;
2853 audio_sample_rate = 44100;
2855 } else if(!strcmp(arg, "dvd")) {
2857 opt_video_codec("mpeg2video");
2858 opt_audio_codec("ac3");
2861 opt_frame_size(norm ? "720x480" : "720x576");
2862 opt_gop_size(norm ? "18" : "15");
2864 video_bit_rate = 6000000;
2865 video_rc_max_rate = 9000000;
2866 video_rc_min_rate = 1500000;
2867 video_rc_buffer_size = 224*1024*8;
2869 audio_bit_rate = 448000;
2870 audio_sample_rate = 48000;
2873 fprintf(stderr, "Unknown target: %s\n", arg);
2878 const OptionDef options[] = {
2880 { "L", 0, {(void*)show_license}, "show license" },
2881 { "h", 0, {(void*)show_help}, "show help" },
2882 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2883 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2884 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
2885 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2886 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2887 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2888 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2889 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
2890 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2891 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2892 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2893 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2894 { "debug", HAS_ARG | OPT_EXPERT, {(void*)opt_debug}, "print specific debug info", "" },
2895 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2896 "add timings for benchmarking" },
2897 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
2898 "dump each input packet" },
2899 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2900 "when dumping packets, also dump the payload" },
2901 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2902 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
2903 { "loop", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
2904 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
2905 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\" or \"dvd\")", "type" },
2908 { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2909 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
2910 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2911 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
2912 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
2913 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2914 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2915 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2916 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2917 { "g", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2918 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
2919 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
2920 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2921 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2922 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2923 { "mbqmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmin}, "min macroblock quantiser scale (VBR)", "q" },
2924 { "mbqmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_qmax}, "max macroblock quantiser scale (VBR)", "q" },
2925 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2926 { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2927 { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2928 { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2929 { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2930 { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2931 { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2932 { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2933 // { "b_strategy", HAS_ARG | OPT_EXPERT, {(void*)opt_b_strategy}, "dynamic b frame selection strategy", "strategy" },
2934 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
2935 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
2936 { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2937 { "maxrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2938 { "minrate", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2939 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2940 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2941 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
2943 { "dct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2944 { "idct_algo", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2945 { "er", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_resilience}, "set error resilience", "n" },
2946 { "ec", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_error_concealment}, "set error concealment", "bit_mask" },
2947 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
2948 { "hq", OPT_BOOL, {(void*)&mb_decision}, "activate high quality settings" },
2949 { "mbd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_decision}, "macroblock decision", "mode" },
2950 { "mbcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_cmp}, "macroblock compare function", "cmp function" },
2951 { "subcmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sub_cmp}, "subpel compare function", "cmp function" },
2952 { "cmp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_cmp}, "fullpel compare function", "cmp function" },
2953 { "4mv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_4mv}, "use four motion vector by macroblock (MPEG4)" },
2954 { "obmc", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_obmc}, "use overlapped block motion compensation (h263+)" },
2955 { "part", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_part}, "use data partitioning (MPEG4)" },
2956 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2957 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
2958 { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
2959 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standarts", "strictness" },
2960 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
2961 "use same video quality as source (implies VBR)" },
2962 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2963 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2964 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
2965 "deinterlace pictures" },
2966 { "interlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_interlace},
2967 "force interlacing support in encoder (MPEG2/MPEG4)" },
2968 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2969 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
2970 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
2971 { "aic", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aic}, "enable Advanced intra coding (h263+)" },
2972 { "aiv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_aiv}, "enable Alternative inter vlc (h263+)" },
2973 { "umv", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&use_umv}, "enable Unlimited Motion Vector (h263+)" },
2974 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
2975 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
2978 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2979 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2980 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2981 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
2982 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2985 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
2986 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
2987 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
2988 { "dv1394", OPT_EXPERT | OPT_GRAB, {(void*)opt_dv1394}, "set DV1394 grab", "" },
2989 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
2993 static void show_banner(void)
2995 printf("ffmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
2998 static void show_license(void)
3002 "This library is free software; you can redistribute it and/or\n"
3003 "modify it under the terms of the GNU Lesser General Public\n"
3004 "License as published by the Free Software Foundation; either\n"
3005 "version 2 of the License, or (at your option) any later version.\n"
3007 "This library is distributed in the hope that it will be useful,\n"
3008 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
3009 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
3010 "Lesser General Public License for more details.\n"
3012 "You should have received a copy of the GNU Lesser General Public\n"
3013 "License along with this library; if not, write to the Free Software\n"
3014 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
3019 static void show_help(void)
3022 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
3023 "Hyper fast Audio and Video encoder\n");
3025 show_help_options(options, "Main options:\n",
3026 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
3027 show_help_options(options, "\nVideo options:\n",
3028 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3030 show_help_options(options, "\nAdvanced Video options:\n",
3031 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3032 OPT_VIDEO | OPT_EXPERT);
3033 show_help_options(options, "\nAudio options:\n",
3034 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3036 show_help_options(options, "\nAdvanced Audio options:\n",
3037 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3038 OPT_AUDIO | OPT_EXPERT);
3039 show_help_options(options, "\nAudio/Video grab options:\n",
3042 show_help_options(options, "\nAdvanced options:\n",
3043 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3048 void parse_arg_file(const char *filename)
3050 opt_output_file(filename);
3053 int main(int argc, char **argv)
3064 parse_options(argc, argv, options);
3066 /* file converter / grab */
3067 if (nb_output_files <= 0) {
3068 fprintf(stderr, "Must supply at least one output file\n");
3072 if (nb_input_files == 0) {
3077 av_encode(output_files, nb_output_files, input_files, nb_input_files,
3078 stream_maps, nb_stream_maps);
3079 ti = getutime() - ti;
3081 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3085 for(i=0;i<nb_output_files;i++) {
3086 /* maybe av_close_output_file ??? */
3087 AVFormatContext *s = output_files[i];
3089 if (!(s->oformat->flags & AVFMT_NOFILE))
3091 for(j=0;j<s->nb_streams;j++)
3092 av_free(s->streams[j]);
3095 for(i=0;i<nb_input_files;i++)
3096 av_close_input_file(input_files[i]);
3101 av_free(intra_matrix);
3103 av_free(inter_matrix);
3105 #ifdef POWERPC_PERFORMANCE_REPORT
3106 extern void powerpc_display_perf_report(void);
3107 powerpc_display_perf_report();
3108 #endif /* POWERPC_PERFORMANCE_REPORT */
3110 #ifndef CONFIG_WIN32
3111 if (received_sigterm) {
3113 "Received signal %d: terminating.\n",
3114 (int) received_sigterm);
3118 exit(0); /* not all OS-es handle main() return value */