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 int video_bit_rate_tolerance = 4000*1000;
109 static float video_qscale = 0;
110 static int video_qmin = 2;
111 static int video_qmax = 31;
112 static int video_lmin = 2*FF_QP2LAMBDA;
113 static int video_lmax = 31*FF_QP2LAMBDA;
114 static int video_mb_lmin = 2*FF_QP2LAMBDA;
115 static int video_mb_lmax = 31*FF_QP2LAMBDA;
116 static int video_qdiff = 3;
117 static float video_qblur = 0.5;
118 static float video_qsquish = 0.0;
119 static float video_qcomp = 0.5;
120 static uint16_t *intra_matrix = NULL;
121 static uint16_t *inter_matrix = NULL;
122 #if 0 //experimental, (can be removed)
123 static float video_rc_qsquish=1.0;
124 static float video_rc_qmod_amp=0;
125 static int video_rc_qmod_freq=0;
127 static char *video_rc_override_string=NULL;
128 static char *video_rc_eq="tex^qComp";
129 static int video_rc_buffer_size=0;
130 static float video_rc_buffer_aggressivity=1.0;
131 static float video_rc_initial_cplx=0;
132 static float video_b_qfactor = 1.25;
133 static float video_b_qoffset = 1.25;
134 static float video_i_qfactor = -0.8;
135 static float video_i_qoffset = 0.0;
136 static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
137 static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
138 static int me_method = ME_EPZS;
139 static int video_disable = 0;
140 static int video_discard = 0;
141 static int video_codec_id = CODEC_ID_NONE;
142 static int video_codec_tag = 0;
143 static int same_quality = 0;
144 static int b_frames = 0;
145 static int pre_me = 0;
146 static int do_deinterlace = 0;
147 static int workaround_bugs = FF_BUG_AUTODETECT;
148 static int packet_size = 0;
149 static int error_rate = 0;
150 static int strict = 0;
151 static int top_field_first = -1;
152 static int sc_threshold = 0;
153 static int me_threshold = 0;
154 static int mb_threshold = 0;
155 static int intra_dc_precision = 8;
156 static int me_penalty_compensation= 256;
157 static int frame_skip_threshold= 0;
158 static int frame_skip_factor= 0;
159 static int frame_skip_exp= 0;
160 static int loop_input = 0;
161 static int loop_output = AVFMT_NOOUTPUTLOOP;
162 static int qp_hist = 0;
164 static int intra_only = 0;
165 static int audio_sample_rate = 44100;
166 static int audio_bit_rate = 64000;
167 #define QSCALE_NONE -99999
168 static float audio_qscale = QSCALE_NONE;
169 static int audio_disable = 0;
170 static int audio_channels = 1;
171 static int audio_codec_id = CODEC_ID_NONE;
172 static int audio_codec_tag = 0;
173 static char *audio_language = NULL;
175 static int subtitle_codec_id = CODEC_ID_NONE;
176 static char *subtitle_language = NULL;
178 static int mux_rate= 0;
179 static int mux_packet_size= 0;
180 static float mux_preload= 0.5;
181 static float mux_max_delay= 0.7;
183 static int64_t recording_time = 0;
184 static int64_t start_time = 0;
185 static int64_t rec_timestamp = 0;
186 static int64_t input_ts_offset = 0;
187 static int file_overwrite = 0;
188 static char *str_title = NULL;
189 static char *str_author = NULL;
190 static char *str_copyright = NULL;
191 static char *str_comment = NULL;
192 static char *str_album = NULL;
193 static int do_benchmark = 0;
194 static int do_hex_dump = 0;
195 static int do_pkt_dump = 0;
196 static int do_psnr = 0;
197 static int do_vstats = 0;
198 static int do_pass = 0;
199 static char *pass_logfilename = NULL;
200 static int audio_stream_copy = 0;
201 static int video_stream_copy = 0;
202 static int subtitle_stream_copy = 0;
203 static int video_sync_method= 1;
204 static int audio_sync_method= 0;
205 static int copy_ts= 0;
206 static int opt_shortest = 0; //
207 static int video_global_header = 0;
209 static int rate_emu = 0;
212 static const char *video_grab_format = "bktr";
214 #ifdef CONFIG_VIDEO4LINUX2
215 static const char *video_grab_format = "video4linux2";
217 static const char *video_grab_format = "video4linux";
220 static char *video_device = NULL;
221 static char *grab_device = NULL;
222 static int video_channel = 0;
223 static char *video_standard = "ntsc";
225 static const char *audio_grab_format = "audio_device";
226 static char *audio_device = NULL;
227 static int audio_volume = 256;
229 static int using_stdin = 0;
230 static int using_vhook = 0;
231 static int verbose = 1;
232 static int thread_count= 1;
233 static int q_pressed = 0;
234 static int me_range = 0;
235 static int64_t video_size = 0;
236 static int64_t audio_size = 0;
237 static int64_t extra_size = 0;
238 static int nb_frames_dup = 0;
239 static int nb_frames_drop = 0;
240 static int input_sync;
241 static int limit_filesize = 0; //
243 static int pgmyuv_compatibility_hack=0;
244 static int dts_delta_threshold = 10;
246 static int sws_flags = SWS_BICUBIC;
248 const char **opt_names=NULL;
249 int opt_name_count=0;
250 AVCodecContext *avctx_opts;
251 AVFormatContext *avformat_opts;
253 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
254 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
255 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
257 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
259 struct AVInputStream;
261 typedef struct AVOutputStream {
262 int file_index; /* file index */
263 int index; /* stream index in the output file */
264 int source_index; /* AVInputStream index */
265 AVStream *st; /* stream in the output file */
266 int encoding_needed; /* true if encoding needed for this stream */
268 /* input pts and corresponding output pts
270 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
271 struct AVInputStream *sync_ist; /* input stream to sync against */
272 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
275 AVFrame pict_tmp; /* temporary image for resampling */
276 struct SwsContext *img_resample_ctx; /* for image resampling */
280 int topBand; /* cropping area sizes */
284 int padtop; /* padding area sizes */
291 ReSampleContext *resample; /* for audio resampling */
292 FifoBuffer fifo; /* for compression: one audio fifo per codec */
296 typedef struct AVInputStream {
300 int discard; /* true if stream data should be discarded */
301 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
302 int64_t sample_index; /* current sample */
304 int64_t start; /* time when read started */
305 unsigned long frame; /* current frame */
306 int64_t next_pts; /* synthetic pts for cases where pkt.pts
308 int64_t pts; /* current pts */
309 int is_start; /* is 1 at the start and after a discontinuity */
312 typedef struct AVInputFile {
313 int eof_reached; /* true if eof reached */
314 int ist_index; /* index of first stream in ist_table */
315 int buffer_size; /* current total buffer size */
316 int buffer_size_max; /* buffer size at which we consider we can stop
318 int nb_streams; /* nb streams we are aware of */
323 /* init terminal so that we can grab keys */
324 static struct termios oldtty;
326 static void term_exit(void)
328 tcsetattr (0, TCSANOW, &oldtty);
331 static volatile sig_atomic_t received_sigterm = 0;
334 sigterm_handler(int sig)
336 received_sigterm = sig;
340 static void term_init(void)
347 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
348 |INLCR|IGNCR|ICRNL|IXON);
349 tty.c_oflag |= OPOST;
350 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
351 tty.c_cflag &= ~(CSIZE|PARENB);
356 tcsetattr (0, TCSANOW, &tty);
358 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
359 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
360 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
362 register a function to be called at normal program termination
365 #ifdef CONFIG_BEOS_NETSERVER
366 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
370 /* read a key without blocking */
371 static int read_key(void)
375 #ifndef CONFIG_BEOS_NETSERVER
383 n = select(1, &rfds, NULL, NULL, &tv);
395 static int decode_interrupt_cb(void)
397 return q_pressed || (q_pressed = read_key() == 'q');
402 static volatile int received_sigterm = 0;
404 /* no interactive support */
405 static void term_exit(void)
409 static void term_init(void)
413 static int read_key(void)
420 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
425 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
428 /* copy stream format */
429 s->nb_streams = ic->nb_streams;
430 for(i=0;i<ic->nb_streams;i++) {
433 // FIXME: a more elegant solution is needed
434 st = av_mallocz(sizeof(AVStream));
435 memcpy(st, ic->streams[i], sizeof(AVStream));
436 st->codec = avcodec_alloc_context();
437 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
441 av_close_input_file(ic);
446 get_sync_ipts(const AVOutputStream *ost)
448 const AVInputStream *ist = ost->sync_ist;
449 return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
452 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
454 AVPacket new_pkt= *pkt;
455 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
456 &new_pkt.data, &new_pkt.size,
457 pkt->data, pkt->size,
458 pkt->flags & PKT_FLAG_KEY);
461 new_pkt.destruct= av_destruct_packet;
468 av_interleaved_write_frame(s, pkt);
471 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
473 static void do_audio_out(AVFormatContext *s,
476 unsigned char *buf, int size)
479 static uint8_t *audio_buf = NULL;
480 static uint8_t *audio_out = NULL;
481 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
483 int size_out, frame_bytes, ret;
484 AVCodecContext *enc= ost->st->codec;
486 /* SC: dynamic allocation of buffers */
488 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
490 audio_out = av_malloc(audio_out_size);
491 if (!audio_buf || !audio_out)
492 return; /* Should signal an error ! */
494 if(audio_sync_method){
495 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
496 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
497 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
498 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
500 //FIXME resample delay
501 if(fabs(delta) > 50){
504 byte_delta= FFMAX(byte_delta, -size);
508 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
513 static uint8_t *input_tmp= NULL;
514 input_tmp= av_realloc(input_tmp, byte_delta + size);
516 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
519 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
521 memset(input_tmp, 0, byte_delta);
522 memcpy(input_tmp + byte_delta, buf, size);
526 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
528 }else if(audio_sync_method>1){
529 int comp= clip(delta, -audio_sync_method, audio_sync_method);
530 assert(ost->audio_resample);
532 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
533 // 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));
534 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
538 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
539 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
541 if (ost->audio_resample) {
543 size_out = audio_resample(ost->resample,
544 (short *)buftmp, (short *)buf,
545 size / (ist->st->codec->channels * 2));
546 size_out = size_out * enc->channels * 2;
552 /* now encode as many frames as possible */
553 if (enc->frame_size > 1) {
554 /* output resampled raw samples */
555 fifo_write(&ost->fifo, buftmp, size_out,
558 frame_bytes = enc->frame_size * 2 * enc->channels;
560 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
561 &ost->fifo.rptr) == 0) {
563 av_init_packet(&pkt);
565 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
568 pkt.stream_index= ost->index;
571 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
572 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
573 pkt.flags |= PKT_FLAG_KEY;
574 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
576 ost->sync_opts += enc->frame_size;
580 av_init_packet(&pkt);
582 ost->sync_opts += size_out / (2 * enc->channels);
584 /* output a pcm frame */
585 /* XXX: change encoding codec API to avoid this ? */
586 switch(enc->codec->id) {
587 case CODEC_ID_PCM_S32LE:
588 case CODEC_ID_PCM_S32BE:
589 case CODEC_ID_PCM_U32LE:
590 case CODEC_ID_PCM_U32BE:
591 size_out = size_out << 1;
593 case CODEC_ID_PCM_S24LE:
594 case CODEC_ID_PCM_S24BE:
595 case CODEC_ID_PCM_U24LE:
596 case CODEC_ID_PCM_U24BE:
597 case CODEC_ID_PCM_S24DAUD:
598 size_out = size_out / 2 * 3;
600 case CODEC_ID_PCM_S16LE:
601 case CODEC_ID_PCM_S16BE:
602 case CODEC_ID_PCM_U16LE:
603 case CODEC_ID_PCM_U16BE:
606 size_out = size_out >> 1;
609 ret = avcodec_encode_audio(enc, audio_out, size_out,
612 pkt.stream_index= ost->index;
615 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
616 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
617 pkt.flags |= PKT_FLAG_KEY;
618 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
622 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
626 AVPicture picture_tmp;
629 dec = ist->st->codec;
631 /* deinterlace : must be done before any resize */
632 if (do_deinterlace || using_vhook) {
635 /* create temporary picture */
636 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
637 buf = av_malloc(size);
641 picture2 = &picture_tmp;
642 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
645 if(avpicture_deinterlace(picture2, picture,
646 dec->pix_fmt, dec->width, dec->height) < 0) {
647 /* if error, do not deinterlace */
653 img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
659 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
661 if (picture != picture2)
662 *picture = *picture2;
666 /* we begin to correct av delay at this threshold */
667 #define AV_DELAY_MAX 0.100
669 static void do_subtitle_out(AVFormatContext *s,
675 static uint8_t *subtitle_out = NULL;
676 int subtitle_out_max_size = 65536;
677 int subtitle_out_size, nb, i;
681 if (pts == AV_NOPTS_VALUE) {
682 fprintf(stderr, "Subtitle packets must have a pts\n");
686 enc = ost->st->codec;
689 subtitle_out = av_malloc(subtitle_out_max_size);
692 /* Note: DVB subtitle need one packet to draw them and one other
693 packet to clear them */
694 /* XXX: signal it in the codec context ? */
695 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
700 for(i = 0; i < nb; i++) {
701 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
702 subtitle_out_max_size, sub);
704 av_init_packet(&pkt);
705 pkt.stream_index = ost->index;
706 pkt.data = subtitle_out;
707 pkt.size = subtitle_out_size;
708 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);
709 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
710 /* XXX: the pts correction is handled here. Maybe handling
711 it in the codec would be better */
713 pkt.pts += 90 * sub->start_display_time;
715 pkt.pts += 90 * sub->end_display_time;
717 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
721 static int bit_buffer_size= 1024*256;
722 static uint8_t *bit_buffer= NULL;
724 static void do_video_out(AVFormatContext *s,
730 int nb_frames, i, ret;
731 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
732 AVFrame picture_crop_temp, picture_pad_temp;
733 uint8_t *buf = NULL, *buf1 = NULL;
734 AVCodecContext *enc, *dec;
736 avcodec_get_frame_defaults(&picture_crop_temp);
737 avcodec_get_frame_defaults(&picture_pad_temp);
739 enc = ost->st->codec;
740 dec = ist->st->codec;
742 /* by default, we output a single frame */
747 if(video_sync_method){
749 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
750 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
753 else if (vdelta > 1.1)
754 nb_frames = lrintf(vdelta);
755 //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);
759 fprintf(stderr, "*** drop!\n");
760 }else if (nb_frames > 1) {
761 nb_frames_dup += nb_frames;
763 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
766 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
768 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
772 if (ost->video_crop) {
773 if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
774 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
777 formatted_picture = &picture_crop_temp;
779 formatted_picture = in_picture;
782 final_picture = formatted_picture;
783 padding_src = formatted_picture;
784 resampling_dst = &ost->pict_tmp;
785 if (ost->video_pad) {
786 final_picture = &ost->pict_tmp;
787 if (ost->video_resample) {
788 if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
789 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
792 resampling_dst = &picture_pad_temp;
796 if (ost->video_resample) {
798 final_picture = &ost->pict_tmp;
799 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
800 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
803 if (ost->video_pad) {
804 img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
805 enc->height, enc->width, enc->pix_fmt,
806 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
809 /* duplicates frame if needed */
810 for(i=0;i<nb_frames;i++) {
812 av_init_packet(&pkt);
813 pkt.stream_index= ost->index;
815 if (s->oformat->flags & AVFMT_RAWPICTURE) {
816 /* raw pictures are written as AVPicture structure to
817 avoid any copies. We support temorarily the older
819 AVFrame* old_frame = enc->coded_frame;
820 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
821 pkt.data= (uint8_t *)final_picture;
822 pkt.size= sizeof(AVPicture);
823 if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
824 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
825 if(dec->coded_frame && dec->coded_frame->key_frame)
826 pkt.flags |= PKT_FLAG_KEY;
828 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
829 enc->coded_frame = old_frame;
833 big_picture= *final_picture;
834 /* better than nothing: use input picture interlaced
836 big_picture.interlaced_frame = in_picture->interlaced_frame;
837 if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
838 if(top_field_first == -1)
839 big_picture.top_field_first = in_picture->top_field_first;
841 big_picture.top_field_first = top_field_first;
844 /* handles sameq here. This is not correct because it may
845 not be a global option */
847 big_picture.quality = ist->st->quality;
849 big_picture.quality = ost->st->quality;
851 big_picture.pict_type = 0;
852 // big_picture.pts = AV_NOPTS_VALUE;
853 big_picture.pts= ost->sync_opts;
854 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
855 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
856 ret = avcodec_encode_video(enc,
857 bit_buffer, bit_buffer_size,
859 //enc->frame_number = enc->real_pict_num;
861 pkt.data= bit_buffer;
863 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
864 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
865 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
866 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
867 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
869 if(enc->coded_frame && enc->coded_frame->key_frame)
870 pkt.flags |= PKT_FLAG_KEY;
871 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
873 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
874 // enc->frame_number-1, enc->real_pict_num, ret,
876 /* if two pass, output log */
877 if (ost->logfile && enc->stats_out) {
878 fprintf(ost->logfile, "%s", enc->stats_out);
890 static double psnr(double d){
891 if(d==0) return INFINITY;
892 return -10.0*log(d)/log(10.0);
895 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
898 static FILE *fvstats=NULL;
905 double ti1, bitrate, avg_bitrate;
909 today = localtime(&today2);
910 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
913 fvstats = fopen(filename,"w");
921 enc = ost->st->codec;
922 if (enc->codec_type == CODEC_TYPE_VIDEO) {
923 frame_number = ost->frame_number;
924 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
925 if (enc->flags&CODEC_FLAG_PSNR)
926 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
928 fprintf(fvstats,"f_size= %6d ", frame_size);
929 /* compute pts value */
930 ti1 = ost->sync_opts * av_q2d(enc->time_base);
934 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
935 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
936 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
937 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
938 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
942 static void print_report(AVFormatContext **output_files,
943 AVOutputStream **ost_table, int nb_ostreams,
948 AVFormatContext *oc, *os;
951 int frame_number, vid, i;
952 double bitrate, ti1, pts;
953 static int64_t last_time = -1;
954 static int qp_histogram[52];
956 if (!is_last_report) {
958 /* display the report every 0.5 seconds */
959 cur_time = av_gettime();
960 if (last_time == -1) {
961 last_time = cur_time;
964 if ((cur_time - last_time) < 500000)
966 last_time = cur_time;
970 oc = output_files[0];
972 total_size = url_ftell(&oc->pb);
977 for(i=0;i<nb_ostreams;i++) {
979 os = output_files[ost->file_index];
980 enc = ost->st->codec;
981 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
982 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
983 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
985 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
986 frame_number = ost->frame_number;
987 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
988 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
990 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
991 if(qp_hist && enc->coded_frame){
993 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
994 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
997 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
999 if (enc->flags&CODEC_FLAG_PSNR){
1001 double error, error_sum=0;
1002 double scale, scale_sum=0;
1003 char type[3]= {'Y','U','V'};
1004 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1007 error= enc->error[j];
1008 scale= enc->width*enc->height*255.0*255.0*frame_number;
1010 error= enc->coded_frame->error[j];
1011 scale= enc->width*enc->height*255.0*255.0;
1016 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1018 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1022 /* compute min output value */
1023 pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1024 if ((pts < ti1) && (pts > 0))
1030 if (verbose || is_last_report) {
1031 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1033 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1034 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1035 (double)total_size / 1024, ti1, bitrate);
1038 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1039 nb_frames_dup, nb_frames_drop);
1042 fprintf(stderr, "%s \r", buf);
1047 if (is_last_report && verbose >= 0){
1048 int64_t raw= audio_size + video_size + extra_size;
1049 fprintf(stderr, "\n");
1050 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1054 100.0*(total_size - raw)/raw
1059 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1060 static int output_packet(AVInputStream *ist, int ist_index,
1061 AVOutputStream **ost_table, int nb_ostreams,
1062 const AVPacket *pkt)
1064 AVFormatContext *os;
1065 AVOutputStream *ost;
1069 int data_size, got_picture;
1071 void *buffer_to_free;
1072 static unsigned int samples_size= 0;
1073 static short *samples= NULL;
1074 AVSubtitle subtitle, *subtitle_to_free;
1078 ist->pts= ist->next_pts; // needed for last packet if vsync=0
1079 } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1080 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1082 // assert(ist->pts == ist->next_pts);
1096 /* decode the packet if needed */
1097 data_buf = NULL; /* fail safe */
1099 subtitle_to_free = NULL;
1100 if (ist->decoding_needed) {
1101 switch(ist->st->codec->codec_type) {
1102 case CODEC_TYPE_AUDIO:{
1104 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1105 /* XXX: could avoid copy if PCM 16 bits with same
1106 endianness as CPU */
1107 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1113 /* Some bug in mpeg audio decoder gives */
1114 /* data_size < 0, it seems they are overflows */
1115 if (data_size <= 0) {
1116 /* no audio frame */
1119 data_buf = (uint8_t *)samples;
1120 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1121 (ist->st->codec->sample_rate * ist->st->codec->channels);
1123 case CODEC_TYPE_VIDEO:
1124 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1125 /* XXX: allocate picture correctly */
1126 avcodec_get_frame_defaults(&picture);
1128 ret = avcodec_decode_video(ist->st->codec,
1129 &picture, &got_picture, ptr, len);
1130 ist->st->quality= picture.quality;
1134 /* no picture yet */
1135 goto discard_packet;
1137 if (ist->st->codec->time_base.num != 0) {
1138 ist->next_pts += ((int64_t)AV_TIME_BASE *
1139 ist->st->codec->time_base.num) /
1140 ist->st->codec->time_base.den;
1144 case CODEC_TYPE_SUBTITLE:
1145 ret = avcodec_decode_subtitle(ist->st->codec,
1146 &subtitle, &got_subtitle, ptr, len);
1149 if (!got_subtitle) {
1150 goto discard_packet;
1152 subtitle_to_free = &subtitle;
1159 switch(ist->st->codec->codec_type) {
1160 case CODEC_TYPE_AUDIO:
1161 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1162 (ist->st->codec->sample_rate * ist->st->codec->channels);
1164 case CODEC_TYPE_VIDEO:
1165 if (ist->st->codec->time_base.num != 0) {
1166 ist->next_pts += ((int64_t)AV_TIME_BASE *
1167 ist->st->codec->time_base.num) /
1168 ist->st->codec->time_base.den;
1178 buffer_to_free = NULL;
1179 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1180 pre_process_video_frame(ist, (AVPicture *)&picture,
1184 // preprocess audio (volume)
1185 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1186 if (audio_volume != 256) {
1189 for(i=0;i<(data_size / sizeof(short));i++) {
1190 int v = ((*volp) * audio_volume + 128) >> 8;
1191 if (v < -32768) v = -32768;
1192 if (v > 32767) v = 32767;
1198 /* frame rate emulation */
1199 if (ist->st->codec->rate_emu) {
1200 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1201 int64_t now = av_gettime() - ist->start;
1209 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1210 is the one of the next displayed one */
1211 /* XXX: add mpeg4 too ? */
1212 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1213 if (ist->st->codec->pict_type != B_TYPE) {
1215 tmp = ist->last_ip_pts;
1216 ist->last_ip_pts = ist->frac_pts.val;
1217 ist->frac_pts.val = tmp;
1221 /* if output time reached then transcode raw format,
1222 encode packets and output them */
1223 if (start_time == 0 || ist->pts >= start_time)
1224 for(i=0;i<nb_ostreams;i++) {
1228 if (ost->source_index == ist_index) {
1229 os = output_files[ost->file_index];
1232 printf("%d: got pts=%0.3f %0.3f\n", i,
1233 (double)pkt->pts / AV_TIME_BASE,
1234 ((double)ist->pts / AV_TIME_BASE) -
1235 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1237 /* set the input output pts pairs */
1238 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1240 if (ost->encoding_needed) {
1241 switch(ost->st->codec->codec_type) {
1242 case CODEC_TYPE_AUDIO:
1243 do_audio_out(os, ost, ist, data_buf, data_size);
1245 case CODEC_TYPE_VIDEO:
1246 do_video_out(os, ost, ist, &picture, &frame_size);
1247 video_size += frame_size;
1248 if (do_vstats && frame_size)
1249 do_video_stats(os, ost, frame_size);
1251 case CODEC_TYPE_SUBTITLE:
1252 do_subtitle_out(os, ost, ist, &subtitle,
1259 AVFrame avframe; //FIXME/XXX remove this
1261 av_init_packet(&opkt);
1263 /* no reencoding needed : output the packet directly */
1264 /* force the input stream PTS */
1266 avcodec_get_frame_defaults(&avframe);
1267 ost->st->codec->coded_frame= &avframe;
1268 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1270 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1271 audio_size += data_size;
1272 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1273 video_size += data_size;
1277 opkt.stream_index= ost->index;
1278 if(pkt->pts != AV_NOPTS_VALUE)
1279 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);
1281 opkt.pts= AV_NOPTS_VALUE;
1285 if (pkt->dts == AV_NOPTS_VALUE)
1286 dts = ist->next_pts;
1288 dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1289 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1291 opkt.flags= pkt->flags;
1293 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1294 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1295 opkt.destruct= av_destruct_packet;
1297 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1298 ost->st->codec->frame_number++;
1299 ost->frame_number++;
1300 av_free_packet(&opkt);
1304 av_free(buffer_to_free);
1305 /* XXX: allocate the subtitles in the codec ? */
1306 if (subtitle_to_free) {
1307 if (subtitle_to_free->rects != NULL) {
1308 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1309 av_free(subtitle_to_free->rects[i].bitmap);
1310 av_free(subtitle_to_free->rects[i].rgba_palette);
1312 av_freep(&subtitle_to_free->rects);
1314 subtitle_to_free->num_rects = 0;
1315 subtitle_to_free = NULL;
1322 for(i=0;i<nb_ostreams;i++) {
1324 if (ost->source_index == ist_index) {
1325 AVCodecContext *enc= ost->st->codec;
1326 os = output_files[ost->file_index];
1328 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1330 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1333 if (ost->encoding_needed) {
1337 av_init_packet(&pkt);
1338 pkt.stream_index= ost->index;
1340 switch(ost->st->codec->codec_type) {
1341 case CODEC_TYPE_AUDIO:
1342 fifo_bytes = fifo_size(&ost->fifo, NULL);
1344 /* encode any samples remaining in fifo */
1345 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1346 int fs_tmp = enc->frame_size;
1347 enc->frame_size = fifo_bytes / (2 * enc->channels);
1348 if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1349 &ost->fifo.rptr) == 0) {
1350 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1352 enc->frame_size = fs_tmp;
1355 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1358 pkt.flags |= PKT_FLAG_KEY;
1360 case CODEC_TYPE_VIDEO:
1361 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1363 if(enc->coded_frame && enc->coded_frame->key_frame)
1364 pkt.flags |= PKT_FLAG_KEY;
1365 if (ost->logfile && enc->stats_out) {
1366 fprintf(ost->logfile, "%s", enc->stats_out);
1375 pkt.data= bit_buffer;
1377 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1378 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1379 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1393 * The following code is the main loop of the file converter
1395 static int av_encode(AVFormatContext **output_files,
1396 int nb_output_files,
1397 AVFormatContext **input_files,
1399 AVStreamMap *stream_maps, int nb_stream_maps)
1401 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1402 AVFormatContext *is, *os;
1403 AVCodecContext *codec, *icodec;
1404 AVOutputStream *ost, **ost_table = NULL;
1405 AVInputStream *ist, **ist_table = NULL;
1406 AVInputFile *file_table;
1407 AVFormatContext *stream_no_data;
1410 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1414 /* input stream init */
1416 for(i=0;i<nb_input_files;i++) {
1417 is = input_files[i];
1418 file_table[i].ist_index = j;
1419 file_table[i].nb_streams = is->nb_streams;
1420 j += is->nb_streams;
1424 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1428 for(i=0;i<nb_istreams;i++) {
1429 ist = av_mallocz(sizeof(AVInputStream));
1435 for(i=0;i<nb_input_files;i++) {
1436 is = input_files[i];
1437 for(k=0;k<is->nb_streams;k++) {
1438 ist = ist_table[j++];
1439 ist->st = is->streams[k];
1440 ist->file_index = i;
1442 ist->discard = 1; /* the stream is discarded by default
1445 if (ist->st->codec->rate_emu) {
1446 ist->start = av_gettime();
1452 /* output stream init */
1454 for(i=0;i<nb_output_files;i++) {
1455 os = output_files[i];
1456 nb_ostreams += os->nb_streams;
1458 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1459 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1463 /* Sanity check the mapping args -- do the input files & streams exist? */
1464 for(i=0;i<nb_stream_maps;i++) {
1465 int fi = stream_maps[i].file_index;
1466 int si = stream_maps[i].stream_index;
1468 if (fi < 0 || fi > nb_input_files - 1 ||
1469 si < 0 || si > file_table[fi].nb_streams - 1) {
1470 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1473 fi = stream_maps[i].sync_file_index;
1474 si = stream_maps[i].sync_stream_index;
1475 if (fi < 0 || fi > nb_input_files - 1 ||
1476 si < 0 || si > file_table[fi].nb_streams - 1) {
1477 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1482 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1485 for(i=0;i<nb_ostreams;i++) {
1486 ost = av_mallocz(sizeof(AVOutputStream));
1493 for(k=0;k<nb_output_files;k++) {
1494 os = output_files[k];
1495 for(i=0;i<os->nb_streams;i++) {
1497 ost = ost_table[n++];
1498 ost->file_index = k;
1500 ost->st = os->streams[i];
1501 if (nb_stream_maps > 0) {
1502 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1503 stream_maps[n-1].stream_index;
1505 /* Sanity check that the stream types match */
1506 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1507 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1508 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1509 ost->file_index, ost->index);
1514 /* get corresponding input stream index : we select the first one with the right type */
1516 for(j=0;j<nb_istreams;j++) {
1519 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1520 ost->source_index = j;
1527 /* try again and reuse existing stream */
1528 for(j=0;j<nb_istreams;j++) {
1530 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1531 ost->source_index = j;
1536 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1537 ost->file_index, ost->index);
1542 ist = ist_table[ost->source_index];
1544 ost->sync_ist = (nb_stream_maps > 0) ?
1545 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1546 stream_maps[n-1].sync_stream_index] : ist;
1550 /* for each output stream, we compute the right encoding parameters */
1551 for(i=0;i<nb_ostreams;i++) {
1553 ist = ist_table[ost->source_index];
1555 codec = ost->st->codec;
1556 icodec = ist->st->codec;
1558 if (ost->st->stream_copy) {
1559 /* if stream_copy is selected, no need to decode or encode */
1560 codec->codec_id = icodec->codec_id;
1561 codec->codec_type = icodec->codec_type;
1562 if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1563 codec->bit_rate = icodec->bit_rate;
1564 codec->extradata= icodec->extradata;
1565 codec->extradata_size= icodec->extradata_size;
1566 codec->time_base = icodec->time_base;
1567 switch(codec->codec_type) {
1568 case CODEC_TYPE_AUDIO:
1569 codec->sample_rate = icodec->sample_rate;
1570 codec->channels = icodec->channels;
1571 codec->frame_size = icodec->frame_size;
1572 codec->block_align= icodec->block_align;
1574 case CODEC_TYPE_VIDEO:
1575 codec->pix_fmt = icodec->pix_fmt;
1576 codec->width = icodec->width;
1577 codec->height = icodec->height;
1578 codec->has_b_frames = icodec->has_b_frames;
1580 case CODEC_TYPE_SUBTITLE:
1586 switch(codec->codec_type) {
1587 case CODEC_TYPE_AUDIO:
1588 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1591 if (codec->channels == icodec->channels &&
1592 codec->sample_rate == icodec->sample_rate) {
1593 ost->audio_resample = 0;
1595 if (codec->channels != icodec->channels &&
1596 (icodec->codec_id == CODEC_ID_AC3 ||
1597 icodec->codec_id == CODEC_ID_DTS)) {
1598 /* Special case for 5:1 AC3 and DTS input */
1599 /* and mono or stereo output */
1600 /* Request specific number of channels */
1601 icodec->channels = codec->channels;
1602 if (codec->sample_rate == icodec->sample_rate)
1603 ost->audio_resample = 0;
1605 ost->audio_resample = 1;
1608 ost->audio_resample = 1;
1611 if(audio_sync_method>1)
1612 ost->audio_resample = 1;
1614 if(ost->audio_resample){
1615 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1616 codec->sample_rate, icodec->sample_rate);
1618 printf("Can't resample. Aborting.\n");
1622 ist->decoding_needed = 1;
1623 ost->encoding_needed = 1;
1625 case CODEC_TYPE_VIDEO:
1626 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1627 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1628 ost->video_resample = ((codec->width != icodec->width -
1629 (frame_leftBand + frame_rightBand) +
1630 (frame_padleft + frame_padright)) ||
1631 (codec->height != icodec->height -
1632 (frame_topBand + frame_bottomBand) +
1633 (frame_padtop + frame_padbottom)) ||
1634 (codec->pix_fmt != icodec->pix_fmt));
1635 if (ost->video_crop) {
1636 ost->topBand = frame_topBand;
1637 ost->leftBand = frame_leftBand;
1639 if (ost->video_pad) {
1640 ost->padtop = frame_padtop;
1641 ost->padleft = frame_padleft;
1642 ost->padbottom = frame_padbottom;
1643 ost->padright = frame_padright;
1644 if (!ost->video_resample) {
1645 avcodec_get_frame_defaults(&ost->pict_tmp);
1646 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1647 codec->width, codec->height ) )
1651 if (ost->video_resample) {
1652 avcodec_get_frame_defaults(&ost->pict_tmp);
1653 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1654 codec->width, codec->height ) )
1657 ost->img_resample_ctx = sws_getContext(
1658 icodec->width - (frame_leftBand + frame_rightBand),
1659 icodec->height - (frame_topBand + frame_bottomBand),
1661 codec->width - (frame_padleft + frame_padright),
1662 codec->height - (frame_padtop + frame_padbottom),
1664 sws_flags, NULL, NULL, NULL);
1665 if (ost->img_resample_ctx == NULL) {
1666 fprintf(stderr, "Cannot get resampling context\n");
1669 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1671 ost->encoding_needed = 1;
1672 ist->decoding_needed = 1;
1674 case CODEC_TYPE_SUBTITLE:
1675 ost->encoding_needed = 1;
1676 ist->decoding_needed = 1;
1683 if (ost->encoding_needed &&
1684 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1685 char logfilename[1024];
1690 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1692 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1693 if (codec->flags & CODEC_FLAG_PASS1) {
1694 f = fopen(logfilename, "w");
1696 perror(logfilename);
1701 /* read the log file */
1702 f = fopen(logfilename, "r");
1704 perror(logfilename);
1707 fseek(f, 0, SEEK_END);
1709 fseek(f, 0, SEEK_SET);
1710 logbuffer = av_malloc(size + 1);
1712 fprintf(stderr, "Could not allocate log buffer\n");
1715 size = fread(logbuffer, 1, size, f);
1717 logbuffer[size] = '\0';
1718 codec->stats_in = logbuffer;
1722 if(codec->codec_type == CODEC_TYPE_VIDEO){
1723 int size= codec->width * codec->height;
1724 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1729 bit_buffer = av_malloc(bit_buffer_size);
1733 /* dump the file output parameters - cannot be done before in case
1735 for(i=0;i<nb_output_files;i++) {
1736 dump_format(output_files[i], i, output_files[i]->filename, 1);
1739 /* dump the stream mapping */
1741 fprintf(stderr, "Stream mapping:\n");
1742 for(i=0;i<nb_ostreams;i++) {
1744 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1745 ist_table[ost->source_index]->file_index,
1746 ist_table[ost->source_index]->index,
1749 if (ost->sync_ist != ist_table[ost->source_index])
1750 fprintf(stderr, " [sync #%d.%d]",
1751 ost->sync_ist->file_index,
1752 ost->sync_ist->index);
1753 fprintf(stderr, "\n");
1757 /* open each encoder */
1758 for(i=0;i<nb_ostreams;i++) {
1760 if (ost->encoding_needed) {
1762 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1764 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1765 ost->file_index, ost->index);
1768 if (avcodec_open(ost->st->codec, codec) < 0) {
1769 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1770 ost->file_index, ost->index);
1773 extra_size += ost->st->codec->extradata_size;
1777 /* open each decoder */
1778 for(i=0;i<nb_istreams;i++) {
1780 if (ist->decoding_needed) {
1782 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1784 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1785 ist->st->codec->codec_id, ist->file_index, ist->index);
1788 if (avcodec_open(ist->st->codec, codec) < 0) {
1789 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1790 ist->file_index, ist->index);
1793 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1794 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1799 for(i=0;i<nb_istreams;i++) {
1801 is = input_files[ist->file_index];
1803 ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1804 if(ist->st->start_time == AV_NOPTS_VALUE)
1806 if(input_files_ts_offset[ist->file_index])
1807 ist->next_pts= AV_NOPTS_VALUE;
1811 /* compute buffer size max (should use a complete heuristic) */
1812 for(i=0;i<nb_input_files;i++) {
1813 file_table[i].buffer_size_max = 2048;
1816 /* set meta data information from input file if required */
1817 for (i=0;i<nb_meta_data_maps;i++) {
1818 AVFormatContext *out_file;
1819 AVFormatContext *in_file;
1821 int out_file_index = meta_data_maps[i].out_file;
1822 int in_file_index = meta_data_maps[i].in_file;
1823 if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1824 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1828 if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1829 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1834 out_file = output_files[out_file_index];
1835 in_file = input_files[in_file_index];
1837 strcpy(out_file->title, in_file->title);
1838 strcpy(out_file->author, in_file->author);
1839 strcpy(out_file->copyright, in_file->copyright);
1840 strcpy(out_file->comment, in_file->comment);
1841 strcpy(out_file->album, in_file->album);
1842 out_file->year = in_file->year;
1843 out_file->track = in_file->track;
1844 strcpy(out_file->genre, in_file->genre);
1847 /* open files and write file headers */
1848 for(i=0;i<nb_output_files;i++) {
1849 os = output_files[i];
1850 if (av_write_header(os) < 0) {
1851 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1858 if ( !using_stdin && verbose >= 0) {
1859 fprintf(stderr, "Press [q] to stop encoding\n");
1860 url_set_interrupt_cb(decode_interrupt_cb);
1868 for(; received_sigterm == 0;) {
1869 int file_index, ist_index;
1877 /* if 'q' pressed, exits */
1881 /* read_key() returns 0 on EOF */
1887 /* select the stream that we must read now by looking at the
1888 smallest output pts */
1890 for(i=0;i<nb_ostreams;i++) {
1893 os = output_files[ost->file_index];
1894 ist = ist_table[ost->source_index];
1895 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1896 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1898 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1899 ipts = (double)ist->pts;
1900 if (!file_table[ist->file_index].eof_reached){
1901 if(ipts < ipts_min) {
1903 if(input_sync ) file_index = ist->file_index;
1905 if(opts < opts_min) {
1907 if(!input_sync) file_index = ist->file_index;
1910 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1915 /* if none, if is finished */
1916 if (file_index < 0) {
1920 /* finish if recording time exhausted */
1921 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1924 /* finish if limit size exhausted */
1925 if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1928 /* read a frame from it and output it in the fifo */
1929 is = input_files[file_index];
1930 if (av_read_frame(is, &pkt) < 0) {
1931 file_table[file_index].eof_reached = 1;
1932 if (opt_shortest) break; else continue; //
1936 stream_no_data = is;
1941 av_pkt_dump(stdout, &pkt, do_hex_dump);
1943 /* the following test is needed in case new streams appear
1944 dynamically in stream : we ignore them */
1945 if (pkt.stream_index >= file_table[file_index].nb_streams)
1946 goto discard_packet;
1947 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1948 ist = ist_table[ist_index];
1950 goto discard_packet;
1952 // 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);
1953 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1954 int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1955 if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1956 input_files_ts_offset[ist->file_index]-= delta;
1958 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1959 for(i=0; i<file_table[file_index].nb_streams; i++){
1960 int index= file_table[file_index].ist_index + i;
1961 ist_table[index]->next_pts += delta;
1962 ist_table[index]->is_start=1;
1967 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1968 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1971 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1972 ist->file_index, ist->index);
1974 av_free_packet(&pkt);
1979 av_free_packet(&pkt);
1981 /* dump report by using the output first video and audio streams */
1982 print_report(output_files, ost_table, nb_ostreams, 0);
1985 /* at the end of stream, we must flush the decoder buffers */
1986 for(i=0;i<nb_istreams;i++) {
1988 if (ist->decoding_needed) {
1989 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1995 /* write the trailer if needed and close file */
1996 for(i=0;i<nb_output_files;i++) {
1997 os = output_files[i];
1998 av_write_trailer(os);
2001 /* dump report by using the first video and audio streams */
2002 print_report(output_files, ost_table, nb_ostreams, 1);
2004 /* close each encoder */
2005 for(i=0;i<nb_ostreams;i++) {
2007 if (ost->encoding_needed) {
2008 av_freep(&ost->st->codec->stats_in);
2009 avcodec_close(ost->st->codec);
2013 /* close each decoder */
2014 for(i=0;i<nb_istreams;i++) {
2016 if (ist->decoding_needed) {
2017 avcodec_close(ist->st->codec);
2025 av_freep(&bit_buffer);
2026 av_free(file_table);
2029 for(i=0;i<nb_istreams;i++) {
2036 for(i=0;i<nb_ostreams;i++) {
2040 fclose(ost->logfile);
2041 ost->logfile = NULL;
2043 fifo_free(&ost->fifo); /* works even if fifo is not
2044 initialized but set to zero */
2045 av_free(ost->pict_tmp.data[0]);
2046 if (ost->video_resample)
2047 sws_freeContext(ost->img_resample_ctx);
2048 if (ost->audio_resample)
2049 audio_resample_close(ost->resample);
2062 int file_read(const char *filename)
2065 unsigned char buffer[1024];
2068 if (url_open(&h, filename, O_RDONLY) < 0) {
2069 printf("could not open '%s'\n", filename);
2073 len = url_read(h, buffer, sizeof(buffer));
2076 for(i=0;i<len;i++) putchar(buffer[i]);
2083 static void opt_image_format(const char *arg)
2087 for(f = first_image_format; f != NULL; f = f->next) {
2088 if (!strcmp(arg, f->name))
2092 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2098 static void opt_format(const char *arg)
2100 /* compatibility stuff for pgmyuv */
2101 if (!strcmp(arg, "pgmyuv")) {
2102 pgmyuv_compatibility_hack=1;
2103 // opt_image_format(arg);
2107 file_iformat = av_find_input_format(arg);
2108 file_oformat = guess_format(arg, NULL, NULL);
2109 if (!file_iformat && !file_oformat) {
2110 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2115 static void opt_video_bitrate_tolerance(const char *arg)
2117 video_bit_rate_tolerance = atoi(arg) * 1000;
2120 static void opt_video_buffer_size(const char *arg)
2122 video_rc_buffer_size = atoi(arg) * 8*1024;
2125 static void opt_video_rc_eq(char *arg)
2130 static void opt_video_rc_override_string(char *arg)
2132 video_rc_override_string = arg;
2136 static void opt_workaround_bugs(const char *arg)
2138 workaround_bugs = atoi(arg);
2141 static void opt_me_threshold(const char *arg)
2143 me_threshold = atoi(arg);
2146 static void opt_mb_threshold(const char *arg)
2148 mb_threshold = atoi(arg);
2151 static void opt_verbose(const char *arg)
2153 verbose = atoi(arg);
2154 av_log_set_level(atoi(arg));
2157 static void opt_frame_rate(const char *arg)
2159 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2160 fprintf(stderr, "Incorrect frame rate\n");
2165 static void opt_frame_crop_top(const char *arg)
2167 frame_topBand = atoi(arg);
2168 if (frame_topBand < 0) {
2169 fprintf(stderr, "Incorrect top crop size\n");
2172 if ((frame_topBand % 2) != 0) {
2173 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2176 if ((frame_topBand) >= frame_height){
2177 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2180 frame_height -= frame_topBand;
2183 static void opt_frame_crop_bottom(const char *arg)
2185 frame_bottomBand = atoi(arg);
2186 if (frame_bottomBand < 0) {
2187 fprintf(stderr, "Incorrect bottom crop size\n");
2190 if ((frame_bottomBand % 2) != 0) {
2191 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2194 if ((frame_bottomBand) >= frame_height){
2195 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2198 frame_height -= frame_bottomBand;
2201 static void opt_frame_crop_left(const char *arg)
2203 frame_leftBand = atoi(arg);
2204 if (frame_leftBand < 0) {
2205 fprintf(stderr, "Incorrect left crop size\n");
2208 if ((frame_leftBand % 2) != 0) {
2209 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2212 if ((frame_leftBand) >= frame_width){
2213 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2216 frame_width -= frame_leftBand;
2219 static void opt_frame_crop_right(const char *arg)
2221 frame_rightBand = atoi(arg);
2222 if (frame_rightBand < 0) {
2223 fprintf(stderr, "Incorrect right crop size\n");
2226 if ((frame_rightBand % 2) != 0) {
2227 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2230 if ((frame_rightBand) >= frame_width){
2231 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2234 frame_width -= frame_rightBand;
2237 static void opt_frame_size(const char *arg)
2239 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2240 fprintf(stderr, "Incorrect frame size\n");
2243 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2244 fprintf(stderr, "Frame size must be a multiple of 2\n");
2250 #define SCALEBITS 10
2251 #define ONE_HALF (1 << (SCALEBITS - 1))
2252 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2254 #define RGB_TO_Y(r, g, b) \
2255 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2256 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2258 #define RGB_TO_U(r1, g1, b1, shift)\
2259 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2260 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2262 #define RGB_TO_V(r1, g1, b1, shift)\
2263 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2264 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2266 static void opt_pad_color(const char *arg) {
2267 /* Input is expected to be six hex digits similar to
2268 how colors are expressed in html tags (but without the #) */
2269 int rgb = strtol(arg, NULL, 16);
2273 g = ((rgb >> 8) & 255);
2276 padcolor[0] = RGB_TO_Y(r,g,b);
2277 padcolor[1] = RGB_TO_U(r,g,b,0);
2278 padcolor[2] = RGB_TO_V(r,g,b,0);
2281 static void opt_frame_pad_top(const char *arg)
2283 frame_padtop = atoi(arg);
2284 if (frame_padtop < 0) {
2285 fprintf(stderr, "Incorrect top pad size\n");
2288 if ((frame_padtop % 2) != 0) {
2289 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2294 static void opt_frame_pad_bottom(const char *arg)
2296 frame_padbottom = atoi(arg);
2297 if (frame_padbottom < 0) {
2298 fprintf(stderr, "Incorrect bottom pad size\n");
2301 if ((frame_padbottom % 2) != 0) {
2302 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2308 static void opt_frame_pad_left(const char *arg)
2310 frame_padleft = atoi(arg);
2311 if (frame_padleft < 0) {
2312 fprintf(stderr, "Incorrect left pad size\n");
2315 if ((frame_padleft % 2) != 0) {
2316 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2322 static void opt_frame_pad_right(const char *arg)
2324 frame_padright = atoi(arg);
2325 if (frame_padright < 0) {
2326 fprintf(stderr, "Incorrect right pad size\n");
2329 if ((frame_padright % 2) != 0) {
2330 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2336 static void opt_frame_pix_fmt(const char *arg)
2338 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2341 static void opt_frame_aspect_ratio(const char *arg)
2347 p = strchr(arg, ':');
2349 x = strtol(arg, (char **)&arg, 10);
2351 y = strtol(arg+1, (char **)&arg, 10);
2353 ar = (double)x / (double)y;
2355 ar = strtod(arg, (char **)&arg);
2358 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2361 frame_aspect_ratio = ar;
2364 static void opt_b_frames(const char *arg)
2366 b_frames = atoi(arg);
2367 if (b_frames > FF_MAX_B_FRAMES) {
2368 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2370 } else if (b_frames < 1) {
2371 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2376 static void opt_pre_me(const char *arg)
2381 static void opt_qscale(const char *arg)
2383 video_qscale = atof(arg);
2384 if (video_qscale <= 0 ||
2385 video_qscale > 255) {
2386 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2391 static void opt_qsquish(const char *arg)
2393 video_qsquish = atof(arg);
2394 if (video_qsquish < 0.0 ||
2395 video_qsquish > 99.0) {
2396 fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2401 static void opt_lmax(const char *arg)
2403 video_lmax = atof(arg)*FF_QP2LAMBDA;
2406 static void opt_lmin(const char *arg)
2408 video_lmin = atof(arg)*FF_QP2LAMBDA;
2411 static void opt_qmin(const char *arg)
2413 video_qmin = atoi(arg);
2414 if (video_qmin < 1 ||
2416 fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2421 static void opt_qmax(const char *arg)
2423 video_qmax = atoi(arg);
2424 if (video_qmax < 1 ||
2426 fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2431 static void opt_mb_lmin(const char *arg)
2433 video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2434 if (video_mb_lmin < 1 ||
2435 video_mb_lmin > FF_LAMBDA_MAX) {
2436 fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2441 static void opt_mb_lmax(const char *arg)
2443 video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2444 if (video_mb_lmax < 1 ||
2445 video_mb_lmax > FF_LAMBDA_MAX) {
2446 fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2451 static void opt_qdiff(const char *arg)
2453 video_qdiff = atoi(arg);
2454 if (video_qdiff < 0 ||
2456 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2461 static void opt_qblur(const char *arg)
2463 video_qblur = atof(arg);
2466 static void opt_qcomp(const char *arg)
2468 video_qcomp = atof(arg);
2471 static void opt_rc_initial_cplx(const char *arg)
2473 video_rc_initial_cplx = atof(arg);
2475 static void opt_b_qfactor(const char *arg)
2477 video_b_qfactor = atof(arg);
2479 static void opt_i_qfactor(const char *arg)
2481 video_i_qfactor = atof(arg);
2483 static void opt_b_qoffset(const char *arg)
2485 video_b_qoffset = atof(arg);
2487 static void opt_i_qoffset(const char *arg)
2489 video_i_qoffset = atof(arg);
2492 static void opt_ibias(const char *arg)
2494 video_intra_quant_bias = atoi(arg);
2496 static void opt_pbias(const char *arg)
2498 video_inter_quant_bias = atoi(arg);
2501 static void opt_packet_size(const char *arg)
2503 packet_size= atoi(arg);
2506 static void opt_error_rate(const char *arg)
2508 error_rate= atoi(arg);
2511 static void opt_strict(const char *arg)
2516 static void opt_top_field_first(const char *arg)
2518 top_field_first= atoi(arg);
2521 static void opt_sc_threshold(const char *arg)
2523 sc_threshold= atoi(arg);
2526 static void opt_me_range(const char *arg)
2528 me_range = atoi(arg);
2531 static void opt_thread_count(const char *arg)
2533 thread_count= atoi(arg);
2534 #if !defined(HAVE_THREADS)
2536 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2540 static void opt_audio_bitrate(const char *arg)
2542 audio_bit_rate = atoi(arg) * 1000;
2545 static void opt_audio_rate(const char *arg)
2547 audio_sample_rate = atoi(arg);
2550 static void opt_audio_channels(const char *arg)
2552 audio_channels = atoi(arg);
2555 static void opt_video_device(const char *arg)
2557 video_device = av_strdup(arg);
2560 static void opt_grab_device(const char *arg)
2562 grab_device = av_strdup(arg);
2565 static void opt_video_channel(const char *arg)
2567 video_channel = strtol(arg, NULL, 0);
2570 static void opt_video_standard(const char *arg)
2572 video_standard = av_strdup(arg);
2575 static void opt_audio_device(const char *arg)
2577 audio_device = av_strdup(arg);
2580 static void opt_codec(int *pstream_copy, int *pcodec_id,
2581 int codec_type, const char *arg)
2585 if (!strcmp(arg, "copy")) {
2590 if (!strcmp(p->name, arg) && p->type == codec_type)
2595 fprintf(stderr, "Unknown codec '%s'\n", arg);
2603 static void opt_audio_codec(const char *arg)
2605 opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2608 static void opt_audio_tag(const char *arg)
2611 audio_codec_tag= strtol(arg, &tail, 0);
2614 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2617 static void opt_video_tag(const char *arg)
2620 video_codec_tag= strtol(arg, &tail, 0);
2623 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2626 static void add_frame_hooker(const char *arg)
2631 char *args = av_strdup(arg);
2635 argv[0] = strtok(args, " ");
2636 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2639 i = frame_hook_add(argc, argv);
2642 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2647 const char *motion_str[] = {
2660 static void opt_motion_estimation(const char *arg)
2666 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2669 if (!strcmp(*p, arg))
2673 me_method = (p - motion_str) + 1;
2676 static void opt_video_codec(const char *arg)
2678 opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2681 static void opt_subtitle_codec(const char *arg)
2683 opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2686 static void opt_map(const char *arg)
2692 m = &stream_maps[nb_stream_maps++];
2694 m->file_index = strtol(arg, (char **)&p, 0);
2698 m->stream_index = strtol(p, (char **)&p, 0);
2701 m->sync_file_index = strtol(p, (char **)&p, 0);
2704 m->sync_stream_index = strtol(p, (char **)&p, 0);
2706 m->sync_file_index = m->file_index;
2707 m->sync_stream_index = m->stream_index;
2711 static void opt_map_meta_data(const char *arg)
2717 m = &meta_data_maps[nb_meta_data_maps++];
2719 m->out_file = strtol(arg, (char **)&p, 0);
2723 m->in_file = strtol(p, (char **)&p, 0);
2726 static void opt_recording_time(const char *arg)
2728 recording_time = parse_date(arg, 1);
2731 static void opt_start_time(const char *arg)
2733 start_time = parse_date(arg, 1);
2736 static void opt_rec_timestamp(const char *arg)
2738 rec_timestamp = parse_date(arg, 0) / 1000000;
2741 static void opt_input_ts_offset(const char *arg)
2743 input_ts_offset = parse_date(arg, 1);
2746 static void opt_input_file(const char *filename)
2748 AVFormatContext *ic;
2749 AVFormatParameters params, *ap = ¶ms;
2750 int err, i, ret, rfps, rfps_base;
2753 if (!strcmp(filename, "-"))
2756 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2757 !strcmp( filename, "/dev/stdin" );
2759 /* get default parameters from command line */
2760 ic = av_alloc_format_context();
2762 memset(ap, 0, sizeof(*ap));
2763 ap->prealloced_context = 1;
2764 ap->sample_rate = audio_sample_rate;
2765 ap->channels = audio_channels;
2766 ap->time_base.den = frame_rate;
2767 ap->time_base.num = frame_rate_base;
2768 ap->width = frame_width + frame_padleft + frame_padright;
2769 ap->height = frame_height + frame_padtop + frame_padbottom;
2770 ap->image_format = image_format;
2771 ap->pix_fmt = frame_pix_fmt;
2772 ap->device = grab_device;
2773 ap->channel = video_channel;
2774 ap->standard = video_standard;
2775 ap->video_codec_id = video_codec_id;
2776 ap->audio_codec_id = audio_codec_id;
2777 if(pgmyuv_compatibility_hack)
2778 ap->video_codec_id= CODEC_ID_PGMYUV;
2780 for(i=0; i<opt_name_count; i++){
2782 double d= av_get_double(avformat_opts, opt_names[i], &opt);
2783 if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2784 av_set_double(ic, opt_names[i], d);
2786 /* open the input file with generic libav function */
2787 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2789 print_error(filename, err);
2793 ic->loop_input = loop_input;
2795 /* If not enough info to get the stream parameters, we decode the
2796 first frames to get it. (used in mpeg case for example) */
2797 ret = av_find_stream_info(ic);
2798 if (ret < 0 && verbose >= 0) {
2799 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2803 timestamp = start_time;
2804 /* add the stream start time */
2805 if (ic->start_time != AV_NOPTS_VALUE)
2806 timestamp += ic->start_time;
2808 /* if seeking requested, we execute it */
2809 if (start_time != 0) {
2810 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2812 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2813 filename, (double)timestamp / AV_TIME_BASE);
2815 /* reset seek info */
2819 /* update the current parameters so that they match the one of the input stream */
2820 for(i=0;i<ic->nb_streams;i++) {
2822 AVCodecContext *enc = ic->streams[i]->codec;
2823 #if defined(HAVE_THREADS)
2825 avcodec_thread_init(enc, thread_count);
2827 enc->thread_count= thread_count;
2828 switch(enc->codec_type) {
2829 case CODEC_TYPE_AUDIO:
2830 for(j=0; j<opt_name_count; j++){
2832 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2833 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2834 av_set_double(enc, opt_names[j], d);
2836 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2837 audio_channels = enc->channels;
2838 audio_sample_rate = enc->sample_rate;
2840 ic->streams[i]->discard= AVDISCARD_ALL;
2842 case CODEC_TYPE_VIDEO:
2843 for(j=0; j<opt_name_count; j++){
2845 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2846 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2847 av_set_double(enc, opt_names[j], d);
2849 frame_height = enc->height;
2850 frame_width = enc->width;
2851 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2852 frame_pix_fmt = enc->pix_fmt;
2853 rfps = ic->streams[i]->r_frame_rate.num;
2854 rfps_base = ic->streams[i]->r_frame_rate.den;
2855 enc->workaround_bugs = workaround_bugs;
2856 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2858 enc->debug |= FF_DEBUG_MV;
2860 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2863 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2864 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2866 (float)rfps / rfps_base, rfps, rfps_base);
2868 /* update the current frame rate to match the stream frame rate */
2870 frame_rate_base = rfps_base;
2872 enc->rate_emu = rate_emu;
2874 ic->streams[i]->discard= AVDISCARD_ALL;
2875 else if(video_discard)
2876 ic->streams[i]->discard= video_discard;
2878 case CODEC_TYPE_DATA:
2880 case CODEC_TYPE_SUBTITLE:
2882 case CODEC_TYPE_UNKNOWN:
2889 input_files[nb_input_files] = ic;
2890 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2891 /* dump the file content */
2893 dump_format(ic, nb_input_files, filename, 0);
2896 file_iformat = NULL;
2897 file_oformat = NULL;
2898 image_format = NULL;
2906 static void opt_grab(const char *arg)
2908 file_iformat = av_find_input_format(arg);
2912 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2914 int has_video, has_audio, i, j;
2915 AVFormatContext *ic;
2919 for(j=0;j<nb_input_files;j++) {
2920 ic = input_files[j];
2921 for(i=0;i<ic->nb_streams;i++) {
2922 AVCodecContext *enc = ic->streams[i]->codec;
2923 switch(enc->codec_type) {
2924 case CODEC_TYPE_AUDIO:
2927 case CODEC_TYPE_VIDEO:
2930 case CODEC_TYPE_DATA:
2931 case CODEC_TYPE_UNKNOWN:
2932 case CODEC_TYPE_SUBTITLE:
2939 *has_video_ptr = has_video;
2940 *has_audio_ptr = has_audio;
2943 static void new_video_stream(AVFormatContext *oc)
2946 AVCodecContext *video_enc;
2949 st = av_new_stream(oc, oc->nb_streams);
2951 fprintf(stderr, "Could not alloc stream\n");
2954 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2955 video_bitstream_filters= NULL;
2957 #if defined(HAVE_THREADS)
2959 avcodec_thread_init(st->codec, thread_count);
2962 video_enc = st->codec;
2965 video_enc->codec_tag= video_codec_tag;
2967 if( (video_global_header&1)
2968 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2969 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2970 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2972 if(video_global_header&2){
2973 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2974 avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2977 if (video_stream_copy) {
2978 st->stream_copy = 1;
2979 video_enc->codec_type = CODEC_TYPE_VIDEO;
2985 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2986 if (video_codec_id != CODEC_ID_NONE)
2987 codec_id = video_codec_id;
2989 video_enc->codec_id = codec_id;
2990 codec = avcodec_find_encoder(codec_id);
2992 for(i=0; i<opt_name_count; i++){
2994 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2995 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2996 av_set_double(video_enc, opt_names[i], d);
2999 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
3000 video_enc->time_base.den = frame_rate;
3001 video_enc->time_base.num = frame_rate_base;
3002 if(codec && codec->supported_framerates){
3003 const AVRational *p= codec->supported_framerates;
3004 AVRational req= (AVRational){frame_rate, frame_rate_base};
3005 const AVRational *best=NULL;
3006 AVRational best_error= (AVRational){INT_MAX, 1};
3007 for(; p->den!=0; p++){
3008 AVRational error= av_sub_q(req, *p);
3009 if(error.num <0) error.num *= -1;
3010 if(av_cmp_q(error, best_error) < 0){
3015 video_enc->time_base.den= best->num;
3016 video_enc->time_base.num= best->den;
3019 video_enc->width = frame_width + frame_padright + frame_padleft;
3020 video_enc->height = frame_height + frame_padtop + frame_padbottom;
3021 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3022 video_enc->pix_fmt = frame_pix_fmt;
3024 if(codec && codec->pix_fmts){
3025 const enum PixelFormat *p= codec->pix_fmts;
3027 if(*p == video_enc->pix_fmt)
3031 video_enc->pix_fmt = codec->pix_fmts[0];
3035 video_enc->gop_size = 0;
3036 if (video_qscale || same_quality) {
3037 video_enc->flags |= CODEC_FLAG_QSCALE;
3038 video_enc->global_quality=
3039 st->quality = FF_QP2LAMBDA * video_qscale;
3043 video_enc->intra_matrix = intra_matrix;
3045 video_enc->inter_matrix = inter_matrix;
3047 video_enc->pre_me = pre_me;
3050 video_enc->max_b_frames = b_frames;
3051 video_enc->b_quant_factor = 2.0;
3053 video_enc->qmin = video_qmin;
3054 video_enc->qmax = video_qmax;
3055 video_enc->lmin = video_lmin;
3056 video_enc->lmax = video_lmax;
3057 video_enc->rc_qsquish = video_qsquish;
3058 video_enc->mb_lmin = video_mb_lmin;
3059 video_enc->mb_lmax = video_mb_lmax;
3060 video_enc->max_qdiff = video_qdiff;
3061 video_enc->qblur = video_qblur;
3062 video_enc->qcompress = video_qcomp;
3063 video_enc->rc_eq = video_rc_eq;
3064 video_enc->workaround_bugs = workaround_bugs;
3065 video_enc->thread_count = thread_count;
3066 p= video_rc_override_string;
3069 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3071 fprintf(stderr, "error parsing rc_override\n");
3074 video_enc->rc_override=
3075 av_realloc(video_enc->rc_override,
3076 sizeof(RcOverride)*(i+1));
3077 video_enc->rc_override[i].start_frame= start;
3078 video_enc->rc_override[i].end_frame = end;
3080 video_enc->rc_override[i].qscale= q;
3081 video_enc->rc_override[i].quality_factor= 1.0;
3084 video_enc->rc_override[i].qscale= 0;
3085 video_enc->rc_override[i].quality_factor= -q/100.0;
3090 video_enc->rc_override_count=i;
3092 video_enc->rc_buffer_size = video_rc_buffer_size;
3093 video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3094 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3095 video_enc->rc_initial_cplx= video_rc_initial_cplx;
3096 video_enc->i_quant_factor = video_i_qfactor;
3097 video_enc->b_quant_factor = video_b_qfactor;
3098 video_enc->i_quant_offset = video_i_qoffset;
3099 video_enc->b_quant_offset = video_b_qoffset;
3100 video_enc->intra_quant_bias = video_intra_quant_bias;
3101 video_enc->inter_quant_bias = video_inter_quant_bias;
3102 video_enc->me_threshold= me_threshold;
3103 video_enc->mb_threshold= mb_threshold;
3104 video_enc->intra_dc_precision= intra_dc_precision - 8;
3105 video_enc->strict_std_compliance = strict;
3106 video_enc->error_rate = error_rate;
3107 video_enc->scenechange_threshold= sc_threshold;
3108 video_enc->me_range = me_range;
3109 video_enc->me_penalty_compensation= me_penalty_compensation;
3110 video_enc->frame_skip_threshold= frame_skip_threshold;
3111 video_enc->frame_skip_factor= frame_skip_factor;
3112 video_enc->frame_skip_exp= frame_skip_exp;
3115 video_enc->rtp_mode= 1;
3116 video_enc->rtp_payload_size= packet_size;
3120 video_enc->flags|= CODEC_FLAG_PSNR;
3122 video_enc->me_method = me_method;
3127 video_enc->flags |= CODEC_FLAG_PASS1;
3129 video_enc->flags |= CODEC_FLAG_PASS2;
3134 /* reset some key parameters */
3136 video_codec_id = CODEC_ID_NONE;
3137 video_stream_copy = 0;
3140 static void new_audio_stream(AVFormatContext *oc)
3143 AVCodecContext *audio_enc;
3146 st = av_new_stream(oc, oc->nb_streams);
3148 fprintf(stderr, "Could not alloc stream\n");
3152 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3153 audio_bitstream_filters= NULL;
3155 #if defined(HAVE_THREADS)
3157 avcodec_thread_init(st->codec, thread_count);
3160 audio_enc = st->codec;
3161 audio_enc->codec_type = CODEC_TYPE_AUDIO;
3164 audio_enc->codec_tag= audio_codec_tag;
3166 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3167 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3168 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3170 if (audio_stream_copy) {
3171 st->stream_copy = 1;
3172 audio_enc->channels = audio_channels;
3174 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3176 for(i=0; i<opt_name_count; i++){
3178 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3179 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3180 av_set_double(audio_enc, opt_names[i], d);
3183 if (audio_codec_id != CODEC_ID_NONE)
3184 codec_id = audio_codec_id;
3185 audio_enc->codec_id = codec_id;
3187 audio_enc->bit_rate = audio_bit_rate;
3188 if (audio_qscale > QSCALE_NONE) {
3189 audio_enc->flags |= CODEC_FLAG_QSCALE;
3190 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3192 audio_enc->strict_std_compliance = strict;
3193 audio_enc->thread_count = thread_count;
3194 /* For audio codecs other than AC3 or DTS we limit */
3195 /* the number of coded channels to stereo */
3196 if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3197 && codec_id != CODEC_ID_DTS) {
3198 audio_enc->channels = 2;
3200 audio_enc->channels = audio_channels;
3202 audio_enc->sample_rate = audio_sample_rate;
3203 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3204 if (audio_language) {
3205 pstrcpy(st->language, sizeof(st->language), audio_language);
3206 av_free(audio_language);
3207 audio_language = NULL;
3210 /* reset some key parameters */
3212 audio_codec_id = CODEC_ID_NONE;
3213 audio_stream_copy = 0;
3216 static void opt_new_subtitle_stream(void)
3218 AVFormatContext *oc;
3220 AVCodecContext *subtitle_enc;
3223 if (nb_output_files <= 0) {
3224 fprintf(stderr, "At least one output file must be specified\n");
3227 oc = output_files[nb_output_files - 1];
3229 st = av_new_stream(oc, oc->nb_streams);
3231 fprintf(stderr, "Could not alloc stream\n");
3235 subtitle_enc = st->codec;
3236 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3237 if (subtitle_stream_copy) {
3238 st->stream_copy = 1;
3240 for(i=0; i<opt_name_count; i++){
3242 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3243 if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3244 av_set_double(subtitle_enc, opt_names[i], d);
3246 subtitle_enc->codec_id = subtitle_codec_id;
3249 if (subtitle_language) {
3250 pstrcpy(st->language, sizeof(st->language), subtitle_language);
3251 av_free(subtitle_language);
3252 subtitle_language = NULL;
3255 subtitle_codec_id = CODEC_ID_NONE;
3256 subtitle_stream_copy = 0;
3259 static void opt_new_audio_stream(void)
3261 AVFormatContext *oc;
3262 if (nb_output_files <= 0) {
3263 fprintf(stderr, "At least one output file must be specified\n");
3266 oc = output_files[nb_output_files - 1];
3267 new_audio_stream(oc);
3270 static void opt_new_video_stream(void)
3272 AVFormatContext *oc;
3273 if (nb_output_files <= 0) {
3274 fprintf(stderr, "At least one output file must be specified\n");
3277 oc = output_files[nb_output_files - 1];
3278 new_video_stream(oc);
3281 static void opt_output_file(const char *filename)
3283 AVFormatContext *oc;
3284 int use_video, use_audio, input_has_video, input_has_audio, i;
3285 AVFormatParameters params, *ap = ¶ms;
3287 if (!strcmp(filename, "-"))
3290 oc = av_alloc_format_context();
3292 if (!file_oformat) {
3293 file_oformat = guess_format(NULL, filename, NULL);
3294 if (!file_oformat) {
3295 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3301 oc->oformat = file_oformat;
3302 pstrcpy(oc->filename, sizeof(oc->filename), filename);
3304 if (!strcmp(file_oformat->name, "ffm") &&
3305 strstart(filename, "http:", NULL)) {
3306 /* special case for files sent to ffserver: we get the stream
3307 parameters from ffserver */
3308 if (read_ffserver_streams(oc, filename) < 0) {
3309 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3313 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3314 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3316 /* disable if no corresponding type found and at least one
3318 if (nb_input_files > 0) {
3319 check_audio_video_inputs(&input_has_video, &input_has_audio);
3320 if (!input_has_video)
3322 if (!input_has_audio)
3326 /* manual disable */
3327 if (audio_disable) {
3330 if (video_disable) {
3335 new_video_stream(oc);
3339 new_audio_stream(oc);
3342 if (!oc->nb_streams) {
3343 fprintf(stderr, "No audio or video streams available\n");
3347 oc->timestamp = rec_timestamp;
3350 pstrcpy(oc->title, sizeof(oc->title), str_title);
3352 pstrcpy(oc->author, sizeof(oc->author), str_author);
3354 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3356 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3358 pstrcpy(oc->album, sizeof(oc->album), str_album);
3361 output_files[nb_output_files++] = oc;
3363 /* check filename in case of an image number is expected */
3364 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3365 if (!av_filename_number_test(oc->filename)) {
3366 print_error(oc->filename, AVERROR_NUMEXPECTED);
3371 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3372 /* test if it already exists to avoid loosing precious files */
3373 if (!file_overwrite &&
3374 (strchr(filename, ':') == NULL ||
3375 strstart(filename, "file:", NULL))) {
3376 if (url_exist(filename)) {
3379 if ( !using_stdin ) {
3380 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3383 if (toupper(c) != 'Y') {
3384 fprintf(stderr, "Not overwriting - exiting\n");
3389 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3396 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3397 fprintf(stderr, "Could not open '%s'\n", filename);
3402 memset(ap, 0, sizeof(*ap));
3403 ap->image_format = image_format;
3404 if (av_set_parameters(oc, ap) < 0) {
3405 fprintf(stderr, "%s: Invalid encoding parameters\n",
3410 oc->packet_size= mux_packet_size;
3411 oc->mux_rate= mux_rate;
3412 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3413 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3414 oc->loop_output = loop_output;
3416 for(i=0; i<opt_name_count; i++){
3418 double d = av_get_double(avformat_opts, opt_names[i], &opt);
3419 if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3420 av_set_double(oc, opt_names[i], d);
3423 /* reset some options */
3424 file_oformat = NULL;
3425 file_iformat = NULL;
3426 image_format = NULL;
3429 /* prepare dummy protocols for grab */
3430 static void prepare_grab(void)
3432 int has_video, has_audio, i, j;
3433 AVFormatContext *oc;
3434 AVFormatContext *ic;
3435 AVFormatParameters vp1, *vp = &vp1;
3436 AVFormatParameters ap1, *ap = &ap1;
3438 /* see if audio/video inputs are needed */
3441 memset(ap, 0, sizeof(*ap));
3442 memset(vp, 0, sizeof(*vp));
3443 vp->time_base.num= 1;
3444 for(j=0;j<nb_output_files;j++) {
3445 oc = output_files[j];
3446 for(i=0;i<oc->nb_streams;i++) {
3447 AVCodecContext *enc = oc->streams[i]->codec;
3448 switch(enc->codec_type) {
3449 case CODEC_TYPE_AUDIO:
3450 if (enc->sample_rate > ap->sample_rate)
3451 ap->sample_rate = enc->sample_rate;
3452 if (enc->channels > ap->channels)
3453 ap->channels = enc->channels;
3456 case CODEC_TYPE_VIDEO:
3457 if (enc->width > vp->width)
3458 vp->width = enc->width;
3459 if (enc->height > vp->height)
3460 vp->height = enc->height;
3462 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3463 vp->time_base = enc->time_base;
3464 vp->width += frame_leftBand + frame_rightBand;
3465 vp->width -= (frame_padleft + frame_padright);
3466 vp->height += frame_topBand + frame_bottomBand;
3467 vp->height -= (frame_padtop + frame_padbottom);
3477 if (has_video == 0 && has_audio == 0) {
3478 fprintf(stderr, "Output file must have at least one audio or video stream\n");
3483 AVInputFormat *fmt1;
3484 fmt1 = av_find_input_format(video_grab_format);
3485 vp->device = video_device;
3486 vp->channel = video_channel;
3487 vp->standard = video_standard;
3488 vp->pix_fmt = frame_pix_fmt;
3489 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3490 fprintf(stderr, "Could not find video grab device\n");
3493 /* If not enough info to get the stream parameters, we decode the
3494 first frames to get it. */
3495 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3496 fprintf(stderr, "Could not find video grab parameters\n");
3499 /* by now video grab has one stream */
3500 ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3501 ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3502 input_files[nb_input_files] = ic;
3505 dump_format(ic, nb_input_files, "", 0);
3509 if (has_audio && audio_grab_format) {
3510 AVInputFormat *fmt1;
3511 fmt1 = av_find_input_format(audio_grab_format);
3512 ap->device = audio_device;
3513 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3514 fprintf(stderr, "Could not find audio grab device\n");
3517 input_files[nb_input_files] = ic;
3520 dump_format(ic, nb_input_files, "", 0);
3526 /* same option as mencoder */
3527 static void opt_pass(const char *pass_str)
3530 pass = atoi(pass_str);
3531 if (pass != 1 && pass != 2) {
3532 fprintf(stderr, "pass number can be only 1 or 2\n");
3538 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3539 static int64_t getutime(void)
3541 return av_gettime();
3544 static int64_t getutime(void)
3546 struct rusage rusage;
3548 getrusage(RUSAGE_SELF, &rusage);
3549 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3553 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3554 extern int ffm_nopts;
3557 static void show_formats(void)
3559 AVInputFormat *ifmt;
3560 AVOutputFormat *ofmt;
3561 AVImageFormat *image_fmt;
3564 const char **pp, *last_name;
3566 printf("File formats:\n");
3571 const char *name=NULL;
3572 const char *long_name=NULL;
3574 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3575 if((name == NULL || strcmp(ofmt->name, name)<0) &&
3576 strcmp(ofmt->name, last_name)>0){
3578 long_name= ofmt->long_name;
3582 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3583 if((name == NULL || strcmp(ifmt->name, name)<0) &&
3584 strcmp(ifmt->name, last_name)>0){
3586 long_name= ifmt->long_name;
3589 if(name && strcmp(ifmt->name, name)==0)
3601 long_name ? long_name:" ");
3605 printf("Image formats (filename extensions, if any, follow):\n");
3606 for(image_fmt = first_image_format; image_fmt != NULL;
3607 image_fmt = image_fmt->next) {
3610 image_fmt->img_read ? "D":" ",
3611 image_fmt->img_write ? "E":" ",
3613 image_fmt->extensions ? image_fmt->extensions:" ");
3617 printf("Codecs:\n");
3623 const char *type_str;
3626 for(p = first_avcodec; p != NULL; p = p->next) {
3627 if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3628 strcmp(p->name, last_name)>0){
3630 decode= encode= cap=0;
3632 if(p2 && strcmp(p->name, p2->name)==0){
3633 if(p->decode) decode=1;
3634 if(p->encode) encode=1;
3635 cap |= p->capabilities;
3640 last_name= p2->name;
3643 case CODEC_TYPE_VIDEO:
3646 case CODEC_TYPE_AUDIO:
3649 case CODEC_TYPE_SUBTITLE:
3658 decode ? "D": (/*p2->decoder ? "d":*/" "),
3661 cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3662 cap & CODEC_CAP_DR1 ? "D":" ",
3663 cap & CODEC_CAP_TRUNCATED ? "T":" ",
3665 /* if(p2->decoder && decode==0)
3666 printf(" use %s for decoding", p2->decoder->name);*/
3671 printf("Supported file protocols:\n");
3672 for(up = first_protocol; up != NULL; up = up->next)
3673 printf(" %s:", up->name);
3676 printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3677 printf("Motion estimation methods:\n");
3681 if ((pp - motion_str + 1) == ME_ZERO)
3682 printf("(fastest)");
3683 else if ((pp - motion_str + 1) == ME_FULL)
3684 printf("(slowest)");
3685 else if ((pp - motion_str + 1) == ME_EPZS)
3686 printf("(default)");
3691 "Note, the names of encoders and decoders dont always match, so there are\n"
3692 "several cases where the above table shows encoder only or decoder only entries\n"
3693 "even though both encoding and decoding are supported for example, the h263\n"
3694 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3699 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3702 const char *p = str;
3709 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3716 static void opt_inter_matrix(const char *arg)
3718 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3719 parse_matrix_coeffs(inter_matrix, arg);
3722 static void opt_intra_matrix(const char *arg)
3724 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3725 parse_matrix_coeffs(intra_matrix, arg);
3728 static void opt_target(const char *arg)
3731 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3733 if(!strncmp(arg, "pal-", 4)) {
3736 } else if(!strncmp(arg, "ntsc-", 5)) {
3739 } else if(!strncmp(arg, "film-", 5)) {
3744 /* Calculate FR via float to avoid int overflow */
3745 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3748 } else if((fr == 29970) || (fr == 23976)) {
3751 /* Try to determine PAL/NTSC by peeking in the input files */
3752 if(nb_input_files) {
3754 for(j = 0; j < nb_input_files; j++) {
3755 for(i = 0; i < input_files[j]->nb_streams; i++) {
3756 AVCodecContext *c = input_files[j]->streams[i]->codec;
3757 if(c->codec_type != CODEC_TYPE_VIDEO)
3759 fr = c->time_base.den * 1000 / c->time_base.num;
3763 } else if((fr == 29970) || (fr == 23976)) {
3773 if(verbose && norm >= 0)
3774 fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3778 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3779 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3780 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3784 if(!strcmp(arg, "vcd")) {
3786 opt_video_codec("mpeg1video");
3787 opt_audio_codec("mp2");
3790 opt_frame_size(norm ? "352x240" : "352x288");
3791 opt_frame_rate(frame_rates[norm]);
3792 opt_default("gop", norm ? "18" : "15");
3794 opt_default("b", "1150000");
3795 opt_default("maxrate", "1150000");
3796 opt_default("minrate", "1150000");
3797 video_rc_buffer_size = 40*1024*8;
3799 audio_bit_rate = 224000;
3800 audio_sample_rate = 44100;
3802 mux_packet_size= 2324;
3803 mux_rate= 2352 * 75 * 8;
3805 /* We have to offset the PTS, so that it is consistent with the SCR.
3806 SCR starts at 36000, but the first two packs contain only padding
3807 and the first pack from the other stream, respectively, may also have
3808 been written before.
3809 So the real data starts at SCR 36000+3*1200. */
3810 mux_preload= (36000+3*1200) / 90000.0; //0.44
3811 } else if(!strcmp(arg, "svcd")) {
3813 opt_video_codec("mpeg2video");
3814 opt_audio_codec("mp2");
3817 opt_frame_size(norm ? "480x480" : "480x576");
3818 opt_frame_rate(frame_rates[norm]);
3819 opt_default("gop", norm ? "18" : "15");
3821 opt_default("b", "2040000");
3822 opt_default("maxrate", "2516000");
3823 opt_default("minrate", "0"); //1145000;
3824 video_rc_buffer_size = 224*1024*8;
3825 opt_default("flags", "+SCAN_OFFSET");
3828 audio_bit_rate = 224000;
3829 audio_sample_rate = 44100;
3831 mux_packet_size= 2324;
3833 } else if(!strcmp(arg, "dvd")) {
3835 opt_video_codec("mpeg2video");
3836 opt_audio_codec("ac3");
3839 opt_frame_size(norm ? "720x480" : "720x576");
3840 opt_frame_rate(frame_rates[norm]);
3841 opt_default("gop", norm ? "18" : "15");
3843 opt_default("b", "6000000");
3844 opt_default("maxrate", "9000000");
3845 opt_default("minrate", "0"); //1500000;
3846 video_rc_buffer_size = 224*1024*8;
3848 mux_packet_size= 2048; // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3849 mux_rate = 10080000; // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3851 audio_bit_rate = 448000;
3852 audio_sample_rate = 48000;
3854 } else if(!strncmp(arg, "dv", 2)) {
3858 opt_frame_size(norm ? "720x480" : "720x576");
3859 opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3860 (norm ? "yuv411p" : "yuv420p"));
3861 opt_frame_rate(frame_rates[norm]);
3863 audio_sample_rate = 48000;
3867 fprintf(stderr, "Unknown target: %s\n", arg);
3872 static void opt_video_bsf(const char *arg)
3874 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3875 AVBitStreamFilterContext **bsfp;
3878 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3882 bsfp= &video_bitstream_filters;
3884 bsfp= &(*bsfp)->next;
3889 //FIXME avoid audio - video code duplication
3890 static void opt_audio_bsf(const char *arg)
3892 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3893 AVBitStreamFilterContext **bsfp;
3896 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3900 bsfp= &audio_bitstream_filters;
3902 bsfp= &(*bsfp)->next;
3907 static void show_version(void)
3909 /* TODO: add function interface to avutil and avformat */
3910 fprintf(stderr, "ffmpeg " FFMPEG_VERSION "\n"
3914 LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3918 static int opt_default(const char *opt, const char *arg){
3919 AVOption *o= av_set_string(avctx_opts, opt, arg);
3921 o = av_set_string(avformat_opts, opt, arg);
3925 // 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));
3927 //FIXME we should always use avctx_opts, ... for storing options so there wont be any need to keep track of whats set over this
3928 opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
3929 opt_names[opt_name_count++]= o->name;
3931 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3932 /* disable generate of real time pts in ffm (need to be supressed anyway) */
3933 if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3937 if(avctx_opts->debug)
3938 av_log_set_level(AV_LOG_DEBUG);
3942 const OptionDef options[] = {
3944 { "L", 0, {(void*)show_license}, "show license" },
3945 { "h", 0, {(void*)show_help}, "show help" },
3946 { "version", 0, {(void*)show_version}, "show version" },
3947 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3948 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3949 { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3950 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3951 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3952 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3953 { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3954 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3955 { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3956 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3957 { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3958 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3959 { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3960 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3961 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3962 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3963 { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3964 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3965 "add timings for benchmarking" },
3966 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3967 "dump each input packet" },
3968 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3969 "when dumping packets, also dump the payload" },
3970 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3971 { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3972 { "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)", "" },
3973 { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3974 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3975 { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3976 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3977 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3978 { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3979 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
3980 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3981 { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3984 { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3985 { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3986 { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3987 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3988 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3989 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3990 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3991 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3992 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3993 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3994 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3995 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3996 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3997 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3998 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3999 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
4000 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4001 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4002 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4003 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
4004 { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
4005 { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
4006 { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
4007 { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
4008 { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
4009 { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
4010 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
4011 { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
4012 { "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" },
4013 { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
4014 { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
4015 { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
4016 { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
4017 { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
4018 { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
4019 { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
4020 { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
4021 { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
4022 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4023 { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
4024 { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
4025 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4026 { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
4028 { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold", "" },
4029 { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold", "" },
4030 { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
4031 { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
4032 { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
4033 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
4034 { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
4035 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
4036 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4037 "use same video quality as source (implies VBR)" },
4038 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4039 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
4040 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4041 "deinterlace pictures" },
4042 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4043 { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
4044 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
4045 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4046 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4047 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4048 { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
4049 { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
4050 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4051 { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
4052 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4053 { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
4054 { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
4055 { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
4056 { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
4057 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4060 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
4061 { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4062 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4063 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4064 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4065 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4066 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4067 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4068 { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
4069 { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4071 /* subtitle options */
4072 { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4073 { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
4074 { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4077 { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
4078 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4079 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4080 { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
4082 /* G.2 grab options */
4083 { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
4084 { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
4087 { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
4088 { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
4089 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4090 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4092 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
4093 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
4095 { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4099 static void show_banner(void)
4101 fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
4102 fprintf(stderr, " configuration: " FFMPEG_CONFIGURATION "\n");
4103 fprintf(stderr, " libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
4104 fprintf(stderr, " libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
4105 fprintf(stderr, " libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
4106 fprintf(stderr, " built on " __DATE__ " " __TIME__);
4108 fprintf(stderr, ", gcc: " __VERSION__ "\n");
4110 fprintf(stderr, ", using a non-gcc compiler\n");
4114 static void show_license(void)
4119 "This program is free software; you can redistribute it and/or modify\n"
4120 "it under the terms of the GNU General Public License as published by\n"
4121 "the Free Software Foundation; either version 2 of the License, or\n"
4122 "(at your option) any later version.\n"
4124 "This program is distributed in the hope that it will be useful,\n"
4125 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4126 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
4127 "GNU General Public License for more details.\n"
4129 "You should have received a copy of the GNU General Public License\n"
4130 "along with this program; if not, write to the Free Software\n"
4131 "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
4135 "This library is free software; you can redistribute it and/or\n"
4136 "modify it under the terms of the GNU Lesser General Public\n"
4137 "License as published by the Free Software Foundation; either\n"
4138 "version 2 of the License, or (at your option) any later version.\n"
4140 "This library is distributed in the hope that it will be useful,\n"
4141 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4142 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
4143 "Lesser General Public License for more details.\n"
4145 "You should have received a copy of the GNU Lesser General Public\n"
4146 "License along with this library; if not, write to the Free Software\n"
4147 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
4153 static void show_help(void)
4156 printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4157 "Hyper fast Audio and Video encoder\n");
4159 show_help_options(options, "Main options:\n",
4160 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4161 show_help_options(options, "\nVideo options:\n",
4162 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4164 show_help_options(options, "\nAdvanced Video options:\n",
4165 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4166 OPT_VIDEO | OPT_EXPERT);
4167 show_help_options(options, "\nAudio options:\n",
4168 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4170 show_help_options(options, "\nAdvanced Audio options:\n",
4171 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4172 OPT_AUDIO | OPT_EXPERT);
4173 show_help_options(options, "\nSubtitle options:\n",
4174 OPT_SUBTITLE | OPT_GRAB,
4176 show_help_options(options, "\nAudio/Video grab options:\n",
4179 show_help_options(options, "\nAdvanced options:\n",
4180 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4182 av_opt_show(avctx_opts, NULL);
4183 av_opt_show(avformat_opts, NULL);
4188 void parse_arg_file(const char *filename)
4190 opt_output_file(filename);
4193 int main(int argc, char **argv)
4200 avctx_opts= avcodec_alloc_context();
4201 avformat_opts = av_alloc_format_context();
4209 parse_options(argc, argv, options);
4211 /* file converter / grab */
4212 if (nb_output_files <= 0) {
4213 fprintf(stderr, "Must supply at least one output file\n");
4217 if (nb_input_files == 0) {
4223 av_encode(output_files, nb_output_files, input_files, nb_input_files,
4224 stream_maps, nb_stream_maps);
4225 ti = getutime() - ti;
4227 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4231 for(i=0;i<nb_output_files;i++) {
4232 /* maybe av_close_output_file ??? */
4233 AVFormatContext *s = output_files[i];
4235 if (!(s->oformat->flags & AVFMT_NOFILE))
4237 for(j=0;j<s->nb_streams;j++)
4238 av_free(s->streams[j]);
4241 for(i=0;i<nb_input_files;i++)
4242 av_close_input_file(input_files[i]);
4247 av_free(intra_matrix);
4249 av_free(inter_matrix);
4251 #ifdef POWERPC_PERFORMANCE_REPORT
4252 extern void powerpc_display_perf_report(void);
4253 powerpc_display_perf_report();
4254 #endif /* POWERPC_PERFORMANCE_REPORT */
4257 if (received_sigterm) {
4259 "Received signal %d: terminating.\n",
4260 (int) received_sigterm);
4264 exit(0); /* not all OS-es handle main() return value */