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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #define HAVE_AV_CONFIG_H
23 #include "framehook.h"
30 #include <sys/ioctl.h>
33 #include <sys/resource.h>
37 #include <sys/types.h>
38 #include <sys/select.h>
41 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
50 #if !defined(INFINITY) && defined(HUGE_VAL)
51 #define INFINITY HUGE_VAL
54 /* select an input stream for an output stream */
55 typedef struct AVStreamMap {
59 int sync_stream_index;
62 /** select an input file for an output file */
63 typedef struct AVMetaDataMap {
68 extern const OptionDef options[];
70 static void show_help(void);
71 static void show_license(void);
72 static int opt_default(const char *opt, const char *arg);
76 static AVFormatContext *input_files[MAX_FILES];
77 static int64_t input_files_ts_offset[MAX_FILES];
78 static int nb_input_files = 0;
80 static AVFormatContext *output_files[MAX_FILES];
81 static int nb_output_files = 0;
83 static AVStreamMap stream_maps[MAX_FILES];
84 static int nb_stream_maps;
86 static AVMetaDataMap meta_data_maps[MAX_FILES];
87 static int nb_meta_data_maps;
89 static AVInputFormat *file_iformat;
90 static AVOutputFormat *file_oformat;
91 static AVImageFormat *image_format;
92 static int frame_width = 0;
93 static int frame_height = 0;
94 static float frame_aspect_ratio = 0;
95 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
96 static int frame_padtop = 0;
97 static int frame_padbottom = 0;
98 static int frame_padleft = 0;
99 static int frame_padright = 0;
100 static int padcolor[3] = {16,128,128}; /* default to black */
101 static int frame_topBand = 0;
102 static int frame_bottomBand = 0;
103 static int frame_leftBand = 0;
104 static int frame_rightBand = 0;
105 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
106 static int frame_rate = 25;
107 static int frame_rate_base = 1;
108 static float video_qscale = 0;
109 static int video_qmin = 2;
110 static int video_qmax = 31;
111 static int video_lmin = 2*FF_QP2LAMBDA;
112 static int video_lmax = 31*FF_QP2LAMBDA;
113 static int video_mb_lmin = 2*FF_QP2LAMBDA;
114 static int video_mb_lmax = 31*FF_QP2LAMBDA;
115 static int video_qdiff = 3;
116 static float video_qsquish = 0.0;
117 static uint16_t *intra_matrix = NULL;
118 static uint16_t *inter_matrix = NULL;
119 #if 0 //experimental, (can be removed)
120 static float video_rc_qsquish=1.0;
121 static float video_rc_qmod_amp=0;
122 static int video_rc_qmod_freq=0;
124 static char *video_rc_override_string=NULL;
125 static char *video_rc_eq="tex^qComp";
126 static int video_rc_buffer_size=0;
127 static float video_rc_buffer_aggressivity=1.0;
128 static int me_method = ME_EPZS;
129 static int video_disable = 0;
130 static int video_discard = 0;
131 static int video_codec_id = CODEC_ID_NONE;
132 static int video_codec_tag = 0;
133 static int same_quality = 0;
134 static int b_frames = 0;
135 static int do_deinterlace = 0;
136 static int workaround_bugs = FF_BUG_AUTODETECT;
137 static int packet_size = 0;
138 static int error_rate = 0;
139 static int strict = 0;
140 static int top_field_first = -1;
141 static int sc_threshold = 0;
142 static int me_threshold = 0;
143 static int mb_threshold = 0;
144 static int intra_dc_precision = 8;
145 static int me_penalty_compensation= 256;
146 static int frame_skip_threshold= 0;
147 static int frame_skip_factor= 0;
148 static int frame_skip_exp= 0;
149 static int loop_input = 0;
150 static int loop_output = AVFMT_NOOUTPUTLOOP;
151 static int qp_hist = 0;
153 static int intra_only = 0;
154 static int audio_sample_rate = 44100;
155 static int audio_bit_rate = 64000;
156 #define QSCALE_NONE -99999
157 static float audio_qscale = QSCALE_NONE;
158 static int audio_disable = 0;
159 static int audio_channels = 1;
160 static int audio_codec_id = CODEC_ID_NONE;
161 static int audio_codec_tag = 0;
162 static char *audio_language = NULL;
164 static int subtitle_codec_id = CODEC_ID_NONE;
165 static char *subtitle_language = NULL;
167 static int mux_rate= 0;
168 static int mux_packet_size= 0;
169 static float mux_preload= 0.5;
170 static float mux_max_delay= 0.7;
172 static int64_t recording_time = 0;
173 static int64_t start_time = 0;
174 static int64_t rec_timestamp = 0;
175 static int64_t input_ts_offset = 0;
176 static int file_overwrite = 0;
177 static char *str_title = NULL;
178 static char *str_author = NULL;
179 static char *str_copyright = NULL;
180 static char *str_comment = NULL;
181 static char *str_album = NULL;
182 static int do_benchmark = 0;
183 static int do_hex_dump = 0;
184 static int do_pkt_dump = 0;
185 static int do_psnr = 0;
186 static int do_vstats = 0;
187 static int do_pass = 0;
188 static char *pass_logfilename = NULL;
189 static int audio_stream_copy = 0;
190 static int video_stream_copy = 0;
191 static int subtitle_stream_copy = 0;
192 static int video_sync_method= 1;
193 static int audio_sync_method= 0;
194 static int copy_ts= 0;
195 static int opt_shortest = 0; //
196 static int video_global_header = 0;
198 static int rate_emu = 0;
201 static const char *video_grab_format = "bktr";
203 #ifdef CONFIG_VIDEO4LINUX2
204 static const char *video_grab_format = "video4linux2";
206 static const char *video_grab_format = "video4linux";
209 static char *video_device = NULL;
210 static char *grab_device = NULL;
211 static int video_channel = 0;
212 static char *video_standard = "ntsc";
214 static const char *audio_grab_format = "audio_device";
215 static char *audio_device = NULL;
216 static int audio_volume = 256;
218 static int using_stdin = 0;
219 static int using_vhook = 0;
220 static int verbose = 1;
221 static int thread_count= 1;
222 static int q_pressed = 0;
223 static int64_t video_size = 0;
224 static int64_t audio_size = 0;
225 static int64_t extra_size = 0;
226 static int nb_frames_dup = 0;
227 static int nb_frames_drop = 0;
228 static int input_sync;
229 static int limit_filesize = 0; //
231 static int pgmyuv_compatibility_hack=0;
232 static int dts_delta_threshold = 10;
234 static int sws_flags = SWS_BICUBIC;
236 const char **opt_names=NULL;
237 int opt_name_count=0;
238 AVCodecContext *avctx_opts;
239 AVFormatContext *avformat_opts;
241 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
242 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
243 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
245 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
247 struct AVInputStream;
249 typedef struct AVOutputStream {
250 int file_index; /* file index */
251 int index; /* stream index in the output file */
252 int source_index; /* AVInputStream index */
253 AVStream *st; /* stream in the output file */
254 int encoding_needed; /* true if encoding needed for this stream */
256 /* input pts and corresponding output pts
258 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
259 struct AVInputStream *sync_ist; /* input stream to sync against */
260 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
263 AVFrame pict_tmp; /* temporary image for resampling */
264 struct SwsContext *img_resample_ctx; /* for image resampling */
268 int topBand; /* cropping area sizes */
272 int padtop; /* padding area sizes */
279 ReSampleContext *resample; /* for audio resampling */
280 FifoBuffer fifo; /* for compression: one audio fifo per codec */
284 typedef struct AVInputStream {
288 int discard; /* true if stream data should be discarded */
289 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
290 int64_t sample_index; /* current sample */
292 int64_t start; /* time when read started */
293 unsigned long frame; /* current frame */
294 int64_t next_pts; /* synthetic pts for cases where pkt.pts
296 int64_t pts; /* current pts */
297 int is_start; /* is 1 at the start and after a discontinuity */
300 typedef struct AVInputFile {
301 int eof_reached; /* true if eof reached */
302 int ist_index; /* index of first stream in ist_table */
303 int buffer_size; /* current total buffer size */
304 int buffer_size_max; /* buffer size at which we consider we can stop
306 int nb_streams; /* nb streams we are aware of */
311 /* init terminal so that we can grab keys */
312 static struct termios oldtty;
314 static void term_exit(void)
316 tcsetattr (0, TCSANOW, &oldtty);
319 static volatile sig_atomic_t received_sigterm = 0;
322 sigterm_handler(int sig)
324 received_sigterm = sig;
328 static void term_init(void)
335 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
336 |INLCR|IGNCR|ICRNL|IXON);
337 tty.c_oflag |= OPOST;
338 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
339 tty.c_cflag &= ~(CSIZE|PARENB);
344 tcsetattr (0, TCSANOW, &tty);
346 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
347 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
348 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
350 register a function to be called at normal program termination
353 #ifdef CONFIG_BEOS_NETSERVER
354 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
358 /* read a key without blocking */
359 static int read_key(void)
363 #ifndef CONFIG_BEOS_NETSERVER
371 n = select(1, &rfds, NULL, NULL, &tv);
383 static int decode_interrupt_cb(void)
385 return q_pressed || (q_pressed = read_key() == 'q');
390 static volatile int received_sigterm = 0;
392 /* no interactive support */
393 static void term_exit(void)
397 static void term_init(void)
401 static int read_key(void)
408 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
413 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
416 /* copy stream format */
417 s->nb_streams = ic->nb_streams;
418 for(i=0;i<ic->nb_streams;i++) {
421 // FIXME: a more elegant solution is needed
422 st = av_mallocz(sizeof(AVStream));
423 memcpy(st, ic->streams[i], sizeof(AVStream));
424 st->codec = avcodec_alloc_context();
425 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
429 av_close_input_file(ic);
434 get_sync_ipts(const AVOutputStream *ost)
436 const AVInputStream *ist = ost->sync_ist;
437 return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
440 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
442 AVPacket new_pkt= *pkt;
443 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
444 &new_pkt.data, &new_pkt.size,
445 pkt->data, pkt->size,
446 pkt->flags & PKT_FLAG_KEY);
449 new_pkt.destruct= av_destruct_packet;
456 av_interleaved_write_frame(s, pkt);
459 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
461 static void do_audio_out(AVFormatContext *s,
464 unsigned char *buf, int size)
467 static uint8_t *audio_buf = NULL;
468 static uint8_t *audio_out = NULL;
469 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
471 int size_out, frame_bytes, ret;
472 AVCodecContext *enc= ost->st->codec;
474 /* SC: dynamic allocation of buffers */
476 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
478 audio_out = av_malloc(audio_out_size);
479 if (!audio_buf || !audio_out)
480 return; /* Should signal an error ! */
482 if(audio_sync_method){
483 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
484 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
485 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
486 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
488 //FIXME resample delay
489 if(fabs(delta) > 50){
492 byte_delta= FFMAX(byte_delta, -size);
496 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
501 static uint8_t *input_tmp= NULL;
502 input_tmp= av_realloc(input_tmp, byte_delta + size);
504 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
507 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
509 memset(input_tmp, 0, byte_delta);
510 memcpy(input_tmp + byte_delta, buf, size);
514 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
516 }else if(audio_sync_method>1){
517 int comp= clip(delta, -audio_sync_method, audio_sync_method);
518 assert(ost->audio_resample);
520 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
521 // fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2));
522 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
526 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
527 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
529 if (ost->audio_resample) {
531 size_out = audio_resample(ost->resample,
532 (short *)buftmp, (short *)buf,
533 size / (ist->st->codec->channels * 2));
534 size_out = size_out * enc->channels * 2;
540 /* now encode as many frames as possible */
541 if (enc->frame_size > 1) {
542 /* output resampled raw samples */
543 fifo_write(&ost->fifo, buftmp, size_out,
546 frame_bytes = enc->frame_size * 2 * enc->channels;
548 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
549 &ost->fifo.rptr) == 0) {
551 av_init_packet(&pkt);
553 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
556 pkt.stream_index= ost->index;
559 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
560 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
561 pkt.flags |= PKT_FLAG_KEY;
562 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
564 ost->sync_opts += enc->frame_size;
568 av_init_packet(&pkt);
570 ost->sync_opts += size_out / (2 * enc->channels);
572 /* output a pcm frame */
573 /* XXX: change encoding codec API to avoid this ? */
574 switch(enc->codec->id) {
575 case CODEC_ID_PCM_S32LE:
576 case CODEC_ID_PCM_S32BE:
577 case CODEC_ID_PCM_U32LE:
578 case CODEC_ID_PCM_U32BE:
579 size_out = size_out << 1;
581 case CODEC_ID_PCM_S24LE:
582 case CODEC_ID_PCM_S24BE:
583 case CODEC_ID_PCM_U24LE:
584 case CODEC_ID_PCM_U24BE:
585 case CODEC_ID_PCM_S24DAUD:
586 size_out = size_out / 2 * 3;
588 case CODEC_ID_PCM_S16LE:
589 case CODEC_ID_PCM_S16BE:
590 case CODEC_ID_PCM_U16LE:
591 case CODEC_ID_PCM_U16BE:
594 size_out = size_out >> 1;
597 ret = avcodec_encode_audio(enc, audio_out, size_out,
600 pkt.stream_index= ost->index;
603 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
604 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
605 pkt.flags |= PKT_FLAG_KEY;
606 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
610 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
614 AVPicture picture_tmp;
617 dec = ist->st->codec;
619 /* deinterlace : must be done before any resize */
620 if (do_deinterlace || using_vhook) {
623 /* create temporary picture */
624 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
625 buf = av_malloc(size);
629 picture2 = &picture_tmp;
630 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
633 if(avpicture_deinterlace(picture2, picture,
634 dec->pix_fmt, dec->width, dec->height) < 0) {
635 /* if error, do not deinterlace */
641 img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
647 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
649 if (picture != picture2)
650 *picture = *picture2;
654 /* we begin to correct av delay at this threshold */
655 #define AV_DELAY_MAX 0.100
657 static void do_subtitle_out(AVFormatContext *s,
663 static uint8_t *subtitle_out = NULL;
664 int subtitle_out_max_size = 65536;
665 int subtitle_out_size, nb, i;
669 if (pts == AV_NOPTS_VALUE) {
670 fprintf(stderr, "Subtitle packets must have a pts\n");
674 enc = ost->st->codec;
677 subtitle_out = av_malloc(subtitle_out_max_size);
680 /* Note: DVB subtitle need one packet to draw them and one other
681 packet to clear them */
682 /* XXX: signal it in the codec context ? */
683 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
688 for(i = 0; i < nb; i++) {
689 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
690 subtitle_out_max_size, sub);
692 av_init_packet(&pkt);
693 pkt.stream_index = ost->index;
694 pkt.data = subtitle_out;
695 pkt.size = subtitle_out_size;
696 pkt.pts = av_rescale_q(av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
697 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
698 /* XXX: the pts correction is handled here. Maybe handling
699 it in the codec would be better */
701 pkt.pts += 90 * sub->start_display_time;
703 pkt.pts += 90 * sub->end_display_time;
705 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
709 static int bit_buffer_size= 1024*256;
710 static uint8_t *bit_buffer= NULL;
712 static void do_video_out(AVFormatContext *s,
718 int nb_frames, i, ret;
719 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
720 AVFrame picture_crop_temp, picture_pad_temp;
721 uint8_t *buf = NULL, *buf1 = NULL;
722 AVCodecContext *enc, *dec;
724 avcodec_get_frame_defaults(&picture_crop_temp);
725 avcodec_get_frame_defaults(&picture_pad_temp);
727 enc = ost->st->codec;
728 dec = ist->st->codec;
730 /* by default, we output a single frame */
735 if(video_sync_method){
737 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
738 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
741 else if (vdelta > 1.1)
742 nb_frames = lrintf(vdelta);
743 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
747 fprintf(stderr, "*** drop!\n");
748 }else if (nb_frames > 1) {
749 nb_frames_dup += nb_frames;
751 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
754 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
756 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
760 if (ost->video_crop) {
761 if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
762 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
765 formatted_picture = &picture_crop_temp;
767 formatted_picture = in_picture;
770 final_picture = formatted_picture;
771 padding_src = formatted_picture;
772 resampling_dst = &ost->pict_tmp;
773 if (ost->video_pad) {
774 final_picture = &ost->pict_tmp;
775 if (ost->video_resample) {
776 if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
777 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
780 resampling_dst = &picture_pad_temp;
784 if (ost->video_resample) {
786 final_picture = &ost->pict_tmp;
787 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
788 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
791 if (ost->video_pad) {
792 img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
793 enc->height, enc->width, enc->pix_fmt,
794 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
797 /* duplicates frame if needed */
798 for(i=0;i<nb_frames;i++) {
800 av_init_packet(&pkt);
801 pkt.stream_index= ost->index;
803 if (s->oformat->flags & AVFMT_RAWPICTURE) {
804 /* raw pictures are written as AVPicture structure to
805 avoid any copies. We support temorarily the older
807 AVFrame* old_frame = enc->coded_frame;
808 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
809 pkt.data= (uint8_t *)final_picture;
810 pkt.size= sizeof(AVPicture);
811 if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
812 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
813 if(dec->coded_frame && dec->coded_frame->key_frame)
814 pkt.flags |= PKT_FLAG_KEY;
816 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
817 enc->coded_frame = old_frame;
821 big_picture= *final_picture;
822 /* better than nothing: use input picture interlaced
824 big_picture.interlaced_frame = in_picture->interlaced_frame;
825 if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
826 if(top_field_first == -1)
827 big_picture.top_field_first = in_picture->top_field_first;
829 big_picture.top_field_first = top_field_first;
832 /* handles sameq here. This is not correct because it may
833 not be a global option */
835 big_picture.quality = ist->st->quality;
837 big_picture.quality = ost->st->quality;
839 big_picture.pict_type = 0;
840 // big_picture.pts = AV_NOPTS_VALUE;
841 big_picture.pts= ost->sync_opts;
842 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
843 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
844 ret = avcodec_encode_video(enc,
845 bit_buffer, bit_buffer_size,
847 //enc->frame_number = enc->real_pict_num;
849 pkt.data= bit_buffer;
851 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
852 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
853 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
854 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
855 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
857 if(enc->coded_frame && enc->coded_frame->key_frame)
858 pkt.flags |= PKT_FLAG_KEY;
859 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
861 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
862 // enc->frame_number-1, enc->real_pict_num, ret,
864 /* if two pass, output log */
865 if (ost->logfile && enc->stats_out) {
866 fprintf(ost->logfile, "%s", enc->stats_out);
878 static double psnr(double d){
879 if(d==0) return INFINITY;
880 return -10.0*log(d)/log(10.0);
883 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
886 static FILE *fvstats=NULL;
893 double ti1, bitrate, avg_bitrate;
897 today = localtime(&today2);
898 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
901 fvstats = fopen(filename,"w");
909 enc = ost->st->codec;
910 if (enc->codec_type == CODEC_TYPE_VIDEO) {
911 frame_number = ost->frame_number;
912 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
913 if (enc->flags&CODEC_FLAG_PSNR)
914 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
916 fprintf(fvstats,"f_size= %6d ", frame_size);
917 /* compute pts value */
918 ti1 = ost->sync_opts * av_q2d(enc->time_base);
922 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
923 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
924 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
925 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
926 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
930 static void print_report(AVFormatContext **output_files,
931 AVOutputStream **ost_table, int nb_ostreams,
936 AVFormatContext *oc, *os;
939 int frame_number, vid, i;
940 double bitrate, ti1, pts;
941 static int64_t last_time = -1;
942 static int qp_histogram[52];
944 if (!is_last_report) {
946 /* display the report every 0.5 seconds */
947 cur_time = av_gettime();
948 if (last_time == -1) {
949 last_time = cur_time;
952 if ((cur_time - last_time) < 500000)
954 last_time = cur_time;
958 oc = output_files[0];
960 total_size = url_ftell(&oc->pb);
965 for(i=0;i<nb_ostreams;i++) {
967 os = output_files[ost->file_index];
968 enc = ost->st->codec;
969 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
970 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
971 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
973 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
974 frame_number = ost->frame_number;
975 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
976 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
978 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
979 if(qp_hist && enc->coded_frame){
981 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
982 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
985 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
987 if (enc->flags&CODEC_FLAG_PSNR){
989 double error, error_sum=0;
990 double scale, scale_sum=0;
991 char type[3]= {'Y','U','V'};
992 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
995 error= enc->error[j];
996 scale= enc->width*enc->height*255.0*255.0*frame_number;
998 error= enc->coded_frame->error[j];
999 scale= enc->width*enc->height*255.0*255.0;
1004 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1006 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1010 /* compute min output value */
1011 pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1012 if ((pts < ti1) && (pts > 0))
1018 if (verbose || is_last_report) {
1019 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1021 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1022 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1023 (double)total_size / 1024, ti1, bitrate);
1026 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1027 nb_frames_dup, nb_frames_drop);
1030 fprintf(stderr, "%s \r", buf);
1035 if (is_last_report && verbose >= 0){
1036 int64_t raw= audio_size + video_size + extra_size;
1037 fprintf(stderr, "\n");
1038 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1042 100.0*(total_size - raw)/raw
1047 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1048 static int output_packet(AVInputStream *ist, int ist_index,
1049 AVOutputStream **ost_table, int nb_ostreams,
1050 const AVPacket *pkt)
1052 AVFormatContext *os;
1053 AVOutputStream *ost;
1057 int data_size, got_picture;
1059 void *buffer_to_free;
1060 static unsigned int samples_size= 0;
1061 static short *samples= NULL;
1062 AVSubtitle subtitle, *subtitle_to_free;
1066 ist->pts= ist->next_pts; // needed for last packet if vsync=0
1067 } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1068 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1070 // assert(ist->pts == ist->next_pts);
1084 /* decode the packet if needed */
1085 data_buf = NULL; /* fail safe */
1087 subtitle_to_free = NULL;
1088 if (ist->decoding_needed) {
1089 switch(ist->st->codec->codec_type) {
1090 case CODEC_TYPE_AUDIO:{
1092 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1093 /* XXX: could avoid copy if PCM 16 bits with same
1094 endianness as CPU */
1095 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1101 /* Some bug in mpeg audio decoder gives */
1102 /* data_size < 0, it seems they are overflows */
1103 if (data_size <= 0) {
1104 /* no audio frame */
1107 data_buf = (uint8_t *)samples;
1108 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1109 (ist->st->codec->sample_rate * ist->st->codec->channels);
1111 case CODEC_TYPE_VIDEO:
1112 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1113 /* XXX: allocate picture correctly */
1114 avcodec_get_frame_defaults(&picture);
1116 ret = avcodec_decode_video(ist->st->codec,
1117 &picture, &got_picture, ptr, len);
1118 ist->st->quality= picture.quality;
1122 /* no picture yet */
1123 goto discard_packet;
1125 if (ist->st->codec->time_base.num != 0) {
1126 ist->next_pts += ((int64_t)AV_TIME_BASE *
1127 ist->st->codec->time_base.num) /
1128 ist->st->codec->time_base.den;
1132 case CODEC_TYPE_SUBTITLE:
1133 ret = avcodec_decode_subtitle(ist->st->codec,
1134 &subtitle, &got_subtitle, ptr, len);
1137 if (!got_subtitle) {
1138 goto discard_packet;
1140 subtitle_to_free = &subtitle;
1147 switch(ist->st->codec->codec_type) {
1148 case CODEC_TYPE_AUDIO:
1149 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1150 (ist->st->codec->sample_rate * ist->st->codec->channels);
1152 case CODEC_TYPE_VIDEO:
1153 if (ist->st->codec->time_base.num != 0) {
1154 ist->next_pts += ((int64_t)AV_TIME_BASE *
1155 ist->st->codec->time_base.num) /
1156 ist->st->codec->time_base.den;
1166 buffer_to_free = NULL;
1167 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1168 pre_process_video_frame(ist, (AVPicture *)&picture,
1172 // preprocess audio (volume)
1173 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1174 if (audio_volume != 256) {
1177 for(i=0;i<(data_size / sizeof(short));i++) {
1178 int v = ((*volp) * audio_volume + 128) >> 8;
1179 if (v < -32768) v = -32768;
1180 if (v > 32767) v = 32767;
1186 /* frame rate emulation */
1187 if (ist->st->codec->rate_emu) {
1188 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1189 int64_t now = av_gettime() - ist->start;
1197 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1198 is the one of the next displayed one */
1199 /* XXX: add mpeg4 too ? */
1200 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1201 if (ist->st->codec->pict_type != B_TYPE) {
1203 tmp = ist->last_ip_pts;
1204 ist->last_ip_pts = ist->frac_pts.val;
1205 ist->frac_pts.val = tmp;
1209 /* if output time reached then transcode raw format,
1210 encode packets and output them */
1211 if (start_time == 0 || ist->pts >= start_time)
1212 for(i=0;i<nb_ostreams;i++) {
1216 if (ost->source_index == ist_index) {
1217 os = output_files[ost->file_index];
1220 printf("%d: got pts=%0.3f %0.3f\n", i,
1221 (double)pkt->pts / AV_TIME_BASE,
1222 ((double)ist->pts / AV_TIME_BASE) -
1223 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1225 /* set the input output pts pairs */
1226 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1228 if (ost->encoding_needed) {
1229 switch(ost->st->codec->codec_type) {
1230 case CODEC_TYPE_AUDIO:
1231 do_audio_out(os, ost, ist, data_buf, data_size);
1233 case CODEC_TYPE_VIDEO:
1234 do_video_out(os, ost, ist, &picture, &frame_size);
1235 video_size += frame_size;
1236 if (do_vstats && frame_size)
1237 do_video_stats(os, ost, frame_size);
1239 case CODEC_TYPE_SUBTITLE:
1240 do_subtitle_out(os, ost, ist, &subtitle,
1247 AVFrame avframe; //FIXME/XXX remove this
1249 av_init_packet(&opkt);
1251 /* no reencoding needed : output the packet directly */
1252 /* force the input stream PTS */
1254 avcodec_get_frame_defaults(&avframe);
1255 ost->st->codec->coded_frame= &avframe;
1256 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1258 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1259 audio_size += data_size;
1260 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1261 video_size += data_size;
1265 opkt.stream_index= ost->index;
1266 if(pkt->pts != AV_NOPTS_VALUE)
1267 opkt.pts= av_rescale_q(av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1269 opkt.pts= AV_NOPTS_VALUE;
1273 if (pkt->dts == AV_NOPTS_VALUE)
1274 dts = ist->next_pts;
1276 dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1277 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1279 opkt.flags= pkt->flags;
1281 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1282 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1283 opkt.destruct= av_destruct_packet;
1285 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1286 ost->st->codec->frame_number++;
1287 ost->frame_number++;
1288 av_free_packet(&opkt);
1292 av_free(buffer_to_free);
1293 /* XXX: allocate the subtitles in the codec ? */
1294 if (subtitle_to_free) {
1295 if (subtitle_to_free->rects != NULL) {
1296 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1297 av_free(subtitle_to_free->rects[i].bitmap);
1298 av_free(subtitle_to_free->rects[i].rgba_palette);
1300 av_freep(&subtitle_to_free->rects);
1302 subtitle_to_free->num_rects = 0;
1303 subtitle_to_free = NULL;
1310 for(i=0;i<nb_ostreams;i++) {
1312 if (ost->source_index == ist_index) {
1313 AVCodecContext *enc= ost->st->codec;
1314 os = output_files[ost->file_index];
1316 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1318 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1321 if (ost->encoding_needed) {
1325 av_init_packet(&pkt);
1326 pkt.stream_index= ost->index;
1328 switch(ost->st->codec->codec_type) {
1329 case CODEC_TYPE_AUDIO:
1330 fifo_bytes = fifo_size(&ost->fifo, NULL);
1332 /* encode any samples remaining in fifo */
1333 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1334 int fs_tmp = enc->frame_size;
1335 enc->frame_size = fifo_bytes / (2 * enc->channels);
1336 if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1337 &ost->fifo.rptr) == 0) {
1338 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1340 enc->frame_size = fs_tmp;
1343 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1346 pkt.flags |= PKT_FLAG_KEY;
1348 case CODEC_TYPE_VIDEO:
1349 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1351 if(enc->coded_frame && enc->coded_frame->key_frame)
1352 pkt.flags |= PKT_FLAG_KEY;
1353 if (ost->logfile && enc->stats_out) {
1354 fprintf(ost->logfile, "%s", enc->stats_out);
1363 pkt.data= bit_buffer;
1365 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1366 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1367 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1381 * The following code is the main loop of the file converter
1383 static int av_encode(AVFormatContext **output_files,
1384 int nb_output_files,
1385 AVFormatContext **input_files,
1387 AVStreamMap *stream_maps, int nb_stream_maps)
1389 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1390 AVFormatContext *is, *os;
1391 AVCodecContext *codec, *icodec;
1392 AVOutputStream *ost, **ost_table = NULL;
1393 AVInputStream *ist, **ist_table = NULL;
1394 AVInputFile *file_table;
1395 AVFormatContext *stream_no_data;
1398 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1402 /* input stream init */
1404 for(i=0;i<nb_input_files;i++) {
1405 is = input_files[i];
1406 file_table[i].ist_index = j;
1407 file_table[i].nb_streams = is->nb_streams;
1408 j += is->nb_streams;
1412 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1416 for(i=0;i<nb_istreams;i++) {
1417 ist = av_mallocz(sizeof(AVInputStream));
1423 for(i=0;i<nb_input_files;i++) {
1424 is = input_files[i];
1425 for(k=0;k<is->nb_streams;k++) {
1426 ist = ist_table[j++];
1427 ist->st = is->streams[k];
1428 ist->file_index = i;
1430 ist->discard = 1; /* the stream is discarded by default
1433 if (ist->st->codec->rate_emu) {
1434 ist->start = av_gettime();
1440 /* output stream init */
1442 for(i=0;i<nb_output_files;i++) {
1443 os = output_files[i];
1444 nb_ostreams += os->nb_streams;
1446 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1447 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1451 /* Sanity check the mapping args -- do the input files & streams exist? */
1452 for(i=0;i<nb_stream_maps;i++) {
1453 int fi = stream_maps[i].file_index;
1454 int si = stream_maps[i].stream_index;
1456 if (fi < 0 || fi > nb_input_files - 1 ||
1457 si < 0 || si > file_table[fi].nb_streams - 1) {
1458 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1461 fi = stream_maps[i].sync_file_index;
1462 si = stream_maps[i].sync_stream_index;
1463 if (fi < 0 || fi > nb_input_files - 1 ||
1464 si < 0 || si > file_table[fi].nb_streams - 1) {
1465 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1470 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1473 for(i=0;i<nb_ostreams;i++) {
1474 ost = av_mallocz(sizeof(AVOutputStream));
1481 for(k=0;k<nb_output_files;k++) {
1482 os = output_files[k];
1483 for(i=0;i<os->nb_streams;i++) {
1485 ost = ost_table[n++];
1486 ost->file_index = k;
1488 ost->st = os->streams[i];
1489 if (nb_stream_maps > 0) {
1490 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1491 stream_maps[n-1].stream_index;
1493 /* Sanity check that the stream types match */
1494 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1495 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1496 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1497 ost->file_index, ost->index);
1502 /* get corresponding input stream index : we select the first one with the right type */
1504 for(j=0;j<nb_istreams;j++) {
1507 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1508 ost->source_index = j;
1515 /* try again and reuse existing stream */
1516 for(j=0;j<nb_istreams;j++) {
1518 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1519 ost->source_index = j;
1524 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1525 ost->file_index, ost->index);
1530 ist = ist_table[ost->source_index];
1532 ost->sync_ist = (nb_stream_maps > 0) ?
1533 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1534 stream_maps[n-1].sync_stream_index] : ist;
1538 /* for each output stream, we compute the right encoding parameters */
1539 for(i=0;i<nb_ostreams;i++) {
1541 ist = ist_table[ost->source_index];
1543 codec = ost->st->codec;
1544 icodec = ist->st->codec;
1546 if (ost->st->stream_copy) {
1547 /* if stream_copy is selected, no need to decode or encode */
1548 codec->codec_id = icodec->codec_id;
1549 codec->codec_type = icodec->codec_type;
1550 if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1551 codec->bit_rate = icodec->bit_rate;
1552 codec->extradata= icodec->extradata;
1553 codec->extradata_size= icodec->extradata_size;
1554 codec->time_base = icodec->time_base;
1555 switch(codec->codec_type) {
1556 case CODEC_TYPE_AUDIO:
1557 codec->sample_rate = icodec->sample_rate;
1558 codec->channels = icodec->channels;
1559 codec->frame_size = icodec->frame_size;
1560 codec->block_align= icodec->block_align;
1562 case CODEC_TYPE_VIDEO:
1563 codec->pix_fmt = icodec->pix_fmt;
1564 codec->width = icodec->width;
1565 codec->height = icodec->height;
1566 codec->has_b_frames = icodec->has_b_frames;
1568 case CODEC_TYPE_SUBTITLE:
1574 switch(codec->codec_type) {
1575 case CODEC_TYPE_AUDIO:
1576 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1579 if (codec->channels == icodec->channels &&
1580 codec->sample_rate == icodec->sample_rate) {
1581 ost->audio_resample = 0;
1583 if (codec->channels != icodec->channels &&
1584 (icodec->codec_id == CODEC_ID_AC3 ||
1585 icodec->codec_id == CODEC_ID_DTS)) {
1586 /* Special case for 5:1 AC3 and DTS input */
1587 /* and mono or stereo output */
1588 /* Request specific number of channels */
1589 icodec->channels = codec->channels;
1590 if (codec->sample_rate == icodec->sample_rate)
1591 ost->audio_resample = 0;
1593 ost->audio_resample = 1;
1596 ost->audio_resample = 1;
1599 if(audio_sync_method>1)
1600 ost->audio_resample = 1;
1602 if(ost->audio_resample){
1603 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1604 codec->sample_rate, icodec->sample_rate);
1606 printf("Can't resample. Aborting.\n");
1610 ist->decoding_needed = 1;
1611 ost->encoding_needed = 1;
1613 case CODEC_TYPE_VIDEO:
1614 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1615 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1616 ost->video_resample = ((codec->width != icodec->width -
1617 (frame_leftBand + frame_rightBand) +
1618 (frame_padleft + frame_padright)) ||
1619 (codec->height != icodec->height -
1620 (frame_topBand + frame_bottomBand) +
1621 (frame_padtop + frame_padbottom)) ||
1622 (codec->pix_fmt != icodec->pix_fmt));
1623 if (ost->video_crop) {
1624 ost->topBand = frame_topBand;
1625 ost->leftBand = frame_leftBand;
1627 if (ost->video_pad) {
1628 ost->padtop = frame_padtop;
1629 ost->padleft = frame_padleft;
1630 ost->padbottom = frame_padbottom;
1631 ost->padright = frame_padright;
1632 if (!ost->video_resample) {
1633 avcodec_get_frame_defaults(&ost->pict_tmp);
1634 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1635 codec->width, codec->height ) )
1639 if (ost->video_resample) {
1640 avcodec_get_frame_defaults(&ost->pict_tmp);
1641 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1642 codec->width, codec->height ) )
1645 ost->img_resample_ctx = sws_getContext(
1646 icodec->width - (frame_leftBand + frame_rightBand),
1647 icodec->height - (frame_topBand + frame_bottomBand),
1649 codec->width - (frame_padleft + frame_padright),
1650 codec->height - (frame_padtop + frame_padbottom),
1652 sws_flags, NULL, NULL, NULL);
1653 if (ost->img_resample_ctx == NULL) {
1654 fprintf(stderr, "Cannot get resampling context\n");
1657 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1659 ost->encoding_needed = 1;
1660 ist->decoding_needed = 1;
1662 case CODEC_TYPE_SUBTITLE:
1663 ost->encoding_needed = 1;
1664 ist->decoding_needed = 1;
1671 if (ost->encoding_needed &&
1672 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1673 char logfilename[1024];
1678 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1680 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1681 if (codec->flags & CODEC_FLAG_PASS1) {
1682 f = fopen(logfilename, "w");
1684 perror(logfilename);
1689 /* read the log file */
1690 f = fopen(logfilename, "r");
1692 perror(logfilename);
1695 fseek(f, 0, SEEK_END);
1697 fseek(f, 0, SEEK_SET);
1698 logbuffer = av_malloc(size + 1);
1700 fprintf(stderr, "Could not allocate log buffer\n");
1703 size = fread(logbuffer, 1, size, f);
1705 logbuffer[size] = '\0';
1706 codec->stats_in = logbuffer;
1710 if(codec->codec_type == CODEC_TYPE_VIDEO){
1711 int size= codec->width * codec->height;
1712 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1717 bit_buffer = av_malloc(bit_buffer_size);
1721 /* dump the file output parameters - cannot be done before in case
1723 for(i=0;i<nb_output_files;i++) {
1724 dump_format(output_files[i], i, output_files[i]->filename, 1);
1727 /* dump the stream mapping */
1729 fprintf(stderr, "Stream mapping:\n");
1730 for(i=0;i<nb_ostreams;i++) {
1732 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1733 ist_table[ost->source_index]->file_index,
1734 ist_table[ost->source_index]->index,
1737 if (ost->sync_ist != ist_table[ost->source_index])
1738 fprintf(stderr, " [sync #%d.%d]",
1739 ost->sync_ist->file_index,
1740 ost->sync_ist->index);
1741 fprintf(stderr, "\n");
1745 /* open each encoder */
1746 for(i=0;i<nb_ostreams;i++) {
1748 if (ost->encoding_needed) {
1750 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1752 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1753 ost->file_index, ost->index);
1756 if (avcodec_open(ost->st->codec, codec) < 0) {
1757 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1758 ost->file_index, ost->index);
1761 extra_size += ost->st->codec->extradata_size;
1765 /* open each decoder */
1766 for(i=0;i<nb_istreams;i++) {
1768 if (ist->decoding_needed) {
1770 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1772 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1773 ist->st->codec->codec_id, ist->file_index, ist->index);
1776 if (avcodec_open(ist->st->codec, codec) < 0) {
1777 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1778 ist->file_index, ist->index);
1781 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1782 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1787 for(i=0;i<nb_istreams;i++) {
1789 is = input_files[ist->file_index];
1791 ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1792 if(ist->st->start_time == AV_NOPTS_VALUE)
1794 if(input_files_ts_offset[ist->file_index])
1795 ist->next_pts= AV_NOPTS_VALUE;
1799 /* compute buffer size max (should use a complete heuristic) */
1800 for(i=0;i<nb_input_files;i++) {
1801 file_table[i].buffer_size_max = 2048;
1804 /* set meta data information from input file if required */
1805 for (i=0;i<nb_meta_data_maps;i++) {
1806 AVFormatContext *out_file;
1807 AVFormatContext *in_file;
1809 int out_file_index = meta_data_maps[i].out_file;
1810 int in_file_index = meta_data_maps[i].in_file;
1811 if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1812 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1816 if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1817 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1822 out_file = output_files[out_file_index];
1823 in_file = input_files[in_file_index];
1825 strcpy(out_file->title, in_file->title);
1826 strcpy(out_file->author, in_file->author);
1827 strcpy(out_file->copyright, in_file->copyright);
1828 strcpy(out_file->comment, in_file->comment);
1829 strcpy(out_file->album, in_file->album);
1830 out_file->year = in_file->year;
1831 out_file->track = in_file->track;
1832 strcpy(out_file->genre, in_file->genre);
1835 /* open files and write file headers */
1836 for(i=0;i<nb_output_files;i++) {
1837 os = output_files[i];
1838 if (av_write_header(os) < 0) {
1839 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1846 if ( !using_stdin && verbose >= 0) {
1847 fprintf(stderr, "Press [q] to stop encoding\n");
1848 url_set_interrupt_cb(decode_interrupt_cb);
1856 for(; received_sigterm == 0;) {
1857 int file_index, ist_index;
1865 /* if 'q' pressed, exits */
1869 /* read_key() returns 0 on EOF */
1875 /* select the stream that we must read now by looking at the
1876 smallest output pts */
1878 for(i=0;i<nb_ostreams;i++) {
1881 os = output_files[ost->file_index];
1882 ist = ist_table[ost->source_index];
1883 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1884 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1886 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1887 ipts = (double)ist->pts;
1888 if (!file_table[ist->file_index].eof_reached){
1889 if(ipts < ipts_min) {
1891 if(input_sync ) file_index = ist->file_index;
1893 if(opts < opts_min) {
1895 if(!input_sync) file_index = ist->file_index;
1898 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1903 /* if none, if is finished */
1904 if (file_index < 0) {
1908 /* finish if recording time exhausted */
1909 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1912 /* finish if limit size exhausted */
1913 if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1916 /* read a frame from it and output it in the fifo */
1917 is = input_files[file_index];
1918 if (av_read_frame(is, &pkt) < 0) {
1919 file_table[file_index].eof_reached = 1;
1920 if (opt_shortest) break; else continue; //
1924 stream_no_data = is;
1929 av_pkt_dump(stdout, &pkt, do_hex_dump);
1931 /* the following test is needed in case new streams appear
1932 dynamically in stream : we ignore them */
1933 if (pkt.stream_index >= file_table[file_index].nb_streams)
1934 goto discard_packet;
1935 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1936 ist = ist_table[ist_index];
1938 goto discard_packet;
1940 // fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
1941 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1942 int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1943 if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1944 input_files_ts_offset[ist->file_index]-= delta;
1946 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1947 for(i=0; i<file_table[file_index].nb_streams; i++){
1948 int index= file_table[file_index].ist_index + i;
1949 ist_table[index]->next_pts += delta;
1950 ist_table[index]->is_start=1;
1955 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1956 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1959 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1960 ist->file_index, ist->index);
1962 av_free_packet(&pkt);
1967 av_free_packet(&pkt);
1969 /* dump report by using the output first video and audio streams */
1970 print_report(output_files, ost_table, nb_ostreams, 0);
1973 /* at the end of stream, we must flush the decoder buffers */
1974 for(i=0;i<nb_istreams;i++) {
1976 if (ist->decoding_needed) {
1977 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1983 /* write the trailer if needed and close file */
1984 for(i=0;i<nb_output_files;i++) {
1985 os = output_files[i];
1986 av_write_trailer(os);
1989 /* dump report by using the first video and audio streams */
1990 print_report(output_files, ost_table, nb_ostreams, 1);
1992 /* close each encoder */
1993 for(i=0;i<nb_ostreams;i++) {
1995 if (ost->encoding_needed) {
1996 av_freep(&ost->st->codec->stats_in);
1997 avcodec_close(ost->st->codec);
2001 /* close each decoder */
2002 for(i=0;i<nb_istreams;i++) {
2004 if (ist->decoding_needed) {
2005 avcodec_close(ist->st->codec);
2013 av_freep(&bit_buffer);
2014 av_free(file_table);
2017 for(i=0;i<nb_istreams;i++) {
2024 for(i=0;i<nb_ostreams;i++) {
2028 fclose(ost->logfile);
2029 ost->logfile = NULL;
2031 fifo_free(&ost->fifo); /* works even if fifo is not
2032 initialized but set to zero */
2033 av_free(ost->pict_tmp.data[0]);
2034 if (ost->video_resample)
2035 sws_freeContext(ost->img_resample_ctx);
2036 if (ost->audio_resample)
2037 audio_resample_close(ost->resample);
2050 int file_read(const char *filename)
2053 unsigned char buffer[1024];
2056 if (url_open(&h, filename, O_RDONLY) < 0) {
2057 printf("could not open '%s'\n", filename);
2061 len = url_read(h, buffer, sizeof(buffer));
2064 for(i=0;i<len;i++) putchar(buffer[i]);
2071 static void opt_image_format(const char *arg)
2075 for(f = first_image_format; f != NULL; f = f->next) {
2076 if (!strcmp(arg, f->name))
2080 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2086 static void opt_format(const char *arg)
2088 /* compatibility stuff for pgmyuv */
2089 if (!strcmp(arg, "pgmyuv")) {
2090 pgmyuv_compatibility_hack=1;
2091 // opt_image_format(arg);
2095 file_iformat = av_find_input_format(arg);
2096 file_oformat = guess_format(arg, NULL, NULL);
2097 if (!file_iformat && !file_oformat) {
2098 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2103 static void opt_video_buffer_size(const char *arg)
2105 video_rc_buffer_size = atoi(arg) * 8*1024;
2108 static void opt_video_rc_eq(char *arg)
2113 static void opt_video_rc_override_string(char *arg)
2115 video_rc_override_string = arg;
2119 static void opt_workaround_bugs(const char *arg)
2121 workaround_bugs = atoi(arg);
2124 static void opt_me_threshold(const char *arg)
2126 me_threshold = atoi(arg);
2129 static void opt_mb_threshold(const char *arg)
2131 mb_threshold = atoi(arg);
2134 static void opt_verbose(const char *arg)
2136 verbose = atoi(arg);
2137 av_log_set_level(atoi(arg));
2140 static void opt_frame_rate(const char *arg)
2142 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2143 fprintf(stderr, "Incorrect frame rate\n");
2148 static void opt_frame_crop_top(const char *arg)
2150 frame_topBand = atoi(arg);
2151 if (frame_topBand < 0) {
2152 fprintf(stderr, "Incorrect top crop size\n");
2155 if ((frame_topBand % 2) != 0) {
2156 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2159 if ((frame_topBand) >= frame_height){
2160 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2163 frame_height -= frame_topBand;
2166 static void opt_frame_crop_bottom(const char *arg)
2168 frame_bottomBand = atoi(arg);
2169 if (frame_bottomBand < 0) {
2170 fprintf(stderr, "Incorrect bottom crop size\n");
2173 if ((frame_bottomBand % 2) != 0) {
2174 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2177 if ((frame_bottomBand) >= frame_height){
2178 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2181 frame_height -= frame_bottomBand;
2184 static void opt_frame_crop_left(const char *arg)
2186 frame_leftBand = atoi(arg);
2187 if (frame_leftBand < 0) {
2188 fprintf(stderr, "Incorrect left crop size\n");
2191 if ((frame_leftBand % 2) != 0) {
2192 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2195 if ((frame_leftBand) >= frame_width){
2196 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2199 frame_width -= frame_leftBand;
2202 static void opt_frame_crop_right(const char *arg)
2204 frame_rightBand = atoi(arg);
2205 if (frame_rightBand < 0) {
2206 fprintf(stderr, "Incorrect right crop size\n");
2209 if ((frame_rightBand % 2) != 0) {
2210 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2213 if ((frame_rightBand) >= frame_width){
2214 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2217 frame_width -= frame_rightBand;
2220 static void opt_frame_size(const char *arg)
2222 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2223 fprintf(stderr, "Incorrect frame size\n");
2226 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2227 fprintf(stderr, "Frame size must be a multiple of 2\n");
2233 #define SCALEBITS 10
2234 #define ONE_HALF (1 << (SCALEBITS - 1))
2235 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2237 #define RGB_TO_Y(r, g, b) \
2238 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2239 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2241 #define RGB_TO_U(r1, g1, b1, shift)\
2242 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2243 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2245 #define RGB_TO_V(r1, g1, b1, shift)\
2246 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2247 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2249 static void opt_pad_color(const char *arg) {
2250 /* Input is expected to be six hex digits similar to
2251 how colors are expressed in html tags (but without the #) */
2252 int rgb = strtol(arg, NULL, 16);
2256 g = ((rgb >> 8) & 255);
2259 padcolor[0] = RGB_TO_Y(r,g,b);
2260 padcolor[1] = RGB_TO_U(r,g,b,0);
2261 padcolor[2] = RGB_TO_V(r,g,b,0);
2264 static void opt_frame_pad_top(const char *arg)
2266 frame_padtop = atoi(arg);
2267 if (frame_padtop < 0) {
2268 fprintf(stderr, "Incorrect top pad size\n");
2271 if ((frame_padtop % 2) != 0) {
2272 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2277 static void opt_frame_pad_bottom(const char *arg)
2279 frame_padbottom = atoi(arg);
2280 if (frame_padbottom < 0) {
2281 fprintf(stderr, "Incorrect bottom pad size\n");
2284 if ((frame_padbottom % 2) != 0) {
2285 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2291 static void opt_frame_pad_left(const char *arg)
2293 frame_padleft = atoi(arg);
2294 if (frame_padleft < 0) {
2295 fprintf(stderr, "Incorrect left pad size\n");
2298 if ((frame_padleft % 2) != 0) {
2299 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2305 static void opt_frame_pad_right(const char *arg)
2307 frame_padright = atoi(arg);
2308 if (frame_padright < 0) {
2309 fprintf(stderr, "Incorrect right pad size\n");
2312 if ((frame_padright % 2) != 0) {
2313 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2319 static void opt_frame_pix_fmt(const char *arg)
2321 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2324 static void opt_frame_aspect_ratio(const char *arg)
2330 p = strchr(arg, ':');
2332 x = strtol(arg, (char **)&arg, 10);
2334 y = strtol(arg+1, (char **)&arg, 10);
2336 ar = (double)x / (double)y;
2338 ar = strtod(arg, (char **)&arg);
2341 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2344 frame_aspect_ratio = ar;
2347 static void opt_b_frames(const char *arg)
2349 b_frames = atoi(arg);
2350 if (b_frames > FF_MAX_B_FRAMES) {
2351 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2353 } else if (b_frames < 1) {
2354 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2359 static void opt_qscale(const char *arg)
2361 video_qscale = atof(arg);
2362 if (video_qscale <= 0 ||
2363 video_qscale > 255) {
2364 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2369 static void opt_qsquish(const char *arg)
2371 video_qsquish = atof(arg);
2372 if (video_qsquish < 0.0 ||
2373 video_qsquish > 99.0) {
2374 fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2379 static void opt_lmax(const char *arg)
2381 video_lmax = atof(arg)*FF_QP2LAMBDA;
2384 static void opt_lmin(const char *arg)
2386 video_lmin = atof(arg)*FF_QP2LAMBDA;
2389 static void opt_qmin(const char *arg)
2391 video_qmin = atoi(arg);
2392 if (video_qmin < 1 ||
2394 fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2399 static void opt_qmax(const char *arg)
2401 video_qmax = atoi(arg);
2402 if (video_qmax < 1 ||
2404 fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2409 static void opt_mb_lmin(const char *arg)
2411 video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2412 if (video_mb_lmin < 1 ||
2413 video_mb_lmin > FF_LAMBDA_MAX) {
2414 fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2419 static void opt_mb_lmax(const char *arg)
2421 video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2422 if (video_mb_lmax < 1 ||
2423 video_mb_lmax > FF_LAMBDA_MAX) {
2424 fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2429 static void opt_qdiff(const char *arg)
2431 video_qdiff = atoi(arg);
2432 if (video_qdiff < 0 ||
2434 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2439 static void opt_packet_size(const char *arg)
2441 packet_size= atoi(arg);
2444 static void opt_error_rate(const char *arg)
2446 error_rate= atoi(arg);
2449 static void opt_strict(const char *arg)
2454 static void opt_top_field_first(const char *arg)
2456 top_field_first= atoi(arg);
2459 static void opt_sc_threshold(const char *arg)
2461 sc_threshold= atoi(arg);
2464 static void opt_thread_count(const char *arg)
2466 thread_count= atoi(arg);
2467 #if !defined(HAVE_THREADS)
2469 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2473 static void opt_audio_bitrate(const char *arg)
2475 audio_bit_rate = atoi(arg) * 1000;
2478 static void opt_audio_rate(const char *arg)
2480 audio_sample_rate = atoi(arg);
2483 static void opt_audio_channels(const char *arg)
2485 audio_channels = atoi(arg);
2488 static void opt_video_device(const char *arg)
2490 video_device = av_strdup(arg);
2493 static void opt_grab_device(const char *arg)
2495 grab_device = av_strdup(arg);
2498 static void opt_video_channel(const char *arg)
2500 video_channel = strtol(arg, NULL, 0);
2503 static void opt_video_standard(const char *arg)
2505 video_standard = av_strdup(arg);
2508 static void opt_audio_device(const char *arg)
2510 audio_device = av_strdup(arg);
2513 static void opt_codec(int *pstream_copy, int *pcodec_id,
2514 int codec_type, const char *arg)
2518 if (!strcmp(arg, "copy")) {
2523 if (!strcmp(p->name, arg) && p->type == codec_type)
2528 fprintf(stderr, "Unknown codec '%s'\n", arg);
2536 static void opt_audio_codec(const char *arg)
2538 opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2541 static void opt_audio_tag(const char *arg)
2544 audio_codec_tag= strtol(arg, &tail, 0);
2547 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2550 static void opt_video_tag(const char *arg)
2553 video_codec_tag= strtol(arg, &tail, 0);
2556 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2559 static void add_frame_hooker(const char *arg)
2564 char *args = av_strdup(arg);
2568 argv[0] = strtok(args, " ");
2569 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2572 i = frame_hook_add(argc, argv);
2575 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2580 const char *motion_str[] = {
2593 static void opt_motion_estimation(const char *arg)
2599 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2602 if (!strcmp(*p, arg))
2606 me_method = (p - motion_str) + 1;
2609 static void opt_video_codec(const char *arg)
2611 opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2614 static void opt_subtitle_codec(const char *arg)
2616 opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2619 static void opt_map(const char *arg)
2625 m = &stream_maps[nb_stream_maps++];
2627 m->file_index = strtol(arg, (char **)&p, 0);
2631 m->stream_index = strtol(p, (char **)&p, 0);
2634 m->sync_file_index = strtol(p, (char **)&p, 0);
2637 m->sync_stream_index = strtol(p, (char **)&p, 0);
2639 m->sync_file_index = m->file_index;
2640 m->sync_stream_index = m->stream_index;
2644 static void opt_map_meta_data(const char *arg)
2650 m = &meta_data_maps[nb_meta_data_maps++];
2652 m->out_file = strtol(arg, (char **)&p, 0);
2656 m->in_file = strtol(p, (char **)&p, 0);
2659 static void opt_recording_time(const char *arg)
2661 recording_time = parse_date(arg, 1);
2664 static void opt_start_time(const char *arg)
2666 start_time = parse_date(arg, 1);
2669 static void opt_rec_timestamp(const char *arg)
2671 rec_timestamp = parse_date(arg, 0) / 1000000;
2674 static void opt_input_ts_offset(const char *arg)
2676 input_ts_offset = parse_date(arg, 1);
2679 static void opt_input_file(const char *filename)
2681 AVFormatContext *ic;
2682 AVFormatParameters params, *ap = ¶ms;
2683 int err, i, ret, rfps, rfps_base;
2686 if (!strcmp(filename, "-"))
2689 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2690 !strcmp( filename, "/dev/stdin" );
2692 /* get default parameters from command line */
2693 ic = av_alloc_format_context();
2695 memset(ap, 0, sizeof(*ap));
2696 ap->prealloced_context = 1;
2697 ap->sample_rate = audio_sample_rate;
2698 ap->channels = audio_channels;
2699 ap->time_base.den = frame_rate;
2700 ap->time_base.num = frame_rate_base;
2701 ap->width = frame_width + frame_padleft + frame_padright;
2702 ap->height = frame_height + frame_padtop + frame_padbottom;
2703 ap->image_format = image_format;
2704 ap->pix_fmt = frame_pix_fmt;
2705 ap->device = grab_device;
2706 ap->channel = video_channel;
2707 ap->standard = video_standard;
2708 ap->video_codec_id = video_codec_id;
2709 ap->audio_codec_id = audio_codec_id;
2710 if(pgmyuv_compatibility_hack)
2711 ap->video_codec_id= CODEC_ID_PGMYUV;
2713 for(i=0; i<opt_name_count; i++){
2715 double d= av_get_double(avformat_opts, opt_names[i], &opt);
2716 if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2717 av_set_double(ic, opt_names[i], d);
2719 /* open the input file with generic libav function */
2720 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2722 print_error(filename, err);
2726 ic->loop_input = loop_input;
2728 /* If not enough info to get the stream parameters, we decode the
2729 first frames to get it. (used in mpeg case for example) */
2730 ret = av_find_stream_info(ic);
2731 if (ret < 0 && verbose >= 0) {
2732 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2736 timestamp = start_time;
2737 /* add the stream start time */
2738 if (ic->start_time != AV_NOPTS_VALUE)
2739 timestamp += ic->start_time;
2741 /* if seeking requested, we execute it */
2742 if (start_time != 0) {
2743 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2745 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2746 filename, (double)timestamp / AV_TIME_BASE);
2748 /* reset seek info */
2752 /* update the current parameters so that they match the one of the input stream */
2753 for(i=0;i<ic->nb_streams;i++) {
2755 AVCodecContext *enc = ic->streams[i]->codec;
2756 #if defined(HAVE_THREADS)
2758 avcodec_thread_init(enc, thread_count);
2760 enc->thread_count= thread_count;
2761 switch(enc->codec_type) {
2762 case CODEC_TYPE_AUDIO:
2763 for(j=0; j<opt_name_count; j++){
2765 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2766 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2767 av_set_double(enc, opt_names[j], d);
2769 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2770 audio_channels = enc->channels;
2771 audio_sample_rate = enc->sample_rate;
2773 ic->streams[i]->discard= AVDISCARD_ALL;
2775 case CODEC_TYPE_VIDEO:
2776 for(j=0; j<opt_name_count; j++){
2778 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2779 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2780 av_set_double(enc, opt_names[j], d);
2782 frame_height = enc->height;
2783 frame_width = enc->width;
2784 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2785 frame_pix_fmt = enc->pix_fmt;
2786 rfps = ic->streams[i]->r_frame_rate.num;
2787 rfps_base = ic->streams[i]->r_frame_rate.den;
2788 enc->workaround_bugs = workaround_bugs;
2789 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2791 enc->debug |= FF_DEBUG_MV;
2793 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2796 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2797 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2799 (float)rfps / rfps_base, rfps, rfps_base);
2801 /* update the current frame rate to match the stream frame rate */
2803 frame_rate_base = rfps_base;
2805 enc->rate_emu = rate_emu;
2807 ic->streams[i]->discard= AVDISCARD_ALL;
2808 else if(video_discard)
2809 ic->streams[i]->discard= video_discard;
2811 case CODEC_TYPE_DATA:
2813 case CODEC_TYPE_SUBTITLE:
2815 case CODEC_TYPE_UNKNOWN:
2822 input_files[nb_input_files] = ic;
2823 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2824 /* dump the file content */
2826 dump_format(ic, nb_input_files, filename, 0);
2829 file_iformat = NULL;
2830 file_oformat = NULL;
2831 image_format = NULL;
2839 static void opt_grab(const char *arg)
2841 file_iformat = av_find_input_format(arg);
2845 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2847 int has_video, has_audio, i, j;
2848 AVFormatContext *ic;
2852 for(j=0;j<nb_input_files;j++) {
2853 ic = input_files[j];
2854 for(i=0;i<ic->nb_streams;i++) {
2855 AVCodecContext *enc = ic->streams[i]->codec;
2856 switch(enc->codec_type) {
2857 case CODEC_TYPE_AUDIO:
2860 case CODEC_TYPE_VIDEO:
2863 case CODEC_TYPE_DATA:
2864 case CODEC_TYPE_UNKNOWN:
2865 case CODEC_TYPE_SUBTITLE:
2872 *has_video_ptr = has_video;
2873 *has_audio_ptr = has_audio;
2876 static void new_video_stream(AVFormatContext *oc)
2879 AVCodecContext *video_enc;
2882 st = av_new_stream(oc, oc->nb_streams);
2884 fprintf(stderr, "Could not alloc stream\n");
2887 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2888 video_bitstream_filters= NULL;
2890 #if defined(HAVE_THREADS)
2892 avcodec_thread_init(st->codec, thread_count);
2895 video_enc = st->codec;
2898 video_enc->codec_tag= video_codec_tag;
2900 if( (video_global_header&1)
2901 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2902 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2903 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2905 if(video_global_header&2){
2906 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2907 avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2910 if (video_stream_copy) {
2911 st->stream_copy = 1;
2912 video_enc->codec_type = CODEC_TYPE_VIDEO;
2918 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2919 if (video_codec_id != CODEC_ID_NONE)
2920 codec_id = video_codec_id;
2922 video_enc->codec_id = codec_id;
2923 codec = avcodec_find_encoder(codec_id);
2925 for(i=0; i<opt_name_count; i++){
2927 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2928 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2929 av_set_double(video_enc, opt_names[i], d);
2932 video_enc->time_base.den = frame_rate;
2933 video_enc->time_base.num = frame_rate_base;
2934 if(codec && codec->supported_framerates){
2935 const AVRational *p= codec->supported_framerates;
2936 AVRational req= (AVRational){frame_rate, frame_rate_base};
2937 const AVRational *best=NULL;
2938 AVRational best_error= (AVRational){INT_MAX, 1};
2939 for(; p->den!=0; p++){
2940 AVRational error= av_sub_q(req, *p);
2941 if(error.num <0) error.num *= -1;
2942 if(av_cmp_q(error, best_error) < 0){
2947 video_enc->time_base.den= best->num;
2948 video_enc->time_base.num= best->den;
2951 video_enc->width = frame_width + frame_padright + frame_padleft;
2952 video_enc->height = frame_height + frame_padtop + frame_padbottom;
2953 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2954 video_enc->pix_fmt = frame_pix_fmt;
2956 if(codec && codec->pix_fmts){
2957 const enum PixelFormat *p= codec->pix_fmts;
2959 if(*p == video_enc->pix_fmt)
2963 video_enc->pix_fmt = codec->pix_fmts[0];
2967 video_enc->gop_size = 0;
2968 if (video_qscale || same_quality) {
2969 video_enc->flags |= CODEC_FLAG_QSCALE;
2970 video_enc->global_quality=
2971 st->quality = FF_QP2LAMBDA * video_qscale;
2975 video_enc->intra_matrix = intra_matrix;
2977 video_enc->inter_matrix = inter_matrix;
2979 video_enc->max_b_frames = b_frames;
2980 video_enc->qmin = video_qmin;
2981 video_enc->qmax = video_qmax;
2982 video_enc->lmin = video_lmin;
2983 video_enc->lmax = video_lmax;
2984 video_enc->rc_qsquish = video_qsquish;
2985 video_enc->mb_lmin = video_mb_lmin;
2986 video_enc->mb_lmax = video_mb_lmax;
2987 video_enc->max_qdiff = video_qdiff;
2988 video_enc->rc_eq = video_rc_eq;
2989 video_enc->workaround_bugs = workaround_bugs;
2990 video_enc->thread_count = thread_count;
2991 p= video_rc_override_string;
2994 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2996 fprintf(stderr, "error parsing rc_override\n");
2999 video_enc->rc_override=
3000 av_realloc(video_enc->rc_override,
3001 sizeof(RcOverride)*(i+1));
3002 video_enc->rc_override[i].start_frame= start;
3003 video_enc->rc_override[i].end_frame = end;
3005 video_enc->rc_override[i].qscale= q;
3006 video_enc->rc_override[i].quality_factor= 1.0;
3009 video_enc->rc_override[i].qscale= 0;
3010 video_enc->rc_override[i].quality_factor= -q/100.0;
3015 video_enc->rc_override_count=i;
3017 video_enc->rc_buffer_size = video_rc_buffer_size;
3018 video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3019 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3020 video_enc->me_threshold= me_threshold;
3021 video_enc->mb_threshold= mb_threshold;
3022 video_enc->intra_dc_precision= intra_dc_precision - 8;
3023 video_enc->strict_std_compliance = strict;
3024 video_enc->error_rate = error_rate;
3025 video_enc->scenechange_threshold= sc_threshold;
3026 video_enc->me_penalty_compensation= me_penalty_compensation;
3027 video_enc->frame_skip_threshold= frame_skip_threshold;
3028 video_enc->frame_skip_factor= frame_skip_factor;
3029 video_enc->frame_skip_exp= frame_skip_exp;
3032 video_enc->rtp_mode= 1;
3033 video_enc->rtp_payload_size= packet_size;
3037 video_enc->flags|= CODEC_FLAG_PSNR;
3039 video_enc->me_method = me_method;
3044 video_enc->flags |= CODEC_FLAG_PASS1;
3046 video_enc->flags |= CODEC_FLAG_PASS2;
3051 /* reset some key parameters */
3053 video_codec_id = CODEC_ID_NONE;
3054 video_stream_copy = 0;
3057 static void new_audio_stream(AVFormatContext *oc)
3060 AVCodecContext *audio_enc;
3063 st = av_new_stream(oc, oc->nb_streams);
3065 fprintf(stderr, "Could not alloc stream\n");
3069 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3070 audio_bitstream_filters= NULL;
3072 #if defined(HAVE_THREADS)
3074 avcodec_thread_init(st->codec, thread_count);
3077 audio_enc = st->codec;
3078 audio_enc->codec_type = CODEC_TYPE_AUDIO;
3081 audio_enc->codec_tag= audio_codec_tag;
3083 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3084 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3085 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3087 if (audio_stream_copy) {
3088 st->stream_copy = 1;
3089 audio_enc->channels = audio_channels;
3091 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3093 for(i=0; i<opt_name_count; i++){
3095 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3096 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3097 av_set_double(audio_enc, opt_names[i], d);
3100 if (audio_codec_id != CODEC_ID_NONE)
3101 codec_id = audio_codec_id;
3102 audio_enc->codec_id = codec_id;
3104 audio_enc->bit_rate = audio_bit_rate;
3105 if (audio_qscale > QSCALE_NONE) {
3106 audio_enc->flags |= CODEC_FLAG_QSCALE;
3107 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3109 audio_enc->strict_std_compliance = strict;
3110 audio_enc->thread_count = thread_count;
3111 /* For audio codecs other than AC3 or DTS we limit */
3112 /* the number of coded channels to stereo */
3113 if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3114 && codec_id != CODEC_ID_DTS) {
3115 audio_enc->channels = 2;
3117 audio_enc->channels = audio_channels;
3119 audio_enc->sample_rate = audio_sample_rate;
3120 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3121 if (audio_language) {
3122 pstrcpy(st->language, sizeof(st->language), audio_language);
3123 av_free(audio_language);
3124 audio_language = NULL;
3127 /* reset some key parameters */
3129 audio_codec_id = CODEC_ID_NONE;
3130 audio_stream_copy = 0;
3133 static void opt_new_subtitle_stream(void)
3135 AVFormatContext *oc;
3137 AVCodecContext *subtitle_enc;
3140 if (nb_output_files <= 0) {
3141 fprintf(stderr, "At least one output file must be specified\n");
3144 oc = output_files[nb_output_files - 1];
3146 st = av_new_stream(oc, oc->nb_streams);
3148 fprintf(stderr, "Could not alloc stream\n");
3152 subtitle_enc = st->codec;
3153 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3154 if (subtitle_stream_copy) {
3155 st->stream_copy = 1;
3157 for(i=0; i<opt_name_count; i++){
3159 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3160 if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3161 av_set_double(subtitle_enc, opt_names[i], d);
3163 subtitle_enc->codec_id = subtitle_codec_id;
3166 if (subtitle_language) {
3167 pstrcpy(st->language, sizeof(st->language), subtitle_language);
3168 av_free(subtitle_language);
3169 subtitle_language = NULL;
3172 subtitle_codec_id = CODEC_ID_NONE;
3173 subtitle_stream_copy = 0;
3176 static void opt_new_audio_stream(void)
3178 AVFormatContext *oc;
3179 if (nb_output_files <= 0) {
3180 fprintf(stderr, "At least one output file must be specified\n");
3183 oc = output_files[nb_output_files - 1];
3184 new_audio_stream(oc);
3187 static void opt_new_video_stream(void)
3189 AVFormatContext *oc;
3190 if (nb_output_files <= 0) {
3191 fprintf(stderr, "At least one output file must be specified\n");
3194 oc = output_files[nb_output_files - 1];
3195 new_video_stream(oc);
3198 static void opt_output_file(const char *filename)
3200 AVFormatContext *oc;
3201 int use_video, use_audio, input_has_video, input_has_audio, i;
3202 AVFormatParameters params, *ap = ¶ms;
3204 if (!strcmp(filename, "-"))
3207 oc = av_alloc_format_context();
3209 if (!file_oformat) {
3210 file_oformat = guess_format(NULL, filename, NULL);
3211 if (!file_oformat) {
3212 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3218 oc->oformat = file_oformat;
3219 pstrcpy(oc->filename, sizeof(oc->filename), filename);
3221 if (!strcmp(file_oformat->name, "ffm") &&
3222 strstart(filename, "http:", NULL)) {
3223 /* special case for files sent to ffserver: we get the stream
3224 parameters from ffserver */
3225 if (read_ffserver_streams(oc, filename) < 0) {
3226 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3230 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3231 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3233 /* disable if no corresponding type found and at least one
3235 if (nb_input_files > 0) {
3236 check_audio_video_inputs(&input_has_video, &input_has_audio);
3237 if (!input_has_video)
3239 if (!input_has_audio)
3243 /* manual disable */
3244 if (audio_disable) {
3247 if (video_disable) {
3252 new_video_stream(oc);
3256 new_audio_stream(oc);
3259 if (!oc->nb_streams) {
3260 fprintf(stderr, "No audio or video streams available\n");
3264 oc->timestamp = rec_timestamp;
3267 pstrcpy(oc->title, sizeof(oc->title), str_title);
3269 pstrcpy(oc->author, sizeof(oc->author), str_author);
3271 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3273 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3275 pstrcpy(oc->album, sizeof(oc->album), str_album);
3278 output_files[nb_output_files++] = oc;
3280 /* check filename in case of an image number is expected */
3281 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3282 if (!av_filename_number_test(oc->filename)) {
3283 print_error(oc->filename, AVERROR_NUMEXPECTED);
3288 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3289 /* test if it already exists to avoid loosing precious files */
3290 if (!file_overwrite &&
3291 (strchr(filename, ':') == NULL ||
3292 strstart(filename, "file:", NULL))) {
3293 if (url_exist(filename)) {
3296 if ( !using_stdin ) {
3297 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3300 if (toupper(c) != 'Y') {
3301 fprintf(stderr, "Not overwriting - exiting\n");
3306 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3313 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3314 fprintf(stderr, "Could not open '%s'\n", filename);
3319 memset(ap, 0, sizeof(*ap));
3320 ap->image_format = image_format;
3321 if (av_set_parameters(oc, ap) < 0) {
3322 fprintf(stderr, "%s: Invalid encoding parameters\n",
3327 oc->packet_size= mux_packet_size;
3328 oc->mux_rate= mux_rate;
3329 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3330 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3331 oc->loop_output = loop_output;
3333 for(i=0; i<opt_name_count; i++){
3335 double d = av_get_double(avformat_opts, opt_names[i], &opt);
3336 if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3337 av_set_double(oc, opt_names[i], d);
3340 /* reset some options */
3341 file_oformat = NULL;
3342 file_iformat = NULL;
3343 image_format = NULL;
3346 /* prepare dummy protocols for grab */
3347 static void prepare_grab(void)
3349 int has_video, has_audio, i, j;
3350 AVFormatContext *oc;
3351 AVFormatContext *ic;
3352 AVFormatParameters vp1, *vp = &vp1;
3353 AVFormatParameters ap1, *ap = &ap1;
3355 /* see if audio/video inputs are needed */
3358 memset(ap, 0, sizeof(*ap));
3359 memset(vp, 0, sizeof(*vp));
3360 vp->time_base.num= 1;
3361 for(j=0;j<nb_output_files;j++) {
3362 oc = output_files[j];
3363 for(i=0;i<oc->nb_streams;i++) {
3364 AVCodecContext *enc = oc->streams[i]->codec;
3365 switch(enc->codec_type) {
3366 case CODEC_TYPE_AUDIO:
3367 if (enc->sample_rate > ap->sample_rate)
3368 ap->sample_rate = enc->sample_rate;
3369 if (enc->channels > ap->channels)
3370 ap->channels = enc->channels;
3373 case CODEC_TYPE_VIDEO:
3374 if (enc->width > vp->width)
3375 vp->width = enc->width;
3376 if (enc->height > vp->height)
3377 vp->height = enc->height;
3379 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3380 vp->time_base = enc->time_base;
3381 vp->width += frame_leftBand + frame_rightBand;
3382 vp->width -= (frame_padleft + frame_padright);
3383 vp->height += frame_topBand + frame_bottomBand;
3384 vp->height -= (frame_padtop + frame_padbottom);
3394 if (has_video == 0 && has_audio == 0) {
3395 fprintf(stderr, "Output file must have at least one audio or video stream\n");
3400 AVInputFormat *fmt1;
3401 fmt1 = av_find_input_format(video_grab_format);
3402 vp->device = video_device;
3403 vp->channel = video_channel;
3404 vp->standard = video_standard;
3405 vp->pix_fmt = frame_pix_fmt;
3406 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3407 fprintf(stderr, "Could not find video grab device\n");
3410 /* If not enough info to get the stream parameters, we decode the
3411 first frames to get it. */
3412 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3413 fprintf(stderr, "Could not find video grab parameters\n");
3416 /* by now video grab has one stream */
3417 ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3418 ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3419 input_files[nb_input_files] = ic;
3422 dump_format(ic, nb_input_files, "", 0);
3426 if (has_audio && audio_grab_format) {
3427 AVInputFormat *fmt1;
3428 fmt1 = av_find_input_format(audio_grab_format);
3429 ap->device = audio_device;
3430 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3431 fprintf(stderr, "Could not find audio grab device\n");
3434 input_files[nb_input_files] = ic;
3437 dump_format(ic, nb_input_files, "", 0);
3443 /* same option as mencoder */
3444 static void opt_pass(const char *pass_str)
3447 pass = atoi(pass_str);
3448 if (pass != 1 && pass != 2) {
3449 fprintf(stderr, "pass number can be only 1 or 2\n");
3455 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3456 static int64_t getutime(void)
3458 return av_gettime();
3461 static int64_t getutime(void)
3463 struct rusage rusage;
3465 getrusage(RUSAGE_SELF, &rusage);
3466 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3470 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3471 extern int ffm_nopts;
3474 static void show_formats(void)
3476 AVInputFormat *ifmt;
3477 AVOutputFormat *ofmt;
3478 AVImageFormat *image_fmt;
3481 const char **pp, *last_name;
3483 printf("File formats:\n");
3488 const char *name=NULL;
3489 const char *long_name=NULL;
3491 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3492 if((name == NULL || strcmp(ofmt->name, name)<0) &&
3493 strcmp(ofmt->name, last_name)>0){
3495 long_name= ofmt->long_name;
3499 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3500 if((name == NULL || strcmp(ifmt->name, name)<0) &&
3501 strcmp(ifmt->name, last_name)>0){
3503 long_name= ifmt->long_name;
3506 if(name && strcmp(ifmt->name, name)==0)
3518 long_name ? long_name:" ");
3522 printf("Image formats (filename extensions, if any, follow):\n");
3523 for(image_fmt = first_image_format; image_fmt != NULL;
3524 image_fmt = image_fmt->next) {
3527 image_fmt->img_read ? "D":" ",
3528 image_fmt->img_write ? "E":" ",
3530 image_fmt->extensions ? image_fmt->extensions:" ");
3534 printf("Codecs:\n");
3540 const char *type_str;
3543 for(p = first_avcodec; p != NULL; p = p->next) {
3544 if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3545 strcmp(p->name, last_name)>0){
3547 decode= encode= cap=0;
3549 if(p2 && strcmp(p->name, p2->name)==0){
3550 if(p->decode) decode=1;
3551 if(p->encode) encode=1;
3552 cap |= p->capabilities;
3557 last_name= p2->name;
3560 case CODEC_TYPE_VIDEO:
3563 case CODEC_TYPE_AUDIO:
3566 case CODEC_TYPE_SUBTITLE:
3575 decode ? "D": (/*p2->decoder ? "d":*/" "),
3578 cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3579 cap & CODEC_CAP_DR1 ? "D":" ",
3580 cap & CODEC_CAP_TRUNCATED ? "T":" ",
3582 /* if(p2->decoder && decode==0)
3583 printf(" use %s for decoding", p2->decoder->name);*/
3588 printf("Supported file protocols:\n");
3589 for(up = first_protocol; up != NULL; up = up->next)
3590 printf(" %s:", up->name);
3593 printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3594 printf("Motion estimation methods:\n");
3598 if ((pp - motion_str + 1) == ME_ZERO)
3599 printf("(fastest)");
3600 else if ((pp - motion_str + 1) == ME_FULL)
3601 printf("(slowest)");
3602 else if ((pp - motion_str + 1) == ME_EPZS)
3603 printf("(default)");
3608 "Note, the names of encoders and decoders dont always match, so there are\n"
3609 "several cases where the above table shows encoder only or decoder only entries\n"
3610 "even though both encoding and decoding are supported for example, the h263\n"
3611 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3616 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3619 const char *p = str;
3626 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3633 static void opt_inter_matrix(const char *arg)
3635 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3636 parse_matrix_coeffs(inter_matrix, arg);
3639 static void opt_intra_matrix(const char *arg)
3641 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3642 parse_matrix_coeffs(intra_matrix, arg);
3645 static void opt_target(const char *arg)
3648 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3650 if(!strncmp(arg, "pal-", 4)) {
3653 } else if(!strncmp(arg, "ntsc-", 5)) {
3656 } else if(!strncmp(arg, "film-", 5)) {
3661 /* Calculate FR via float to avoid int overflow */
3662 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3665 } else if((fr == 29970) || (fr == 23976)) {
3668 /* Try to determine PAL/NTSC by peeking in the input files */
3669 if(nb_input_files) {
3671 for(j = 0; j < nb_input_files; j++) {
3672 for(i = 0; i < input_files[j]->nb_streams; i++) {
3673 AVCodecContext *c = input_files[j]->streams[i]->codec;
3674 if(c->codec_type != CODEC_TYPE_VIDEO)
3676 fr = c->time_base.den * 1000 / c->time_base.num;
3680 } else if((fr == 29970) || (fr == 23976)) {
3690 if(verbose && norm >= 0)
3691 fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3695 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3696 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3697 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3701 if(!strcmp(arg, "vcd")) {
3703 opt_video_codec("mpeg1video");
3704 opt_audio_codec("mp2");
3707 opt_frame_size(norm ? "352x240" : "352x288");
3708 opt_frame_rate(frame_rates[norm]);
3709 opt_default("gop", norm ? "18" : "15");
3711 opt_default("b", "1150000");
3712 opt_default("maxrate", "1150000");
3713 opt_default("minrate", "1150000");
3714 video_rc_buffer_size = 40*1024*8;
3716 audio_bit_rate = 224000;
3717 audio_sample_rate = 44100;
3719 mux_packet_size= 2324;
3720 mux_rate= 2352 * 75 * 8;
3722 /* We have to offset the PTS, so that it is consistent with the SCR.
3723 SCR starts at 36000, but the first two packs contain only padding
3724 and the first pack from the other stream, respectively, may also have
3725 been written before.
3726 So the real data starts at SCR 36000+3*1200. */
3727 mux_preload= (36000+3*1200) / 90000.0; //0.44
3728 } else if(!strcmp(arg, "svcd")) {
3730 opt_video_codec("mpeg2video");
3731 opt_audio_codec("mp2");
3734 opt_frame_size(norm ? "480x480" : "480x576");
3735 opt_frame_rate(frame_rates[norm]);
3736 opt_default("gop", norm ? "18" : "15");
3738 opt_default("b", "2040000");
3739 opt_default("maxrate", "2516000");
3740 opt_default("minrate", "0"); //1145000;
3741 video_rc_buffer_size = 224*1024*8;
3742 opt_default("flags", "+SCAN_OFFSET");
3745 audio_bit_rate = 224000;
3746 audio_sample_rate = 44100;
3748 mux_packet_size= 2324;
3750 } else if(!strcmp(arg, "dvd")) {
3752 opt_video_codec("mpeg2video");
3753 opt_audio_codec("ac3");
3756 opt_frame_size(norm ? "720x480" : "720x576");
3757 opt_frame_rate(frame_rates[norm]);
3758 opt_default("gop", norm ? "18" : "15");
3760 opt_default("b", "6000000");
3761 opt_default("maxrate", "9000000");
3762 opt_default("minrate", "0"); //1500000;
3763 video_rc_buffer_size = 224*1024*8;
3765 mux_packet_size= 2048; // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3766 mux_rate = 10080000; // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3768 audio_bit_rate = 448000;
3769 audio_sample_rate = 48000;
3771 } else if(!strncmp(arg, "dv", 2)) {
3775 opt_frame_size(norm ? "720x480" : "720x576");
3776 opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3777 (norm ? "yuv411p" : "yuv420p"));
3778 opt_frame_rate(frame_rates[norm]);
3780 audio_sample_rate = 48000;
3784 fprintf(stderr, "Unknown target: %s\n", arg);
3789 static void opt_video_bsf(const char *arg)
3791 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3792 AVBitStreamFilterContext **bsfp;
3795 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3799 bsfp= &video_bitstream_filters;
3801 bsfp= &(*bsfp)->next;
3806 //FIXME avoid audio - video code duplication
3807 static void opt_audio_bsf(const char *arg)
3809 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3810 AVBitStreamFilterContext **bsfp;
3813 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3817 bsfp= &audio_bitstream_filters;
3819 bsfp= &(*bsfp)->next;
3824 static void show_version(void)
3826 /* TODO: add function interface to avutil and avformat */
3827 fprintf(stderr, "ffmpeg " FFMPEG_VERSION "\n"
3831 LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3835 static int opt_default(const char *opt, const char *arg){
3836 AVOption *o= av_set_string(avctx_opts, opt, arg);
3838 o = av_set_string(avformat_opts, opt, arg);
3842 // av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
3844 //FIXME we should always use avctx_opts, ... for storing options so there wont be any need to keep track of whats set over this
3845 opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
3846 opt_names[opt_name_count++]= o->name;
3848 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3849 /* disable generate of real time pts in ffm (need to be supressed anyway) */
3850 if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3854 if(avctx_opts->debug)
3855 av_log_set_level(AV_LOG_DEBUG);
3859 const OptionDef options[] = {
3861 { "L", 0, {(void*)show_license}, "show license" },
3862 { "h", 0, {(void*)show_help}, "show help" },
3863 { "version", 0, {(void*)show_version}, "show version" },
3864 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3865 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3866 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3867 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3868 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3869 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3870 { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3871 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3872 { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3873 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3874 { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3875 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3876 { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3877 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3878 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3879 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3880 { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3881 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3882 "add timings for benchmarking" },
3883 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3884 "dump each input packet" },
3885 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3886 "when dumping packets, also dump the payload" },
3887 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3888 { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3889 { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "number of times to loop output in formats that support looping (0 loops forever)", "" },
3890 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3891 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3892 { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3893 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3894 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3895 { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3896 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
3897 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3898 { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3901 { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3902 { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3903 { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3904 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3905 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3906 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3907 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3908 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3909 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3910 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3911 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3912 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3913 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3914 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3915 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3916 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3917 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3918 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3919 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3920 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
3921 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
3922 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
3923 { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
3924 { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
3925 { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
3926 { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
3927 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
3928 { "qsquish", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qsquish}, "how to keep quantiser between qmin and qmax (0 = clip, 1 = use differentiable function)", "squish" },
3929 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
3930 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3931 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
3932 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3933 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
3935 { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold", "" },
3936 { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold", "" },
3937 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
3938 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
3939 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
3940 { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
3941 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3942 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3943 "use same video quality as source (implies VBR)" },
3944 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3945 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3946 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3947 "deinterlace pictures" },
3948 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3949 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
3950 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3951 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3952 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3953 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3954 { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
3955 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3956 { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
3957 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3958 { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
3959 { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
3960 { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
3961 { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
3962 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
3965 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
3966 { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3967 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3968 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3969 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3970 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3971 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3972 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3973 { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3974 { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3976 /* subtitle options */
3977 { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
3978 { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
3979 { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
3982 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
3983 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3984 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3985 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
3987 /* G.2 grab options */
3988 { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
3989 { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
3992 { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
3993 { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
3994 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3995 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3997 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
3998 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
4000 { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4004 static void show_banner(void)
4006 fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
4007 fprintf(stderr, " configuration: " FFMPEG_CONFIGURATION "\n");
4008 fprintf(stderr, " libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
4009 fprintf(stderr, " libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
4010 fprintf(stderr, " libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
4011 fprintf(stderr, " built on " __DATE__ " " __TIME__);
4013 fprintf(stderr, ", gcc: " __VERSION__ "\n");
4015 fprintf(stderr, ", using a non-gcc compiler\n");
4019 static void show_license(void)
4024 "This program is free software; you can redistribute it and/or modify\n"
4025 "it under the terms of the GNU General Public License as published by\n"
4026 "the Free Software Foundation; either version 2 of the License, or\n"
4027 "(at your option) any later version.\n"
4029 "This program is distributed in the hope that it will be useful,\n"
4030 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4031 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
4032 "GNU General Public License for more details.\n"
4034 "You should have received a copy of the GNU General Public License\n"
4035 "along with this program; if not, write to the Free Software\n"
4036 "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
4040 "This library is free software; you can redistribute it and/or\n"
4041 "modify it under the terms of the GNU Lesser General Public\n"
4042 "License as published by the Free Software Foundation; either\n"
4043 "version 2 of the License, or (at your option) any later version.\n"
4045 "This library is distributed in the hope that it will be useful,\n"
4046 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4047 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
4048 "Lesser General Public License for more details.\n"
4050 "You should have received a copy of the GNU Lesser General Public\n"
4051 "License along with this library; if not, write to the Free Software\n"
4052 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
4058 static void show_help(void)
4061 printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4062 "Hyper fast Audio and Video encoder\n");
4064 show_help_options(options, "Main options:\n",
4065 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4066 show_help_options(options, "\nVideo options:\n",
4067 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4069 show_help_options(options, "\nAdvanced Video options:\n",
4070 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4071 OPT_VIDEO | OPT_EXPERT);
4072 show_help_options(options, "\nAudio options:\n",
4073 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4075 show_help_options(options, "\nAdvanced Audio options:\n",
4076 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4077 OPT_AUDIO | OPT_EXPERT);
4078 show_help_options(options, "\nSubtitle options:\n",
4079 OPT_SUBTITLE | OPT_GRAB,
4081 show_help_options(options, "\nAudio/Video grab options:\n",
4084 show_help_options(options, "\nAdvanced options:\n",
4085 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4087 av_opt_show(avctx_opts, NULL);
4088 av_opt_show(avformat_opts, NULL);
4093 void parse_arg_file(const char *filename)
4095 opt_output_file(filename);
4098 int main(int argc, char **argv)
4105 avctx_opts= avcodec_alloc_context();
4106 avformat_opts = av_alloc_format_context();
4114 parse_options(argc, argv, options);
4116 /* file converter / grab */
4117 if (nb_output_files <= 0) {
4118 fprintf(stderr, "Must supply at least one output file\n");
4122 if (nb_input_files == 0) {
4128 av_encode(output_files, nb_output_files, input_files, nb_input_files,
4129 stream_maps, nb_stream_maps);
4130 ti = getutime() - ti;
4132 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4136 for(i=0;i<nb_output_files;i++) {
4137 /* maybe av_close_output_file ??? */
4138 AVFormatContext *s = output_files[i];
4140 if (!(s->oformat->flags & AVFMT_NOFILE))
4142 for(j=0;j<s->nb_streams;j++)
4143 av_free(s->streams[j]);
4146 for(i=0;i<nb_input_files;i++)
4147 av_close_input_file(input_files[i]);
4152 av_free(intra_matrix);
4154 av_free(inter_matrix);
4156 #ifdef POWERPC_PERFORMANCE_REPORT
4157 extern void powerpc_display_perf_report(void);
4158 powerpc_display_perf_report();
4159 #endif /* POWERPC_PERFORMANCE_REPORT */
4162 if (received_sigterm) {
4164 "Received signal %d: terminating.\n",
4165 (int) received_sigterm);
4169 exit(0); /* not all OS-es handle main() return value */