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_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
137 static int me_method = ME_EPZS;
138 static int video_disable = 0;
139 static int video_discard = 0;
140 static int video_codec_id = CODEC_ID_NONE;
141 static int video_codec_tag = 0;
142 static int same_quality = 0;
143 static int b_frames = 0;
144 static int do_deinterlace = 0;
145 static int workaround_bugs = FF_BUG_AUTODETECT;
146 static int packet_size = 0;
147 static int error_rate = 0;
148 static int strict = 0;
149 static int top_field_first = -1;
150 static int sc_threshold = 0;
151 static int me_threshold = 0;
152 static int mb_threshold = 0;
153 static int intra_dc_precision = 8;
154 static int me_penalty_compensation= 256;
155 static int frame_skip_threshold= 0;
156 static int frame_skip_factor= 0;
157 static int frame_skip_exp= 0;
158 static int loop_input = 0;
159 static int loop_output = AVFMT_NOOUTPUTLOOP;
160 static int qp_hist = 0;
162 static int intra_only = 0;
163 static int audio_sample_rate = 44100;
164 static int audio_bit_rate = 64000;
165 #define QSCALE_NONE -99999
166 static float audio_qscale = QSCALE_NONE;
167 static int audio_disable = 0;
168 static int audio_channels = 1;
169 static int audio_codec_id = CODEC_ID_NONE;
170 static int audio_codec_tag = 0;
171 static char *audio_language = NULL;
173 static int subtitle_codec_id = CODEC_ID_NONE;
174 static char *subtitle_language = NULL;
176 static int mux_rate= 0;
177 static int mux_packet_size= 0;
178 static float mux_preload= 0.5;
179 static float mux_max_delay= 0.7;
181 static int64_t recording_time = 0;
182 static int64_t start_time = 0;
183 static int64_t rec_timestamp = 0;
184 static int64_t input_ts_offset = 0;
185 static int file_overwrite = 0;
186 static char *str_title = NULL;
187 static char *str_author = NULL;
188 static char *str_copyright = NULL;
189 static char *str_comment = NULL;
190 static char *str_album = NULL;
191 static int do_benchmark = 0;
192 static int do_hex_dump = 0;
193 static int do_pkt_dump = 0;
194 static int do_psnr = 0;
195 static int do_vstats = 0;
196 static int do_pass = 0;
197 static char *pass_logfilename = NULL;
198 static int audio_stream_copy = 0;
199 static int video_stream_copy = 0;
200 static int subtitle_stream_copy = 0;
201 static int video_sync_method= 1;
202 static int audio_sync_method= 0;
203 static int copy_ts= 0;
204 static int opt_shortest = 0; //
205 static int video_global_header = 0;
207 static int rate_emu = 0;
210 static const char *video_grab_format = "bktr";
212 #ifdef CONFIG_VIDEO4LINUX2
213 static const char *video_grab_format = "video4linux2";
215 static const char *video_grab_format = "video4linux";
218 static char *video_device = NULL;
219 static char *grab_device = NULL;
220 static int video_channel = 0;
221 static char *video_standard = "ntsc";
223 static const char *audio_grab_format = "audio_device";
224 static char *audio_device = NULL;
225 static int audio_volume = 256;
227 static int using_stdin = 0;
228 static int using_vhook = 0;
229 static int verbose = 1;
230 static int thread_count= 1;
231 static int q_pressed = 0;
232 static int me_range = 0;
233 static int64_t video_size = 0;
234 static int64_t audio_size = 0;
235 static int64_t extra_size = 0;
236 static int nb_frames_dup = 0;
237 static int nb_frames_drop = 0;
238 static int input_sync;
239 static int limit_filesize = 0; //
241 static int pgmyuv_compatibility_hack=0;
242 static int dts_delta_threshold = 10;
244 static int sws_flags = SWS_BICUBIC;
246 const char **opt_names=NULL;
247 int opt_name_count=0;
248 AVCodecContext *avctx_opts;
249 AVFormatContext *avformat_opts;
251 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
252 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
253 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
255 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
257 struct AVInputStream;
259 typedef struct AVOutputStream {
260 int file_index; /* file index */
261 int index; /* stream index in the output file */
262 int source_index; /* AVInputStream index */
263 AVStream *st; /* stream in the output file */
264 int encoding_needed; /* true if encoding needed for this stream */
266 /* input pts and corresponding output pts
268 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
269 struct AVInputStream *sync_ist; /* input stream to sync against */
270 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
273 AVFrame pict_tmp; /* temporary image for resampling */
274 struct SwsContext *img_resample_ctx; /* for image resampling */
278 int topBand; /* cropping area sizes */
282 int padtop; /* padding area sizes */
289 ReSampleContext *resample; /* for audio resampling */
290 FifoBuffer fifo; /* for compression: one audio fifo per codec */
294 typedef struct AVInputStream {
298 int discard; /* true if stream data should be discarded */
299 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
300 int64_t sample_index; /* current sample */
302 int64_t start; /* time when read started */
303 unsigned long frame; /* current frame */
304 int64_t next_pts; /* synthetic pts for cases where pkt.pts
306 int64_t pts; /* current pts */
307 int is_start; /* is 1 at the start and after a discontinuity */
310 typedef struct AVInputFile {
311 int eof_reached; /* true if eof reached */
312 int ist_index; /* index of first stream in ist_table */
313 int buffer_size; /* current total buffer size */
314 int buffer_size_max; /* buffer size at which we consider we can stop
316 int nb_streams; /* nb streams we are aware of */
321 /* init terminal so that we can grab keys */
322 static struct termios oldtty;
324 static void term_exit(void)
326 tcsetattr (0, TCSANOW, &oldtty);
329 static volatile sig_atomic_t received_sigterm = 0;
332 sigterm_handler(int sig)
334 received_sigterm = sig;
338 static void term_init(void)
345 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
346 |INLCR|IGNCR|ICRNL|IXON);
347 tty.c_oflag |= OPOST;
348 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
349 tty.c_cflag &= ~(CSIZE|PARENB);
354 tcsetattr (0, TCSANOW, &tty);
356 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
357 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
358 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
360 register a function to be called at normal program termination
363 #ifdef CONFIG_BEOS_NETSERVER
364 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
368 /* read a key without blocking */
369 static int read_key(void)
373 #ifndef CONFIG_BEOS_NETSERVER
381 n = select(1, &rfds, NULL, NULL, &tv);
393 static int decode_interrupt_cb(void)
395 return q_pressed || (q_pressed = read_key() == 'q');
400 static volatile int received_sigterm = 0;
402 /* no interactive support */
403 static void term_exit(void)
407 static void term_init(void)
411 static int read_key(void)
418 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
423 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
426 /* copy stream format */
427 s->nb_streams = ic->nb_streams;
428 for(i=0;i<ic->nb_streams;i++) {
431 // FIXME: a more elegant solution is needed
432 st = av_mallocz(sizeof(AVStream));
433 memcpy(st, ic->streams[i], sizeof(AVStream));
434 st->codec = avcodec_alloc_context();
435 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
439 av_close_input_file(ic);
444 get_sync_ipts(const AVOutputStream *ost)
446 const AVInputStream *ist = ost->sync_ist;
447 return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
450 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
452 AVPacket new_pkt= *pkt;
453 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
454 &new_pkt.data, &new_pkt.size,
455 pkt->data, pkt->size,
456 pkt->flags & PKT_FLAG_KEY);
459 new_pkt.destruct= av_destruct_packet;
466 av_interleaved_write_frame(s, pkt);
469 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
471 static void do_audio_out(AVFormatContext *s,
474 unsigned char *buf, int size)
477 static uint8_t *audio_buf = NULL;
478 static uint8_t *audio_out = NULL;
479 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
481 int size_out, frame_bytes, ret;
482 AVCodecContext *enc= ost->st->codec;
484 /* SC: dynamic allocation of buffers */
486 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
488 audio_out = av_malloc(audio_out_size);
489 if (!audio_buf || !audio_out)
490 return; /* Should signal an error ! */
492 if(audio_sync_method){
493 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
494 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
495 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
496 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
498 //FIXME resample delay
499 if(fabs(delta) > 50){
502 byte_delta= FFMAX(byte_delta, -size);
506 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
511 static uint8_t *input_tmp= NULL;
512 input_tmp= av_realloc(input_tmp, byte_delta + size);
514 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
517 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
519 memset(input_tmp, 0, byte_delta);
520 memcpy(input_tmp + byte_delta, buf, size);
524 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
526 }else if(audio_sync_method>1){
527 int comp= clip(delta, -audio_sync_method, audio_sync_method);
528 assert(ost->audio_resample);
530 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
531 // 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));
532 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
536 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
537 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
539 if (ost->audio_resample) {
541 size_out = audio_resample(ost->resample,
542 (short *)buftmp, (short *)buf,
543 size / (ist->st->codec->channels * 2));
544 size_out = size_out * enc->channels * 2;
550 /* now encode as many frames as possible */
551 if (enc->frame_size > 1) {
552 /* output resampled raw samples */
553 fifo_write(&ost->fifo, buftmp, size_out,
556 frame_bytes = enc->frame_size * 2 * enc->channels;
558 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
559 &ost->fifo.rptr) == 0) {
561 av_init_packet(&pkt);
563 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
566 pkt.stream_index= ost->index;
569 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
570 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
571 pkt.flags |= PKT_FLAG_KEY;
572 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
574 ost->sync_opts += enc->frame_size;
578 av_init_packet(&pkt);
580 ost->sync_opts += size_out / (2 * enc->channels);
582 /* output a pcm frame */
583 /* XXX: change encoding codec API to avoid this ? */
584 switch(enc->codec->id) {
585 case CODEC_ID_PCM_S32LE:
586 case CODEC_ID_PCM_S32BE:
587 case CODEC_ID_PCM_U32LE:
588 case CODEC_ID_PCM_U32BE:
589 size_out = size_out << 1;
591 case CODEC_ID_PCM_S24LE:
592 case CODEC_ID_PCM_S24BE:
593 case CODEC_ID_PCM_U24LE:
594 case CODEC_ID_PCM_U24BE:
595 case CODEC_ID_PCM_S24DAUD:
596 size_out = size_out / 2 * 3;
598 case CODEC_ID_PCM_S16LE:
599 case CODEC_ID_PCM_S16BE:
600 case CODEC_ID_PCM_U16LE:
601 case CODEC_ID_PCM_U16BE:
604 size_out = size_out >> 1;
607 ret = avcodec_encode_audio(enc, audio_out, size_out,
610 pkt.stream_index= ost->index;
613 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
614 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
615 pkt.flags |= PKT_FLAG_KEY;
616 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
620 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
624 AVPicture picture_tmp;
627 dec = ist->st->codec;
629 /* deinterlace : must be done before any resize */
630 if (do_deinterlace || using_vhook) {
633 /* create temporary picture */
634 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
635 buf = av_malloc(size);
639 picture2 = &picture_tmp;
640 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
643 if(avpicture_deinterlace(picture2, picture,
644 dec->pix_fmt, dec->width, dec->height) < 0) {
645 /* if error, do not deinterlace */
651 img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
657 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
659 if (picture != picture2)
660 *picture = *picture2;
664 /* we begin to correct av delay at this threshold */
665 #define AV_DELAY_MAX 0.100
667 static void do_subtitle_out(AVFormatContext *s,
673 static uint8_t *subtitle_out = NULL;
674 int subtitle_out_max_size = 65536;
675 int subtitle_out_size, nb, i;
679 if (pts == AV_NOPTS_VALUE) {
680 fprintf(stderr, "Subtitle packets must have a pts\n");
684 enc = ost->st->codec;
687 subtitle_out = av_malloc(subtitle_out_max_size);
690 /* Note: DVB subtitle need one packet to draw them and one other
691 packet to clear them */
692 /* XXX: signal it in the codec context ? */
693 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
698 for(i = 0; i < nb; i++) {
699 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
700 subtitle_out_max_size, sub);
702 av_init_packet(&pkt);
703 pkt.stream_index = ost->index;
704 pkt.data = subtitle_out;
705 pkt.size = subtitle_out_size;
706 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);
707 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
708 /* XXX: the pts correction is handled here. Maybe handling
709 it in the codec would be better */
711 pkt.pts += 90 * sub->start_display_time;
713 pkt.pts += 90 * sub->end_display_time;
715 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
719 static int bit_buffer_size= 1024*256;
720 static uint8_t *bit_buffer= NULL;
722 static void do_video_out(AVFormatContext *s,
728 int nb_frames, i, ret;
729 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
730 AVFrame picture_crop_temp, picture_pad_temp;
731 uint8_t *buf = NULL, *buf1 = NULL;
732 AVCodecContext *enc, *dec;
734 avcodec_get_frame_defaults(&picture_crop_temp);
735 avcodec_get_frame_defaults(&picture_pad_temp);
737 enc = ost->st->codec;
738 dec = ist->st->codec;
740 /* by default, we output a single frame */
745 if(video_sync_method){
747 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
748 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
751 else if (vdelta > 1.1)
752 nb_frames = lrintf(vdelta);
753 //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);
757 fprintf(stderr, "*** drop!\n");
758 }else if (nb_frames > 1) {
759 nb_frames_dup += nb_frames;
761 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
764 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
766 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
770 if (ost->video_crop) {
771 if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
772 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
775 formatted_picture = &picture_crop_temp;
777 formatted_picture = in_picture;
780 final_picture = formatted_picture;
781 padding_src = formatted_picture;
782 resampling_dst = &ost->pict_tmp;
783 if (ost->video_pad) {
784 final_picture = &ost->pict_tmp;
785 if (ost->video_resample) {
786 if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
787 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
790 resampling_dst = &picture_pad_temp;
794 if (ost->video_resample) {
796 final_picture = &ost->pict_tmp;
797 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
798 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
801 if (ost->video_pad) {
802 img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
803 enc->height, enc->width, enc->pix_fmt,
804 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
807 /* duplicates frame if needed */
808 for(i=0;i<nb_frames;i++) {
810 av_init_packet(&pkt);
811 pkt.stream_index= ost->index;
813 if (s->oformat->flags & AVFMT_RAWPICTURE) {
814 /* raw pictures are written as AVPicture structure to
815 avoid any copies. We support temorarily the older
817 AVFrame* old_frame = enc->coded_frame;
818 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
819 pkt.data= (uint8_t *)final_picture;
820 pkt.size= sizeof(AVPicture);
821 if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
822 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
823 if(dec->coded_frame && dec->coded_frame->key_frame)
824 pkt.flags |= PKT_FLAG_KEY;
826 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
827 enc->coded_frame = old_frame;
831 big_picture= *final_picture;
832 /* better than nothing: use input picture interlaced
834 big_picture.interlaced_frame = in_picture->interlaced_frame;
835 if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
836 if(top_field_first == -1)
837 big_picture.top_field_first = in_picture->top_field_first;
839 big_picture.top_field_first = top_field_first;
842 /* handles sameq here. This is not correct because it may
843 not be a global option */
845 big_picture.quality = ist->st->quality;
847 big_picture.quality = ost->st->quality;
849 big_picture.pict_type = 0;
850 // big_picture.pts = AV_NOPTS_VALUE;
851 big_picture.pts= ost->sync_opts;
852 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
853 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
854 ret = avcodec_encode_video(enc,
855 bit_buffer, bit_buffer_size,
857 //enc->frame_number = enc->real_pict_num;
859 pkt.data= bit_buffer;
861 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
862 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
863 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
864 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
865 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
867 if(enc->coded_frame && enc->coded_frame->key_frame)
868 pkt.flags |= PKT_FLAG_KEY;
869 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
871 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
872 // enc->frame_number-1, enc->real_pict_num, ret,
874 /* if two pass, output log */
875 if (ost->logfile && enc->stats_out) {
876 fprintf(ost->logfile, "%s", enc->stats_out);
888 static double psnr(double d){
889 if(d==0) return INFINITY;
890 return -10.0*log(d)/log(10.0);
893 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
896 static FILE *fvstats=NULL;
903 double ti1, bitrate, avg_bitrate;
907 today = localtime(&today2);
908 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
911 fvstats = fopen(filename,"w");
919 enc = ost->st->codec;
920 if (enc->codec_type == CODEC_TYPE_VIDEO) {
921 frame_number = ost->frame_number;
922 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
923 if (enc->flags&CODEC_FLAG_PSNR)
924 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
926 fprintf(fvstats,"f_size= %6d ", frame_size);
927 /* compute pts value */
928 ti1 = ost->sync_opts * av_q2d(enc->time_base);
932 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
933 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
934 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
935 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
936 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
940 static void print_report(AVFormatContext **output_files,
941 AVOutputStream **ost_table, int nb_ostreams,
946 AVFormatContext *oc, *os;
949 int frame_number, vid, i;
950 double bitrate, ti1, pts;
951 static int64_t last_time = -1;
952 static int qp_histogram[52];
954 if (!is_last_report) {
956 /* display the report every 0.5 seconds */
957 cur_time = av_gettime();
958 if (last_time == -1) {
959 last_time = cur_time;
962 if ((cur_time - last_time) < 500000)
964 last_time = cur_time;
968 oc = output_files[0];
970 total_size = url_ftell(&oc->pb);
975 for(i=0;i<nb_ostreams;i++) {
977 os = output_files[ost->file_index];
978 enc = ost->st->codec;
979 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
980 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
981 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
983 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
984 frame_number = ost->frame_number;
985 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
986 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
988 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
989 if(qp_hist && enc->coded_frame){
991 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
992 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
995 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
997 if (enc->flags&CODEC_FLAG_PSNR){
999 double error, error_sum=0;
1000 double scale, scale_sum=0;
1001 char type[3]= {'Y','U','V'};
1002 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1005 error= enc->error[j];
1006 scale= enc->width*enc->height*255.0*255.0*frame_number;
1008 error= enc->coded_frame->error[j];
1009 scale= enc->width*enc->height*255.0*255.0;
1014 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1016 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1020 /* compute min output value */
1021 pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1022 if ((pts < ti1) && (pts > 0))
1028 if (verbose || is_last_report) {
1029 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1031 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1032 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1033 (double)total_size / 1024, ti1, bitrate);
1036 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1037 nb_frames_dup, nb_frames_drop);
1040 fprintf(stderr, "%s \r", buf);
1045 if (is_last_report && verbose >= 0){
1046 int64_t raw= audio_size + video_size + extra_size;
1047 fprintf(stderr, "\n");
1048 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1052 100.0*(total_size - raw)/raw
1057 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1058 static int output_packet(AVInputStream *ist, int ist_index,
1059 AVOutputStream **ost_table, int nb_ostreams,
1060 const AVPacket *pkt)
1062 AVFormatContext *os;
1063 AVOutputStream *ost;
1067 int data_size, got_picture;
1069 void *buffer_to_free;
1070 static unsigned int samples_size= 0;
1071 static short *samples= NULL;
1072 AVSubtitle subtitle, *subtitle_to_free;
1076 ist->pts= ist->next_pts; // needed for last packet if vsync=0
1077 } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1078 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1080 // assert(ist->pts == ist->next_pts);
1094 /* decode the packet if needed */
1095 data_buf = NULL; /* fail safe */
1097 subtitle_to_free = NULL;
1098 if (ist->decoding_needed) {
1099 switch(ist->st->codec->codec_type) {
1100 case CODEC_TYPE_AUDIO:{
1102 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1103 /* XXX: could avoid copy if PCM 16 bits with same
1104 endianness as CPU */
1105 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1111 /* Some bug in mpeg audio decoder gives */
1112 /* data_size < 0, it seems they are overflows */
1113 if (data_size <= 0) {
1114 /* no audio frame */
1117 data_buf = (uint8_t *)samples;
1118 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1119 (ist->st->codec->sample_rate * ist->st->codec->channels);
1121 case CODEC_TYPE_VIDEO:
1122 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1123 /* XXX: allocate picture correctly */
1124 avcodec_get_frame_defaults(&picture);
1126 ret = avcodec_decode_video(ist->st->codec,
1127 &picture, &got_picture, ptr, len);
1128 ist->st->quality= picture.quality;
1132 /* no picture yet */
1133 goto discard_packet;
1135 if (ist->st->codec->time_base.num != 0) {
1136 ist->next_pts += ((int64_t)AV_TIME_BASE *
1137 ist->st->codec->time_base.num) /
1138 ist->st->codec->time_base.den;
1142 case CODEC_TYPE_SUBTITLE:
1143 ret = avcodec_decode_subtitle(ist->st->codec,
1144 &subtitle, &got_subtitle, ptr, len);
1147 if (!got_subtitle) {
1148 goto discard_packet;
1150 subtitle_to_free = &subtitle;
1157 switch(ist->st->codec->codec_type) {
1158 case CODEC_TYPE_AUDIO:
1159 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1160 (ist->st->codec->sample_rate * ist->st->codec->channels);
1162 case CODEC_TYPE_VIDEO:
1163 if (ist->st->codec->time_base.num != 0) {
1164 ist->next_pts += ((int64_t)AV_TIME_BASE *
1165 ist->st->codec->time_base.num) /
1166 ist->st->codec->time_base.den;
1176 buffer_to_free = NULL;
1177 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1178 pre_process_video_frame(ist, (AVPicture *)&picture,
1182 // preprocess audio (volume)
1183 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1184 if (audio_volume != 256) {
1187 for(i=0;i<(data_size / sizeof(short));i++) {
1188 int v = ((*volp) * audio_volume + 128) >> 8;
1189 if (v < -32768) v = -32768;
1190 if (v > 32767) v = 32767;
1196 /* frame rate emulation */
1197 if (ist->st->codec->rate_emu) {
1198 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1199 int64_t now = av_gettime() - ist->start;
1207 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1208 is the one of the next displayed one */
1209 /* XXX: add mpeg4 too ? */
1210 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1211 if (ist->st->codec->pict_type != B_TYPE) {
1213 tmp = ist->last_ip_pts;
1214 ist->last_ip_pts = ist->frac_pts.val;
1215 ist->frac_pts.val = tmp;
1219 /* if output time reached then transcode raw format,
1220 encode packets and output them */
1221 if (start_time == 0 || ist->pts >= start_time)
1222 for(i=0;i<nb_ostreams;i++) {
1226 if (ost->source_index == ist_index) {
1227 os = output_files[ost->file_index];
1230 printf("%d: got pts=%0.3f %0.3f\n", i,
1231 (double)pkt->pts / AV_TIME_BASE,
1232 ((double)ist->pts / AV_TIME_BASE) -
1233 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1235 /* set the input output pts pairs */
1236 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1238 if (ost->encoding_needed) {
1239 switch(ost->st->codec->codec_type) {
1240 case CODEC_TYPE_AUDIO:
1241 do_audio_out(os, ost, ist, data_buf, data_size);
1243 case CODEC_TYPE_VIDEO:
1244 do_video_out(os, ost, ist, &picture, &frame_size);
1245 video_size += frame_size;
1246 if (do_vstats && frame_size)
1247 do_video_stats(os, ost, frame_size);
1249 case CODEC_TYPE_SUBTITLE:
1250 do_subtitle_out(os, ost, ist, &subtitle,
1257 AVFrame avframe; //FIXME/XXX remove this
1259 av_init_packet(&opkt);
1261 /* no reencoding needed : output the packet directly */
1262 /* force the input stream PTS */
1264 avcodec_get_frame_defaults(&avframe);
1265 ost->st->codec->coded_frame= &avframe;
1266 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1268 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1269 audio_size += data_size;
1270 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1271 video_size += data_size;
1275 opkt.stream_index= ost->index;
1276 if(pkt->pts != AV_NOPTS_VALUE)
1277 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);
1279 opkt.pts= AV_NOPTS_VALUE;
1283 if (pkt->dts == AV_NOPTS_VALUE)
1284 dts = ist->next_pts;
1286 dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1287 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1289 opkt.flags= pkt->flags;
1291 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1292 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1293 opkt.destruct= av_destruct_packet;
1295 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1296 ost->st->codec->frame_number++;
1297 ost->frame_number++;
1298 av_free_packet(&opkt);
1302 av_free(buffer_to_free);
1303 /* XXX: allocate the subtitles in the codec ? */
1304 if (subtitle_to_free) {
1305 if (subtitle_to_free->rects != NULL) {
1306 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1307 av_free(subtitle_to_free->rects[i].bitmap);
1308 av_free(subtitle_to_free->rects[i].rgba_palette);
1310 av_freep(&subtitle_to_free->rects);
1312 subtitle_to_free->num_rects = 0;
1313 subtitle_to_free = NULL;
1320 for(i=0;i<nb_ostreams;i++) {
1322 if (ost->source_index == ist_index) {
1323 AVCodecContext *enc= ost->st->codec;
1324 os = output_files[ost->file_index];
1326 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1328 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1331 if (ost->encoding_needed) {
1335 av_init_packet(&pkt);
1336 pkt.stream_index= ost->index;
1338 switch(ost->st->codec->codec_type) {
1339 case CODEC_TYPE_AUDIO:
1340 fifo_bytes = fifo_size(&ost->fifo, NULL);
1342 /* encode any samples remaining in fifo */
1343 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1344 int fs_tmp = enc->frame_size;
1345 enc->frame_size = fifo_bytes / (2 * enc->channels);
1346 if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1347 &ost->fifo.rptr) == 0) {
1348 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1350 enc->frame_size = fs_tmp;
1353 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1356 pkt.flags |= PKT_FLAG_KEY;
1358 case CODEC_TYPE_VIDEO:
1359 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1361 if(enc->coded_frame && enc->coded_frame->key_frame)
1362 pkt.flags |= PKT_FLAG_KEY;
1363 if (ost->logfile && enc->stats_out) {
1364 fprintf(ost->logfile, "%s", enc->stats_out);
1373 pkt.data= bit_buffer;
1375 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1376 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1377 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1391 * The following code is the main loop of the file converter
1393 static int av_encode(AVFormatContext **output_files,
1394 int nb_output_files,
1395 AVFormatContext **input_files,
1397 AVStreamMap *stream_maps, int nb_stream_maps)
1399 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1400 AVFormatContext *is, *os;
1401 AVCodecContext *codec, *icodec;
1402 AVOutputStream *ost, **ost_table = NULL;
1403 AVInputStream *ist, **ist_table = NULL;
1404 AVInputFile *file_table;
1405 AVFormatContext *stream_no_data;
1408 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1412 /* input stream init */
1414 for(i=0;i<nb_input_files;i++) {
1415 is = input_files[i];
1416 file_table[i].ist_index = j;
1417 file_table[i].nb_streams = is->nb_streams;
1418 j += is->nb_streams;
1422 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1426 for(i=0;i<nb_istreams;i++) {
1427 ist = av_mallocz(sizeof(AVInputStream));
1433 for(i=0;i<nb_input_files;i++) {
1434 is = input_files[i];
1435 for(k=0;k<is->nb_streams;k++) {
1436 ist = ist_table[j++];
1437 ist->st = is->streams[k];
1438 ist->file_index = i;
1440 ist->discard = 1; /* the stream is discarded by default
1443 if (ist->st->codec->rate_emu) {
1444 ist->start = av_gettime();
1450 /* output stream init */
1452 for(i=0;i<nb_output_files;i++) {
1453 os = output_files[i];
1454 nb_ostreams += os->nb_streams;
1456 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1457 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1461 /* Sanity check the mapping args -- do the input files & streams exist? */
1462 for(i=0;i<nb_stream_maps;i++) {
1463 int fi = stream_maps[i].file_index;
1464 int si = stream_maps[i].stream_index;
1466 if (fi < 0 || fi > nb_input_files - 1 ||
1467 si < 0 || si > file_table[fi].nb_streams - 1) {
1468 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1471 fi = stream_maps[i].sync_file_index;
1472 si = stream_maps[i].sync_stream_index;
1473 if (fi < 0 || fi > nb_input_files - 1 ||
1474 si < 0 || si > file_table[fi].nb_streams - 1) {
1475 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1480 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1483 for(i=0;i<nb_ostreams;i++) {
1484 ost = av_mallocz(sizeof(AVOutputStream));
1491 for(k=0;k<nb_output_files;k++) {
1492 os = output_files[k];
1493 for(i=0;i<os->nb_streams;i++) {
1495 ost = ost_table[n++];
1496 ost->file_index = k;
1498 ost->st = os->streams[i];
1499 if (nb_stream_maps > 0) {
1500 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1501 stream_maps[n-1].stream_index;
1503 /* Sanity check that the stream types match */
1504 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1505 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1506 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1507 ost->file_index, ost->index);
1512 /* get corresponding input stream index : we select the first one with the right type */
1514 for(j=0;j<nb_istreams;j++) {
1517 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1518 ost->source_index = j;
1525 /* try again and reuse existing stream */
1526 for(j=0;j<nb_istreams;j++) {
1528 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1529 ost->source_index = j;
1534 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1535 ost->file_index, ost->index);
1540 ist = ist_table[ost->source_index];
1542 ost->sync_ist = (nb_stream_maps > 0) ?
1543 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1544 stream_maps[n-1].sync_stream_index] : ist;
1548 /* for each output stream, we compute the right encoding parameters */
1549 for(i=0;i<nb_ostreams;i++) {
1551 ist = ist_table[ost->source_index];
1553 codec = ost->st->codec;
1554 icodec = ist->st->codec;
1556 if (ost->st->stream_copy) {
1557 /* if stream_copy is selected, no need to decode or encode */
1558 codec->codec_id = icodec->codec_id;
1559 codec->codec_type = icodec->codec_type;
1560 if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1561 codec->bit_rate = icodec->bit_rate;
1562 codec->extradata= icodec->extradata;
1563 codec->extradata_size= icodec->extradata_size;
1564 codec->time_base = icodec->time_base;
1565 switch(codec->codec_type) {
1566 case CODEC_TYPE_AUDIO:
1567 codec->sample_rate = icodec->sample_rate;
1568 codec->channels = icodec->channels;
1569 codec->frame_size = icodec->frame_size;
1570 codec->block_align= icodec->block_align;
1572 case CODEC_TYPE_VIDEO:
1573 codec->pix_fmt = icodec->pix_fmt;
1574 codec->width = icodec->width;
1575 codec->height = icodec->height;
1576 codec->has_b_frames = icodec->has_b_frames;
1578 case CODEC_TYPE_SUBTITLE:
1584 switch(codec->codec_type) {
1585 case CODEC_TYPE_AUDIO:
1586 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1589 if (codec->channels == icodec->channels &&
1590 codec->sample_rate == icodec->sample_rate) {
1591 ost->audio_resample = 0;
1593 if (codec->channels != icodec->channels &&
1594 (icodec->codec_id == CODEC_ID_AC3 ||
1595 icodec->codec_id == CODEC_ID_DTS)) {
1596 /* Special case for 5:1 AC3 and DTS input */
1597 /* and mono or stereo output */
1598 /* Request specific number of channels */
1599 icodec->channels = codec->channels;
1600 if (codec->sample_rate == icodec->sample_rate)
1601 ost->audio_resample = 0;
1603 ost->audio_resample = 1;
1606 ost->audio_resample = 1;
1609 if(audio_sync_method>1)
1610 ost->audio_resample = 1;
1612 if(ost->audio_resample){
1613 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1614 codec->sample_rate, icodec->sample_rate);
1616 printf("Can't resample. Aborting.\n");
1620 ist->decoding_needed = 1;
1621 ost->encoding_needed = 1;
1623 case CODEC_TYPE_VIDEO:
1624 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1625 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1626 ost->video_resample = ((codec->width != icodec->width -
1627 (frame_leftBand + frame_rightBand) +
1628 (frame_padleft + frame_padright)) ||
1629 (codec->height != icodec->height -
1630 (frame_topBand + frame_bottomBand) +
1631 (frame_padtop + frame_padbottom)) ||
1632 (codec->pix_fmt != icodec->pix_fmt));
1633 if (ost->video_crop) {
1634 ost->topBand = frame_topBand;
1635 ost->leftBand = frame_leftBand;
1637 if (ost->video_pad) {
1638 ost->padtop = frame_padtop;
1639 ost->padleft = frame_padleft;
1640 ost->padbottom = frame_padbottom;
1641 ost->padright = frame_padright;
1642 if (!ost->video_resample) {
1643 avcodec_get_frame_defaults(&ost->pict_tmp);
1644 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1645 codec->width, codec->height ) )
1649 if (ost->video_resample) {
1650 avcodec_get_frame_defaults(&ost->pict_tmp);
1651 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1652 codec->width, codec->height ) )
1655 ost->img_resample_ctx = sws_getContext(
1656 icodec->width - (frame_leftBand + frame_rightBand),
1657 icodec->height - (frame_topBand + frame_bottomBand),
1659 codec->width - (frame_padleft + frame_padright),
1660 codec->height - (frame_padtop + frame_padbottom),
1662 sws_flags, NULL, NULL, NULL);
1663 if (ost->img_resample_ctx == NULL) {
1664 fprintf(stderr, "Cannot get resampling context\n");
1667 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1669 ost->encoding_needed = 1;
1670 ist->decoding_needed = 1;
1672 case CODEC_TYPE_SUBTITLE:
1673 ost->encoding_needed = 1;
1674 ist->decoding_needed = 1;
1681 if (ost->encoding_needed &&
1682 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1683 char logfilename[1024];
1688 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1690 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1691 if (codec->flags & CODEC_FLAG_PASS1) {
1692 f = fopen(logfilename, "w");
1694 perror(logfilename);
1699 /* read the log file */
1700 f = fopen(logfilename, "r");
1702 perror(logfilename);
1705 fseek(f, 0, SEEK_END);
1707 fseek(f, 0, SEEK_SET);
1708 logbuffer = av_malloc(size + 1);
1710 fprintf(stderr, "Could not allocate log buffer\n");
1713 size = fread(logbuffer, 1, size, f);
1715 logbuffer[size] = '\0';
1716 codec->stats_in = logbuffer;
1720 if(codec->codec_type == CODEC_TYPE_VIDEO){
1721 int size= codec->width * codec->height;
1722 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1727 bit_buffer = av_malloc(bit_buffer_size);
1731 /* dump the file output parameters - cannot be done before in case
1733 for(i=0;i<nb_output_files;i++) {
1734 dump_format(output_files[i], i, output_files[i]->filename, 1);
1737 /* dump the stream mapping */
1739 fprintf(stderr, "Stream mapping:\n");
1740 for(i=0;i<nb_ostreams;i++) {
1742 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1743 ist_table[ost->source_index]->file_index,
1744 ist_table[ost->source_index]->index,
1747 if (ost->sync_ist != ist_table[ost->source_index])
1748 fprintf(stderr, " [sync #%d.%d]",
1749 ost->sync_ist->file_index,
1750 ost->sync_ist->index);
1751 fprintf(stderr, "\n");
1755 /* open each encoder */
1756 for(i=0;i<nb_ostreams;i++) {
1758 if (ost->encoding_needed) {
1760 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1762 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1763 ost->file_index, ost->index);
1766 if (avcodec_open(ost->st->codec, codec) < 0) {
1767 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1768 ost->file_index, ost->index);
1771 extra_size += ost->st->codec->extradata_size;
1775 /* open each decoder */
1776 for(i=0;i<nb_istreams;i++) {
1778 if (ist->decoding_needed) {
1780 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1782 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1783 ist->st->codec->codec_id, ist->file_index, ist->index);
1786 if (avcodec_open(ist->st->codec, codec) < 0) {
1787 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1788 ist->file_index, ist->index);
1791 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1792 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1797 for(i=0;i<nb_istreams;i++) {
1799 is = input_files[ist->file_index];
1801 ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1802 if(ist->st->start_time == AV_NOPTS_VALUE)
1804 if(input_files_ts_offset[ist->file_index])
1805 ist->next_pts= AV_NOPTS_VALUE;
1809 /* compute buffer size max (should use a complete heuristic) */
1810 for(i=0;i<nb_input_files;i++) {
1811 file_table[i].buffer_size_max = 2048;
1814 /* set meta data information from input file if required */
1815 for (i=0;i<nb_meta_data_maps;i++) {
1816 AVFormatContext *out_file;
1817 AVFormatContext *in_file;
1819 int out_file_index = meta_data_maps[i].out_file;
1820 int in_file_index = meta_data_maps[i].in_file;
1821 if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1822 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1826 if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1827 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1832 out_file = output_files[out_file_index];
1833 in_file = input_files[in_file_index];
1835 strcpy(out_file->title, in_file->title);
1836 strcpy(out_file->author, in_file->author);
1837 strcpy(out_file->copyright, in_file->copyright);
1838 strcpy(out_file->comment, in_file->comment);
1839 strcpy(out_file->album, in_file->album);
1840 out_file->year = in_file->year;
1841 out_file->track = in_file->track;
1842 strcpy(out_file->genre, in_file->genre);
1845 /* open files and write file headers */
1846 for(i=0;i<nb_output_files;i++) {
1847 os = output_files[i];
1848 if (av_write_header(os) < 0) {
1849 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1856 if ( !using_stdin && verbose >= 0) {
1857 fprintf(stderr, "Press [q] to stop encoding\n");
1858 url_set_interrupt_cb(decode_interrupt_cb);
1866 for(; received_sigterm == 0;) {
1867 int file_index, ist_index;
1875 /* if 'q' pressed, exits */
1879 /* read_key() returns 0 on EOF */
1885 /* select the stream that we must read now by looking at the
1886 smallest output pts */
1888 for(i=0;i<nb_ostreams;i++) {
1891 os = output_files[ost->file_index];
1892 ist = ist_table[ost->source_index];
1893 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1894 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1896 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1897 ipts = (double)ist->pts;
1898 if (!file_table[ist->file_index].eof_reached){
1899 if(ipts < ipts_min) {
1901 if(input_sync ) file_index = ist->file_index;
1903 if(opts < opts_min) {
1905 if(!input_sync) file_index = ist->file_index;
1908 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1913 /* if none, if is finished */
1914 if (file_index < 0) {
1918 /* finish if recording time exhausted */
1919 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1922 /* finish if limit size exhausted */
1923 if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1926 /* read a frame from it and output it in the fifo */
1927 is = input_files[file_index];
1928 if (av_read_frame(is, &pkt) < 0) {
1929 file_table[file_index].eof_reached = 1;
1930 if (opt_shortest) break; else continue; //
1934 stream_no_data = is;
1939 av_pkt_dump(stdout, &pkt, do_hex_dump);
1941 /* the following test is needed in case new streams appear
1942 dynamically in stream : we ignore them */
1943 if (pkt.stream_index >= file_table[file_index].nb_streams)
1944 goto discard_packet;
1945 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1946 ist = ist_table[ist_index];
1948 goto discard_packet;
1950 // 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);
1951 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1952 int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1953 if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1954 input_files_ts_offset[ist->file_index]-= delta;
1956 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1957 for(i=0; i<file_table[file_index].nb_streams; i++){
1958 int index= file_table[file_index].ist_index + i;
1959 ist_table[index]->next_pts += delta;
1960 ist_table[index]->is_start=1;
1965 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1966 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1969 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1970 ist->file_index, ist->index);
1972 av_free_packet(&pkt);
1977 av_free_packet(&pkt);
1979 /* dump report by using the output first video and audio streams */
1980 print_report(output_files, ost_table, nb_ostreams, 0);
1983 /* at the end of stream, we must flush the decoder buffers */
1984 for(i=0;i<nb_istreams;i++) {
1986 if (ist->decoding_needed) {
1987 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1993 /* write the trailer if needed and close file */
1994 for(i=0;i<nb_output_files;i++) {
1995 os = output_files[i];
1996 av_write_trailer(os);
1999 /* dump report by using the first video and audio streams */
2000 print_report(output_files, ost_table, nb_ostreams, 1);
2002 /* close each encoder */
2003 for(i=0;i<nb_ostreams;i++) {
2005 if (ost->encoding_needed) {
2006 av_freep(&ost->st->codec->stats_in);
2007 avcodec_close(ost->st->codec);
2011 /* close each decoder */
2012 for(i=0;i<nb_istreams;i++) {
2014 if (ist->decoding_needed) {
2015 avcodec_close(ist->st->codec);
2023 av_freep(&bit_buffer);
2024 av_free(file_table);
2027 for(i=0;i<nb_istreams;i++) {
2034 for(i=0;i<nb_ostreams;i++) {
2038 fclose(ost->logfile);
2039 ost->logfile = NULL;
2041 fifo_free(&ost->fifo); /* works even if fifo is not
2042 initialized but set to zero */
2043 av_free(ost->pict_tmp.data[0]);
2044 if (ost->video_resample)
2045 sws_freeContext(ost->img_resample_ctx);
2046 if (ost->audio_resample)
2047 audio_resample_close(ost->resample);
2060 int file_read(const char *filename)
2063 unsigned char buffer[1024];
2066 if (url_open(&h, filename, O_RDONLY) < 0) {
2067 printf("could not open '%s'\n", filename);
2071 len = url_read(h, buffer, sizeof(buffer));
2074 for(i=0;i<len;i++) putchar(buffer[i]);
2081 static void opt_image_format(const char *arg)
2085 for(f = first_image_format; f != NULL; f = f->next) {
2086 if (!strcmp(arg, f->name))
2090 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2096 static void opt_format(const char *arg)
2098 /* compatibility stuff for pgmyuv */
2099 if (!strcmp(arg, "pgmyuv")) {
2100 pgmyuv_compatibility_hack=1;
2101 // opt_image_format(arg);
2105 file_iformat = av_find_input_format(arg);
2106 file_oformat = guess_format(arg, NULL, NULL);
2107 if (!file_iformat && !file_oformat) {
2108 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2113 static void opt_video_bitrate_tolerance(const char *arg)
2115 video_bit_rate_tolerance = atoi(arg) * 1000;
2118 static void opt_video_buffer_size(const char *arg)
2120 video_rc_buffer_size = atoi(arg) * 8*1024;
2123 static void opt_video_rc_eq(char *arg)
2128 static void opt_video_rc_override_string(char *arg)
2130 video_rc_override_string = arg;
2134 static void opt_workaround_bugs(const char *arg)
2136 workaround_bugs = atoi(arg);
2139 static void opt_me_threshold(const char *arg)
2141 me_threshold = atoi(arg);
2144 static void opt_mb_threshold(const char *arg)
2146 mb_threshold = atoi(arg);
2149 static void opt_verbose(const char *arg)
2151 verbose = atoi(arg);
2152 av_log_set_level(atoi(arg));
2155 static void opt_frame_rate(const char *arg)
2157 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2158 fprintf(stderr, "Incorrect frame rate\n");
2163 static void opt_frame_crop_top(const char *arg)
2165 frame_topBand = atoi(arg);
2166 if (frame_topBand < 0) {
2167 fprintf(stderr, "Incorrect top crop size\n");
2170 if ((frame_topBand % 2) != 0) {
2171 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2174 if ((frame_topBand) >= frame_height){
2175 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2178 frame_height -= frame_topBand;
2181 static void opt_frame_crop_bottom(const char *arg)
2183 frame_bottomBand = atoi(arg);
2184 if (frame_bottomBand < 0) {
2185 fprintf(stderr, "Incorrect bottom crop size\n");
2188 if ((frame_bottomBand % 2) != 0) {
2189 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2192 if ((frame_bottomBand) >= frame_height){
2193 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2196 frame_height -= frame_bottomBand;
2199 static void opt_frame_crop_left(const char *arg)
2201 frame_leftBand = atoi(arg);
2202 if (frame_leftBand < 0) {
2203 fprintf(stderr, "Incorrect left crop size\n");
2206 if ((frame_leftBand % 2) != 0) {
2207 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2210 if ((frame_leftBand) >= frame_width){
2211 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2214 frame_width -= frame_leftBand;
2217 static void opt_frame_crop_right(const char *arg)
2219 frame_rightBand = atoi(arg);
2220 if (frame_rightBand < 0) {
2221 fprintf(stderr, "Incorrect right crop size\n");
2224 if ((frame_rightBand % 2) != 0) {
2225 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2228 if ((frame_rightBand) >= frame_width){
2229 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2232 frame_width -= frame_rightBand;
2235 static void opt_frame_size(const char *arg)
2237 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2238 fprintf(stderr, "Incorrect frame size\n");
2241 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2242 fprintf(stderr, "Frame size must be a multiple of 2\n");
2248 #define SCALEBITS 10
2249 #define ONE_HALF (1 << (SCALEBITS - 1))
2250 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2252 #define RGB_TO_Y(r, g, b) \
2253 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2254 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2256 #define RGB_TO_U(r1, g1, b1, shift)\
2257 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2258 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2260 #define RGB_TO_V(r1, g1, b1, shift)\
2261 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2262 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2264 static void opt_pad_color(const char *arg) {
2265 /* Input is expected to be six hex digits similar to
2266 how colors are expressed in html tags (but without the #) */
2267 int rgb = strtol(arg, NULL, 16);
2271 g = ((rgb >> 8) & 255);
2274 padcolor[0] = RGB_TO_Y(r,g,b);
2275 padcolor[1] = RGB_TO_U(r,g,b,0);
2276 padcolor[2] = RGB_TO_V(r,g,b,0);
2279 static void opt_frame_pad_top(const char *arg)
2281 frame_padtop = atoi(arg);
2282 if (frame_padtop < 0) {
2283 fprintf(stderr, "Incorrect top pad size\n");
2286 if ((frame_padtop % 2) != 0) {
2287 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2292 static void opt_frame_pad_bottom(const char *arg)
2294 frame_padbottom = atoi(arg);
2295 if (frame_padbottom < 0) {
2296 fprintf(stderr, "Incorrect bottom pad size\n");
2299 if ((frame_padbottom % 2) != 0) {
2300 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2306 static void opt_frame_pad_left(const char *arg)
2308 frame_padleft = atoi(arg);
2309 if (frame_padleft < 0) {
2310 fprintf(stderr, "Incorrect left pad size\n");
2313 if ((frame_padleft % 2) != 0) {
2314 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2320 static void opt_frame_pad_right(const char *arg)
2322 frame_padright = atoi(arg);
2323 if (frame_padright < 0) {
2324 fprintf(stderr, "Incorrect right pad size\n");
2327 if ((frame_padright % 2) != 0) {
2328 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2334 static void opt_frame_pix_fmt(const char *arg)
2336 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2339 static void opt_frame_aspect_ratio(const char *arg)
2345 p = strchr(arg, ':');
2347 x = strtol(arg, (char **)&arg, 10);
2349 y = strtol(arg+1, (char **)&arg, 10);
2351 ar = (double)x / (double)y;
2353 ar = strtod(arg, (char **)&arg);
2356 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2359 frame_aspect_ratio = ar;
2362 static void opt_b_frames(const char *arg)
2364 b_frames = atoi(arg);
2365 if (b_frames > FF_MAX_B_FRAMES) {
2366 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2368 } else if (b_frames < 1) {
2369 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2374 static void opt_qscale(const char *arg)
2376 video_qscale = atof(arg);
2377 if (video_qscale <= 0 ||
2378 video_qscale > 255) {
2379 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2384 static void opt_qsquish(const char *arg)
2386 video_qsquish = atof(arg);
2387 if (video_qsquish < 0.0 ||
2388 video_qsquish > 99.0) {
2389 fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2394 static void opt_lmax(const char *arg)
2396 video_lmax = atof(arg)*FF_QP2LAMBDA;
2399 static void opt_lmin(const char *arg)
2401 video_lmin = atof(arg)*FF_QP2LAMBDA;
2404 static void opt_qmin(const char *arg)
2406 video_qmin = atoi(arg);
2407 if (video_qmin < 1 ||
2409 fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2414 static void opt_qmax(const char *arg)
2416 video_qmax = atoi(arg);
2417 if (video_qmax < 1 ||
2419 fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2424 static void opt_mb_lmin(const char *arg)
2426 video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2427 if (video_mb_lmin < 1 ||
2428 video_mb_lmin > FF_LAMBDA_MAX) {
2429 fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2434 static void opt_mb_lmax(const char *arg)
2436 video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2437 if (video_mb_lmax < 1 ||
2438 video_mb_lmax > FF_LAMBDA_MAX) {
2439 fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2444 static void opt_qdiff(const char *arg)
2446 video_qdiff = atoi(arg);
2447 if (video_qdiff < 0 ||
2449 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2454 static void opt_qblur(const char *arg)
2456 video_qblur = atof(arg);
2459 static void opt_qcomp(const char *arg)
2461 video_qcomp = atof(arg);
2464 static void opt_rc_initial_cplx(const char *arg)
2466 video_rc_initial_cplx = atof(arg);
2468 static void opt_b_qfactor(const char *arg)
2470 video_b_qfactor = atof(arg);
2472 static void opt_i_qfactor(const char *arg)
2474 video_i_qfactor = atof(arg);
2476 static void opt_b_qoffset(const char *arg)
2478 video_b_qoffset = atof(arg);
2480 static void opt_i_qoffset(const char *arg)
2482 video_i_qoffset = atof(arg);
2485 static void opt_pbias(const char *arg)
2487 video_inter_quant_bias = atoi(arg);
2490 static void opt_packet_size(const char *arg)
2492 packet_size= atoi(arg);
2495 static void opt_error_rate(const char *arg)
2497 error_rate= atoi(arg);
2500 static void opt_strict(const char *arg)
2505 static void opt_top_field_first(const char *arg)
2507 top_field_first= atoi(arg);
2510 static void opt_sc_threshold(const char *arg)
2512 sc_threshold= atoi(arg);
2515 static void opt_me_range(const char *arg)
2517 me_range = atoi(arg);
2520 static void opt_thread_count(const char *arg)
2522 thread_count= atoi(arg);
2523 #if !defined(HAVE_THREADS)
2525 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2529 static void opt_audio_bitrate(const char *arg)
2531 audio_bit_rate = atoi(arg) * 1000;
2534 static void opt_audio_rate(const char *arg)
2536 audio_sample_rate = atoi(arg);
2539 static void opt_audio_channels(const char *arg)
2541 audio_channels = atoi(arg);
2544 static void opt_video_device(const char *arg)
2546 video_device = av_strdup(arg);
2549 static void opt_grab_device(const char *arg)
2551 grab_device = av_strdup(arg);
2554 static void opt_video_channel(const char *arg)
2556 video_channel = strtol(arg, NULL, 0);
2559 static void opt_video_standard(const char *arg)
2561 video_standard = av_strdup(arg);
2564 static void opt_audio_device(const char *arg)
2566 audio_device = av_strdup(arg);
2569 static void opt_codec(int *pstream_copy, int *pcodec_id,
2570 int codec_type, const char *arg)
2574 if (!strcmp(arg, "copy")) {
2579 if (!strcmp(p->name, arg) && p->type == codec_type)
2584 fprintf(stderr, "Unknown codec '%s'\n", arg);
2592 static void opt_audio_codec(const char *arg)
2594 opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2597 static void opt_audio_tag(const char *arg)
2600 audio_codec_tag= strtol(arg, &tail, 0);
2603 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2606 static void opt_video_tag(const char *arg)
2609 video_codec_tag= strtol(arg, &tail, 0);
2612 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2615 static void add_frame_hooker(const char *arg)
2620 char *args = av_strdup(arg);
2624 argv[0] = strtok(args, " ");
2625 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2628 i = frame_hook_add(argc, argv);
2631 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2636 const char *motion_str[] = {
2649 static void opt_motion_estimation(const char *arg)
2655 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2658 if (!strcmp(*p, arg))
2662 me_method = (p - motion_str) + 1;
2665 static void opt_video_codec(const char *arg)
2667 opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2670 static void opt_subtitle_codec(const char *arg)
2672 opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2675 static void opt_map(const char *arg)
2681 m = &stream_maps[nb_stream_maps++];
2683 m->file_index = strtol(arg, (char **)&p, 0);
2687 m->stream_index = strtol(p, (char **)&p, 0);
2690 m->sync_file_index = strtol(p, (char **)&p, 0);
2693 m->sync_stream_index = strtol(p, (char **)&p, 0);
2695 m->sync_file_index = m->file_index;
2696 m->sync_stream_index = m->stream_index;
2700 static void opt_map_meta_data(const char *arg)
2706 m = &meta_data_maps[nb_meta_data_maps++];
2708 m->out_file = strtol(arg, (char **)&p, 0);
2712 m->in_file = strtol(p, (char **)&p, 0);
2715 static void opt_recording_time(const char *arg)
2717 recording_time = parse_date(arg, 1);
2720 static void opt_start_time(const char *arg)
2722 start_time = parse_date(arg, 1);
2725 static void opt_rec_timestamp(const char *arg)
2727 rec_timestamp = parse_date(arg, 0) / 1000000;
2730 static void opt_input_ts_offset(const char *arg)
2732 input_ts_offset = parse_date(arg, 1);
2735 static void opt_input_file(const char *filename)
2737 AVFormatContext *ic;
2738 AVFormatParameters params, *ap = ¶ms;
2739 int err, i, ret, rfps, rfps_base;
2742 if (!strcmp(filename, "-"))
2745 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2746 !strcmp( filename, "/dev/stdin" );
2748 /* get default parameters from command line */
2749 ic = av_alloc_format_context();
2751 memset(ap, 0, sizeof(*ap));
2752 ap->prealloced_context = 1;
2753 ap->sample_rate = audio_sample_rate;
2754 ap->channels = audio_channels;
2755 ap->time_base.den = frame_rate;
2756 ap->time_base.num = frame_rate_base;
2757 ap->width = frame_width + frame_padleft + frame_padright;
2758 ap->height = frame_height + frame_padtop + frame_padbottom;
2759 ap->image_format = image_format;
2760 ap->pix_fmt = frame_pix_fmt;
2761 ap->device = grab_device;
2762 ap->channel = video_channel;
2763 ap->standard = video_standard;
2764 ap->video_codec_id = video_codec_id;
2765 ap->audio_codec_id = audio_codec_id;
2766 if(pgmyuv_compatibility_hack)
2767 ap->video_codec_id= CODEC_ID_PGMYUV;
2769 for(i=0; i<opt_name_count; i++){
2771 double d= av_get_double(avformat_opts, opt_names[i], &opt);
2772 if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2773 av_set_double(ic, opt_names[i], d);
2775 /* open the input file with generic libav function */
2776 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2778 print_error(filename, err);
2782 ic->loop_input = loop_input;
2784 /* If not enough info to get the stream parameters, we decode the
2785 first frames to get it. (used in mpeg case for example) */
2786 ret = av_find_stream_info(ic);
2787 if (ret < 0 && verbose >= 0) {
2788 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2792 timestamp = start_time;
2793 /* add the stream start time */
2794 if (ic->start_time != AV_NOPTS_VALUE)
2795 timestamp += ic->start_time;
2797 /* if seeking requested, we execute it */
2798 if (start_time != 0) {
2799 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2801 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2802 filename, (double)timestamp / AV_TIME_BASE);
2804 /* reset seek info */
2808 /* update the current parameters so that they match the one of the input stream */
2809 for(i=0;i<ic->nb_streams;i++) {
2811 AVCodecContext *enc = ic->streams[i]->codec;
2812 #if defined(HAVE_THREADS)
2814 avcodec_thread_init(enc, thread_count);
2816 enc->thread_count= thread_count;
2817 switch(enc->codec_type) {
2818 case CODEC_TYPE_AUDIO:
2819 for(j=0; j<opt_name_count; j++){
2821 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2822 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2823 av_set_double(enc, opt_names[j], d);
2825 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2826 audio_channels = enc->channels;
2827 audio_sample_rate = enc->sample_rate;
2829 ic->streams[i]->discard= AVDISCARD_ALL;
2831 case CODEC_TYPE_VIDEO:
2832 for(j=0; j<opt_name_count; j++){
2834 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2835 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2836 av_set_double(enc, opt_names[j], d);
2838 frame_height = enc->height;
2839 frame_width = enc->width;
2840 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2841 frame_pix_fmt = enc->pix_fmt;
2842 rfps = ic->streams[i]->r_frame_rate.num;
2843 rfps_base = ic->streams[i]->r_frame_rate.den;
2844 enc->workaround_bugs = workaround_bugs;
2845 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2847 enc->debug |= FF_DEBUG_MV;
2849 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2852 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2853 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2855 (float)rfps / rfps_base, rfps, rfps_base);
2857 /* update the current frame rate to match the stream frame rate */
2859 frame_rate_base = rfps_base;
2861 enc->rate_emu = rate_emu;
2863 ic->streams[i]->discard= AVDISCARD_ALL;
2864 else if(video_discard)
2865 ic->streams[i]->discard= video_discard;
2867 case CODEC_TYPE_DATA:
2869 case CODEC_TYPE_SUBTITLE:
2871 case CODEC_TYPE_UNKNOWN:
2878 input_files[nb_input_files] = ic;
2879 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2880 /* dump the file content */
2882 dump_format(ic, nb_input_files, filename, 0);
2885 file_iformat = NULL;
2886 file_oformat = NULL;
2887 image_format = NULL;
2895 static void opt_grab(const char *arg)
2897 file_iformat = av_find_input_format(arg);
2901 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2903 int has_video, has_audio, i, j;
2904 AVFormatContext *ic;
2908 for(j=0;j<nb_input_files;j++) {
2909 ic = input_files[j];
2910 for(i=0;i<ic->nb_streams;i++) {
2911 AVCodecContext *enc = ic->streams[i]->codec;
2912 switch(enc->codec_type) {
2913 case CODEC_TYPE_AUDIO:
2916 case CODEC_TYPE_VIDEO:
2919 case CODEC_TYPE_DATA:
2920 case CODEC_TYPE_UNKNOWN:
2921 case CODEC_TYPE_SUBTITLE:
2928 *has_video_ptr = has_video;
2929 *has_audio_ptr = has_audio;
2932 static void new_video_stream(AVFormatContext *oc)
2935 AVCodecContext *video_enc;
2938 st = av_new_stream(oc, oc->nb_streams);
2940 fprintf(stderr, "Could not alloc stream\n");
2943 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2944 video_bitstream_filters= NULL;
2946 #if defined(HAVE_THREADS)
2948 avcodec_thread_init(st->codec, thread_count);
2951 video_enc = st->codec;
2954 video_enc->codec_tag= video_codec_tag;
2956 if( (video_global_header&1)
2957 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2958 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2959 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2961 if(video_global_header&2){
2962 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2963 avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2966 if (video_stream_copy) {
2967 st->stream_copy = 1;
2968 video_enc->codec_type = CODEC_TYPE_VIDEO;
2974 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2975 if (video_codec_id != CODEC_ID_NONE)
2976 codec_id = video_codec_id;
2978 video_enc->codec_id = codec_id;
2979 codec = avcodec_find_encoder(codec_id);
2981 for(i=0; i<opt_name_count; i++){
2983 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2984 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2985 av_set_double(video_enc, opt_names[i], d);
2988 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2989 video_enc->time_base.den = frame_rate;
2990 video_enc->time_base.num = frame_rate_base;
2991 if(codec && codec->supported_framerates){
2992 const AVRational *p= codec->supported_framerates;
2993 AVRational req= (AVRational){frame_rate, frame_rate_base};
2994 const AVRational *best=NULL;
2995 AVRational best_error= (AVRational){INT_MAX, 1};
2996 for(; p->den!=0; p++){
2997 AVRational error= av_sub_q(req, *p);
2998 if(error.num <0) error.num *= -1;
2999 if(av_cmp_q(error, best_error) < 0){
3004 video_enc->time_base.den= best->num;
3005 video_enc->time_base.num= best->den;
3008 video_enc->width = frame_width + frame_padright + frame_padleft;
3009 video_enc->height = frame_height + frame_padtop + frame_padbottom;
3010 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3011 video_enc->pix_fmt = frame_pix_fmt;
3013 if(codec && codec->pix_fmts){
3014 const enum PixelFormat *p= codec->pix_fmts;
3016 if(*p == video_enc->pix_fmt)
3020 video_enc->pix_fmt = codec->pix_fmts[0];
3024 video_enc->gop_size = 0;
3025 if (video_qscale || same_quality) {
3026 video_enc->flags |= CODEC_FLAG_QSCALE;
3027 video_enc->global_quality=
3028 st->quality = FF_QP2LAMBDA * video_qscale;
3032 video_enc->intra_matrix = intra_matrix;
3034 video_enc->inter_matrix = inter_matrix;
3037 video_enc->max_b_frames = b_frames;
3038 video_enc->b_quant_factor = 2.0;
3040 video_enc->qmin = video_qmin;
3041 video_enc->qmax = video_qmax;
3042 video_enc->lmin = video_lmin;
3043 video_enc->lmax = video_lmax;
3044 video_enc->rc_qsquish = video_qsquish;
3045 video_enc->mb_lmin = video_mb_lmin;
3046 video_enc->mb_lmax = video_mb_lmax;
3047 video_enc->max_qdiff = video_qdiff;
3048 video_enc->qblur = video_qblur;
3049 video_enc->qcompress = video_qcomp;
3050 video_enc->rc_eq = video_rc_eq;
3051 video_enc->workaround_bugs = workaround_bugs;
3052 video_enc->thread_count = thread_count;
3053 p= video_rc_override_string;
3056 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3058 fprintf(stderr, "error parsing rc_override\n");
3061 video_enc->rc_override=
3062 av_realloc(video_enc->rc_override,
3063 sizeof(RcOverride)*(i+1));
3064 video_enc->rc_override[i].start_frame= start;
3065 video_enc->rc_override[i].end_frame = end;
3067 video_enc->rc_override[i].qscale= q;
3068 video_enc->rc_override[i].quality_factor= 1.0;
3071 video_enc->rc_override[i].qscale= 0;
3072 video_enc->rc_override[i].quality_factor= -q/100.0;
3077 video_enc->rc_override_count=i;
3079 video_enc->rc_buffer_size = video_rc_buffer_size;
3080 video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3081 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3082 video_enc->rc_initial_cplx= video_rc_initial_cplx;
3083 video_enc->i_quant_factor = video_i_qfactor;
3084 video_enc->b_quant_factor = video_b_qfactor;
3085 video_enc->i_quant_offset = video_i_qoffset;
3086 video_enc->b_quant_offset = video_b_qoffset;
3087 video_enc->inter_quant_bias = video_inter_quant_bias;
3088 video_enc->me_threshold= me_threshold;
3089 video_enc->mb_threshold= mb_threshold;
3090 video_enc->intra_dc_precision= intra_dc_precision - 8;
3091 video_enc->strict_std_compliance = strict;
3092 video_enc->error_rate = error_rate;
3093 video_enc->scenechange_threshold= sc_threshold;
3094 video_enc->me_range = me_range;
3095 video_enc->me_penalty_compensation= me_penalty_compensation;
3096 video_enc->frame_skip_threshold= frame_skip_threshold;
3097 video_enc->frame_skip_factor= frame_skip_factor;
3098 video_enc->frame_skip_exp= frame_skip_exp;
3101 video_enc->rtp_mode= 1;
3102 video_enc->rtp_payload_size= packet_size;
3106 video_enc->flags|= CODEC_FLAG_PSNR;
3108 video_enc->me_method = me_method;
3113 video_enc->flags |= CODEC_FLAG_PASS1;
3115 video_enc->flags |= CODEC_FLAG_PASS2;
3120 /* reset some key parameters */
3122 video_codec_id = CODEC_ID_NONE;
3123 video_stream_copy = 0;
3126 static void new_audio_stream(AVFormatContext *oc)
3129 AVCodecContext *audio_enc;
3132 st = av_new_stream(oc, oc->nb_streams);
3134 fprintf(stderr, "Could not alloc stream\n");
3138 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3139 audio_bitstream_filters= NULL;
3141 #if defined(HAVE_THREADS)
3143 avcodec_thread_init(st->codec, thread_count);
3146 audio_enc = st->codec;
3147 audio_enc->codec_type = CODEC_TYPE_AUDIO;
3150 audio_enc->codec_tag= audio_codec_tag;
3152 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3153 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3154 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3156 if (audio_stream_copy) {
3157 st->stream_copy = 1;
3158 audio_enc->channels = audio_channels;
3160 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3162 for(i=0; i<opt_name_count; i++){
3164 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3165 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3166 av_set_double(audio_enc, opt_names[i], d);
3169 if (audio_codec_id != CODEC_ID_NONE)
3170 codec_id = audio_codec_id;
3171 audio_enc->codec_id = codec_id;
3173 audio_enc->bit_rate = audio_bit_rate;
3174 if (audio_qscale > QSCALE_NONE) {
3175 audio_enc->flags |= CODEC_FLAG_QSCALE;
3176 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3178 audio_enc->strict_std_compliance = strict;
3179 audio_enc->thread_count = thread_count;
3180 /* For audio codecs other than AC3 or DTS we limit */
3181 /* the number of coded channels to stereo */
3182 if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3183 && codec_id != CODEC_ID_DTS) {
3184 audio_enc->channels = 2;
3186 audio_enc->channels = audio_channels;
3188 audio_enc->sample_rate = audio_sample_rate;
3189 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3190 if (audio_language) {
3191 pstrcpy(st->language, sizeof(st->language), audio_language);
3192 av_free(audio_language);
3193 audio_language = NULL;
3196 /* reset some key parameters */
3198 audio_codec_id = CODEC_ID_NONE;
3199 audio_stream_copy = 0;
3202 static void opt_new_subtitle_stream(void)
3204 AVFormatContext *oc;
3206 AVCodecContext *subtitle_enc;
3209 if (nb_output_files <= 0) {
3210 fprintf(stderr, "At least one output file must be specified\n");
3213 oc = output_files[nb_output_files - 1];
3215 st = av_new_stream(oc, oc->nb_streams);
3217 fprintf(stderr, "Could not alloc stream\n");
3221 subtitle_enc = st->codec;
3222 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3223 if (subtitle_stream_copy) {
3224 st->stream_copy = 1;
3226 for(i=0; i<opt_name_count; i++){
3228 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3229 if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3230 av_set_double(subtitle_enc, opt_names[i], d);
3232 subtitle_enc->codec_id = subtitle_codec_id;
3235 if (subtitle_language) {
3236 pstrcpy(st->language, sizeof(st->language), subtitle_language);
3237 av_free(subtitle_language);
3238 subtitle_language = NULL;
3241 subtitle_codec_id = CODEC_ID_NONE;
3242 subtitle_stream_copy = 0;
3245 static void opt_new_audio_stream(void)
3247 AVFormatContext *oc;
3248 if (nb_output_files <= 0) {
3249 fprintf(stderr, "At least one output file must be specified\n");
3252 oc = output_files[nb_output_files - 1];
3253 new_audio_stream(oc);
3256 static void opt_new_video_stream(void)
3258 AVFormatContext *oc;
3259 if (nb_output_files <= 0) {
3260 fprintf(stderr, "At least one output file must be specified\n");
3263 oc = output_files[nb_output_files - 1];
3264 new_video_stream(oc);
3267 static void opt_output_file(const char *filename)
3269 AVFormatContext *oc;
3270 int use_video, use_audio, input_has_video, input_has_audio, i;
3271 AVFormatParameters params, *ap = ¶ms;
3273 if (!strcmp(filename, "-"))
3276 oc = av_alloc_format_context();
3278 if (!file_oformat) {
3279 file_oformat = guess_format(NULL, filename, NULL);
3280 if (!file_oformat) {
3281 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3287 oc->oformat = file_oformat;
3288 pstrcpy(oc->filename, sizeof(oc->filename), filename);
3290 if (!strcmp(file_oformat->name, "ffm") &&
3291 strstart(filename, "http:", NULL)) {
3292 /* special case for files sent to ffserver: we get the stream
3293 parameters from ffserver */
3294 if (read_ffserver_streams(oc, filename) < 0) {
3295 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3299 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3300 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3302 /* disable if no corresponding type found and at least one
3304 if (nb_input_files > 0) {
3305 check_audio_video_inputs(&input_has_video, &input_has_audio);
3306 if (!input_has_video)
3308 if (!input_has_audio)
3312 /* manual disable */
3313 if (audio_disable) {
3316 if (video_disable) {
3321 new_video_stream(oc);
3325 new_audio_stream(oc);
3328 if (!oc->nb_streams) {
3329 fprintf(stderr, "No audio or video streams available\n");
3333 oc->timestamp = rec_timestamp;
3336 pstrcpy(oc->title, sizeof(oc->title), str_title);
3338 pstrcpy(oc->author, sizeof(oc->author), str_author);
3340 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3342 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3344 pstrcpy(oc->album, sizeof(oc->album), str_album);
3347 output_files[nb_output_files++] = oc;
3349 /* check filename in case of an image number is expected */
3350 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3351 if (!av_filename_number_test(oc->filename)) {
3352 print_error(oc->filename, AVERROR_NUMEXPECTED);
3357 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3358 /* test if it already exists to avoid loosing precious files */
3359 if (!file_overwrite &&
3360 (strchr(filename, ':') == NULL ||
3361 strstart(filename, "file:", NULL))) {
3362 if (url_exist(filename)) {
3365 if ( !using_stdin ) {
3366 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3369 if (toupper(c) != 'Y') {
3370 fprintf(stderr, "Not overwriting - exiting\n");
3375 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3382 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3383 fprintf(stderr, "Could not open '%s'\n", filename);
3388 memset(ap, 0, sizeof(*ap));
3389 ap->image_format = image_format;
3390 if (av_set_parameters(oc, ap) < 0) {
3391 fprintf(stderr, "%s: Invalid encoding parameters\n",
3396 oc->packet_size= mux_packet_size;
3397 oc->mux_rate= mux_rate;
3398 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3399 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3400 oc->loop_output = loop_output;
3402 for(i=0; i<opt_name_count; i++){
3404 double d = av_get_double(avformat_opts, opt_names[i], &opt);
3405 if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3406 av_set_double(oc, opt_names[i], d);
3409 /* reset some options */
3410 file_oformat = NULL;
3411 file_iformat = NULL;
3412 image_format = NULL;
3415 /* prepare dummy protocols for grab */
3416 static void prepare_grab(void)
3418 int has_video, has_audio, i, j;
3419 AVFormatContext *oc;
3420 AVFormatContext *ic;
3421 AVFormatParameters vp1, *vp = &vp1;
3422 AVFormatParameters ap1, *ap = &ap1;
3424 /* see if audio/video inputs are needed */
3427 memset(ap, 0, sizeof(*ap));
3428 memset(vp, 0, sizeof(*vp));
3429 vp->time_base.num= 1;
3430 for(j=0;j<nb_output_files;j++) {
3431 oc = output_files[j];
3432 for(i=0;i<oc->nb_streams;i++) {
3433 AVCodecContext *enc = oc->streams[i]->codec;
3434 switch(enc->codec_type) {
3435 case CODEC_TYPE_AUDIO:
3436 if (enc->sample_rate > ap->sample_rate)
3437 ap->sample_rate = enc->sample_rate;
3438 if (enc->channels > ap->channels)
3439 ap->channels = enc->channels;
3442 case CODEC_TYPE_VIDEO:
3443 if (enc->width > vp->width)
3444 vp->width = enc->width;
3445 if (enc->height > vp->height)
3446 vp->height = enc->height;
3448 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3449 vp->time_base = enc->time_base;
3450 vp->width += frame_leftBand + frame_rightBand;
3451 vp->width -= (frame_padleft + frame_padright);
3452 vp->height += frame_topBand + frame_bottomBand;
3453 vp->height -= (frame_padtop + frame_padbottom);
3463 if (has_video == 0 && has_audio == 0) {
3464 fprintf(stderr, "Output file must have at least one audio or video stream\n");
3469 AVInputFormat *fmt1;
3470 fmt1 = av_find_input_format(video_grab_format);
3471 vp->device = video_device;
3472 vp->channel = video_channel;
3473 vp->standard = video_standard;
3474 vp->pix_fmt = frame_pix_fmt;
3475 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3476 fprintf(stderr, "Could not find video grab device\n");
3479 /* If not enough info to get the stream parameters, we decode the
3480 first frames to get it. */
3481 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3482 fprintf(stderr, "Could not find video grab parameters\n");
3485 /* by now video grab has one stream */
3486 ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3487 ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3488 input_files[nb_input_files] = ic;
3491 dump_format(ic, nb_input_files, "", 0);
3495 if (has_audio && audio_grab_format) {
3496 AVInputFormat *fmt1;
3497 fmt1 = av_find_input_format(audio_grab_format);
3498 ap->device = audio_device;
3499 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3500 fprintf(stderr, "Could not find audio grab device\n");
3503 input_files[nb_input_files] = ic;
3506 dump_format(ic, nb_input_files, "", 0);
3512 /* same option as mencoder */
3513 static void opt_pass(const char *pass_str)
3516 pass = atoi(pass_str);
3517 if (pass != 1 && pass != 2) {
3518 fprintf(stderr, "pass number can be only 1 or 2\n");
3524 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3525 static int64_t getutime(void)
3527 return av_gettime();
3530 static int64_t getutime(void)
3532 struct rusage rusage;
3534 getrusage(RUSAGE_SELF, &rusage);
3535 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3539 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3540 extern int ffm_nopts;
3543 static void show_formats(void)
3545 AVInputFormat *ifmt;
3546 AVOutputFormat *ofmt;
3547 AVImageFormat *image_fmt;
3550 const char **pp, *last_name;
3552 printf("File formats:\n");
3557 const char *name=NULL;
3558 const char *long_name=NULL;
3560 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3561 if((name == NULL || strcmp(ofmt->name, name)<0) &&
3562 strcmp(ofmt->name, last_name)>0){
3564 long_name= ofmt->long_name;
3568 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3569 if((name == NULL || strcmp(ifmt->name, name)<0) &&
3570 strcmp(ifmt->name, last_name)>0){
3572 long_name= ifmt->long_name;
3575 if(name && strcmp(ifmt->name, name)==0)
3587 long_name ? long_name:" ");
3591 printf("Image formats (filename extensions, if any, follow):\n");
3592 for(image_fmt = first_image_format; image_fmt != NULL;
3593 image_fmt = image_fmt->next) {
3596 image_fmt->img_read ? "D":" ",
3597 image_fmt->img_write ? "E":" ",
3599 image_fmt->extensions ? image_fmt->extensions:" ");
3603 printf("Codecs:\n");
3609 const char *type_str;
3612 for(p = first_avcodec; p != NULL; p = p->next) {
3613 if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3614 strcmp(p->name, last_name)>0){
3616 decode= encode= cap=0;
3618 if(p2 && strcmp(p->name, p2->name)==0){
3619 if(p->decode) decode=1;
3620 if(p->encode) encode=1;
3621 cap |= p->capabilities;
3626 last_name= p2->name;
3629 case CODEC_TYPE_VIDEO:
3632 case CODEC_TYPE_AUDIO:
3635 case CODEC_TYPE_SUBTITLE:
3644 decode ? "D": (/*p2->decoder ? "d":*/" "),
3647 cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3648 cap & CODEC_CAP_DR1 ? "D":" ",
3649 cap & CODEC_CAP_TRUNCATED ? "T":" ",
3651 /* if(p2->decoder && decode==0)
3652 printf(" use %s for decoding", p2->decoder->name);*/
3657 printf("Supported file protocols:\n");
3658 for(up = first_protocol; up != NULL; up = up->next)
3659 printf(" %s:", up->name);
3662 printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3663 printf("Motion estimation methods:\n");
3667 if ((pp - motion_str + 1) == ME_ZERO)
3668 printf("(fastest)");
3669 else if ((pp - motion_str + 1) == ME_FULL)
3670 printf("(slowest)");
3671 else if ((pp - motion_str + 1) == ME_EPZS)
3672 printf("(default)");
3677 "Note, the names of encoders and decoders dont always match, so there are\n"
3678 "several cases where the above table shows encoder only or decoder only entries\n"
3679 "even though both encoding and decoding are supported for example, the h263\n"
3680 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3685 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3688 const char *p = str;
3695 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3702 static void opt_inter_matrix(const char *arg)
3704 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3705 parse_matrix_coeffs(inter_matrix, arg);
3708 static void opt_intra_matrix(const char *arg)
3710 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3711 parse_matrix_coeffs(intra_matrix, arg);
3714 static void opt_target(const char *arg)
3717 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3719 if(!strncmp(arg, "pal-", 4)) {
3722 } else if(!strncmp(arg, "ntsc-", 5)) {
3725 } else if(!strncmp(arg, "film-", 5)) {
3730 /* Calculate FR via float to avoid int overflow */
3731 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3734 } else if((fr == 29970) || (fr == 23976)) {
3737 /* Try to determine PAL/NTSC by peeking in the input files */
3738 if(nb_input_files) {
3740 for(j = 0; j < nb_input_files; j++) {
3741 for(i = 0; i < input_files[j]->nb_streams; i++) {
3742 AVCodecContext *c = input_files[j]->streams[i]->codec;
3743 if(c->codec_type != CODEC_TYPE_VIDEO)
3745 fr = c->time_base.den * 1000 / c->time_base.num;