3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 #define HAVE_AV_CONFIG_H
23 #include "framehook.h"
30 #include <sys/ioctl.h>
33 #include <sys/resource.h>
37 #include <sys/types.h>
38 #include <sys/select.h>
41 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
50 #if !defined(INFINITY) && defined(HUGE_VAL)
51 #define INFINITY HUGE_VAL
54 /* select an input stream for an output stream */
55 typedef struct AVStreamMap {
59 int sync_stream_index;
62 /** select an input file for an output file */
63 typedef struct AVMetaDataMap {
68 extern const OptionDef options[];
70 static void show_help(void);
71 static void show_license(void);
72 static int opt_default(const char *opt, const char *arg);
76 static AVFormatContext *input_files[MAX_FILES];
77 static int64_t input_files_ts_offset[MAX_FILES];
78 static int nb_input_files = 0;
80 static AVFormatContext *output_files[MAX_FILES];
81 static int nb_output_files = 0;
83 static AVStreamMap stream_maps[MAX_FILES];
84 static int nb_stream_maps;
86 static AVMetaDataMap meta_data_maps[MAX_FILES];
87 static int nb_meta_data_maps;
89 static AVInputFormat *file_iformat;
90 static AVOutputFormat *file_oformat;
91 static AVImageFormat *image_format;
92 static int frame_width = 0;
93 static int frame_height = 0;
94 static float frame_aspect_ratio = 0;
95 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
96 static int frame_padtop = 0;
97 static int frame_padbottom = 0;
98 static int frame_padleft = 0;
99 static int frame_padright = 0;
100 static int padcolor[3] = {16,128,128}; /* default to black */
101 static int frame_topBand = 0;
102 static int frame_bottomBand = 0;
103 static int frame_leftBand = 0;
104 static int frame_rightBand = 0;
105 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
106 static int frame_rate = 25;
107 static int frame_rate_base = 1;
108 static float video_qscale = 0;
109 static int video_qmax = 31;
110 static int video_lmin = 2*FF_QP2LAMBDA;
111 static int video_lmax = 31*FF_QP2LAMBDA;
112 static int video_mb_lmin = 2*FF_QP2LAMBDA;
113 static int video_mb_lmax = 31*FF_QP2LAMBDA;
114 static int video_qdiff = 3;
115 static float video_qsquish = 0.0;
116 static uint16_t *intra_matrix = NULL;
117 static uint16_t *inter_matrix = NULL;
118 #if 0 //experimental, (can be removed)
119 static float video_rc_qsquish=1.0;
120 static float video_rc_qmod_amp=0;
121 static int video_rc_qmod_freq=0;
123 static char *video_rc_override_string=NULL;
124 static char *video_rc_eq="tex^qComp";
125 static float video_rc_buffer_aggressivity=1.0;
126 static int me_method = ME_EPZS;
127 static int video_disable = 0;
128 static int video_discard = 0;
129 static int video_codec_id = CODEC_ID_NONE;
130 static int video_codec_tag = 0;
131 static int same_quality = 0;
132 static int do_deinterlace = 0;
133 static int workaround_bugs = FF_BUG_AUTODETECT;
134 static int packet_size = 0;
135 static int error_rate = 0;
136 static int strict = 0;
137 static int top_field_first = -1;
138 static int sc_threshold = 0;
139 static int me_threshold = 0;
140 static int mb_threshold = 0;
141 static int intra_dc_precision = 8;
142 static int me_penalty_compensation= 256;
143 static int frame_skip_threshold= 0;
144 static int frame_skip_factor= 0;
145 static int frame_skip_exp= 0;
146 static int loop_input = 0;
147 static int loop_output = AVFMT_NOOUTPUTLOOP;
148 static int qp_hist = 0;
150 static int intra_only = 0;
151 static int audio_sample_rate = 44100;
152 static int audio_bit_rate = 64000;
153 #define QSCALE_NONE -99999
154 static float audio_qscale = QSCALE_NONE;
155 static int audio_disable = 0;
156 static int audio_channels = 1;
157 static int audio_codec_id = CODEC_ID_NONE;
158 static int audio_codec_tag = 0;
159 static char *audio_language = NULL;
161 static int subtitle_codec_id = CODEC_ID_NONE;
162 static char *subtitle_language = NULL;
164 static float mux_preload= 0.5;
165 static float mux_max_delay= 0.7;
167 static int64_t recording_time = 0;
168 static int64_t start_time = 0;
169 static int64_t rec_timestamp = 0;
170 static int64_t input_ts_offset = 0;
171 static int file_overwrite = 0;
172 static char *str_title = NULL;
173 static char *str_author = NULL;
174 static char *str_copyright = NULL;
175 static char *str_comment = NULL;
176 static char *str_album = NULL;
177 static int do_benchmark = 0;
178 static int do_hex_dump = 0;
179 static int do_pkt_dump = 0;
180 static int do_psnr = 0;
181 static int do_vstats = 0;
182 static int do_pass = 0;
183 static char *pass_logfilename = NULL;
184 static int audio_stream_copy = 0;
185 static int video_stream_copy = 0;
186 static int subtitle_stream_copy = 0;
187 static int video_sync_method= 1;
188 static int audio_sync_method= 0;
189 static int copy_ts= 0;
190 static int opt_shortest = 0; //
191 static int video_global_header = 0;
193 static int rate_emu = 0;
196 static const char *video_grab_format = "bktr";
198 #ifdef CONFIG_VIDEO4LINUX2
199 static const char *video_grab_format = "video4linux2";
201 static const char *video_grab_format = "video4linux";
204 static char *video_device = NULL;
205 static char *grab_device = NULL;
206 static int video_channel = 0;
207 static char *video_standard = "ntsc";
209 static const char *audio_grab_format = "audio_device";
210 static char *audio_device = NULL;
211 static int audio_volume = 256;
213 static int using_stdin = 0;
214 static int using_vhook = 0;
215 static int verbose = 1;
216 static int thread_count= 1;
217 static int q_pressed = 0;
218 static int64_t video_size = 0;
219 static int64_t audio_size = 0;
220 static int64_t extra_size = 0;
221 static int nb_frames_dup = 0;
222 static int nb_frames_drop = 0;
223 static int input_sync;
224 static int limit_filesize = 0; //
226 static int pgmyuv_compatibility_hack=0;
227 static int dts_delta_threshold = 10;
229 static int sws_flags = SWS_BICUBIC;
231 const char **opt_names=NULL;
232 int opt_name_count=0;
233 AVCodecContext *avctx_opts;
234 AVFormatContext *avformat_opts;
236 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
237 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
238 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
240 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
242 struct AVInputStream;
244 typedef struct AVOutputStream {
245 int file_index; /* file index */
246 int index; /* stream index in the output file */
247 int source_index; /* AVInputStream index */
248 AVStream *st; /* stream in the output file */
249 int encoding_needed; /* true if encoding needed for this stream */
251 /* input pts and corresponding output pts
253 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
254 struct AVInputStream *sync_ist; /* input stream to sync against */
255 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
258 AVFrame pict_tmp; /* temporary image for resampling */
259 struct SwsContext *img_resample_ctx; /* for image resampling */
263 int topBand; /* cropping area sizes */
267 int padtop; /* padding area sizes */
274 ReSampleContext *resample; /* for audio resampling */
275 FifoBuffer fifo; /* for compression: one audio fifo per codec */
279 typedef struct AVInputStream {
283 int discard; /* true if stream data should be discarded */
284 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
285 int64_t sample_index; /* current sample */
287 int64_t start; /* time when read started */
288 unsigned long frame; /* current frame */
289 int64_t next_pts; /* synthetic pts for cases where pkt.pts
291 int64_t pts; /* current pts */
292 int is_start; /* is 1 at the start and after a discontinuity */
295 typedef struct AVInputFile {
296 int eof_reached; /* true if eof reached */
297 int ist_index; /* index of first stream in ist_table */
298 int buffer_size; /* current total buffer size */
299 int buffer_size_max; /* buffer size at which we consider we can stop
301 int nb_streams; /* nb streams we are aware of */
306 /* init terminal so that we can grab keys */
307 static struct termios oldtty;
309 static void term_exit(void)
311 tcsetattr (0, TCSANOW, &oldtty);
314 static volatile sig_atomic_t received_sigterm = 0;
317 sigterm_handler(int sig)
319 received_sigterm = sig;
323 static void term_init(void)
330 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
331 |INLCR|IGNCR|ICRNL|IXON);
332 tty.c_oflag |= OPOST;
333 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
334 tty.c_cflag &= ~(CSIZE|PARENB);
339 tcsetattr (0, TCSANOW, &tty);
341 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
342 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
343 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
345 register a function to be called at normal program termination
348 #ifdef CONFIG_BEOS_NETSERVER
349 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
353 /* read a key without blocking */
354 static int read_key(void)
358 #ifndef CONFIG_BEOS_NETSERVER
366 n = select(1, &rfds, NULL, NULL, &tv);
378 static int decode_interrupt_cb(void)
380 return q_pressed || (q_pressed = read_key() == 'q');
385 static volatile int received_sigterm = 0;
387 /* no interactive support */
388 static void term_exit(void)
392 static void term_init(void)
396 static int read_key(void)
403 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
408 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
411 /* copy stream format */
412 s->nb_streams = ic->nb_streams;
413 for(i=0;i<ic->nb_streams;i++) {
416 // FIXME: a more elegant solution is needed
417 st = av_mallocz(sizeof(AVStream));
418 memcpy(st, ic->streams[i], sizeof(AVStream));
419 st->codec = avcodec_alloc_context();
420 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
424 av_close_input_file(ic);
429 get_sync_ipts(const AVOutputStream *ost)
431 const AVInputStream *ist = ost->sync_ist;
432 return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
435 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
437 AVPacket new_pkt= *pkt;
438 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
439 &new_pkt.data, &new_pkt.size,
440 pkt->data, pkt->size,
441 pkt->flags & PKT_FLAG_KEY);
444 new_pkt.destruct= av_destruct_packet;
451 av_interleaved_write_frame(s, pkt);
454 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
456 static void do_audio_out(AVFormatContext *s,
459 unsigned char *buf, int size)
462 static uint8_t *audio_buf = NULL;
463 static uint8_t *audio_out = NULL;
464 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
466 int size_out, frame_bytes, ret;
467 AVCodecContext *enc= ost->st->codec;
469 /* SC: dynamic allocation of buffers */
471 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
473 audio_out = av_malloc(audio_out_size);
474 if (!audio_buf || !audio_out)
475 return; /* Should signal an error ! */
477 if(audio_sync_method){
478 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
479 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
480 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
481 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
483 //FIXME resample delay
484 if(fabs(delta) > 50){
487 byte_delta= FFMAX(byte_delta, -size);
491 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
496 static uint8_t *input_tmp= NULL;
497 input_tmp= av_realloc(input_tmp, byte_delta + size);
499 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
502 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
504 memset(input_tmp, 0, byte_delta);
505 memcpy(input_tmp + byte_delta, buf, size);
509 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
511 }else if(audio_sync_method>1){
512 int comp= clip(delta, -audio_sync_method, audio_sync_method);
513 assert(ost->audio_resample);
515 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
516 // 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));
517 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
521 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
522 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
524 if (ost->audio_resample) {
526 size_out = audio_resample(ost->resample,
527 (short *)buftmp, (short *)buf,
528 size / (ist->st->codec->channels * 2));
529 size_out = size_out * enc->channels * 2;
535 /* now encode as many frames as possible */
536 if (enc->frame_size > 1) {
537 /* output resampled raw samples */
538 fifo_write(&ost->fifo, buftmp, size_out,
541 frame_bytes = enc->frame_size * 2 * enc->channels;
543 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
544 &ost->fifo.rptr) == 0) {
546 av_init_packet(&pkt);
548 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
551 pkt.stream_index= ost->index;
554 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
555 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
556 pkt.flags |= PKT_FLAG_KEY;
557 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
559 ost->sync_opts += enc->frame_size;
563 av_init_packet(&pkt);
565 ost->sync_opts += size_out / (2 * enc->channels);
567 /* output a pcm frame */
568 /* XXX: change encoding codec API to avoid this ? */
569 switch(enc->codec->id) {
570 case CODEC_ID_PCM_S32LE:
571 case CODEC_ID_PCM_S32BE:
572 case CODEC_ID_PCM_U32LE:
573 case CODEC_ID_PCM_U32BE:
574 size_out = size_out << 1;
576 case CODEC_ID_PCM_S24LE:
577 case CODEC_ID_PCM_S24BE:
578 case CODEC_ID_PCM_U24LE:
579 case CODEC_ID_PCM_U24BE:
580 case CODEC_ID_PCM_S24DAUD:
581 size_out = size_out / 2 * 3;
583 case CODEC_ID_PCM_S16LE:
584 case CODEC_ID_PCM_S16BE:
585 case CODEC_ID_PCM_U16LE:
586 case CODEC_ID_PCM_U16BE:
589 size_out = size_out >> 1;
592 ret = avcodec_encode_audio(enc, audio_out, size_out,
595 pkt.stream_index= ost->index;
598 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
599 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
600 pkt.flags |= PKT_FLAG_KEY;
601 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
605 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
609 AVPicture picture_tmp;
612 dec = ist->st->codec;
614 /* deinterlace : must be done before any resize */
615 if (do_deinterlace || using_vhook) {
618 /* create temporary picture */
619 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
620 buf = av_malloc(size);
624 picture2 = &picture_tmp;
625 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
628 if(avpicture_deinterlace(picture2, picture,
629 dec->pix_fmt, dec->width, dec->height) < 0) {
630 /* if error, do not deinterlace */
636 img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
642 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
644 if (picture != picture2)
645 *picture = *picture2;
649 /* we begin to correct av delay at this threshold */
650 #define AV_DELAY_MAX 0.100
652 static void do_subtitle_out(AVFormatContext *s,
658 static uint8_t *subtitle_out = NULL;
659 int subtitle_out_max_size = 65536;
660 int subtitle_out_size, nb, i;
664 if (pts == AV_NOPTS_VALUE) {
665 fprintf(stderr, "Subtitle packets must have a pts\n");
669 enc = ost->st->codec;
672 subtitle_out = av_malloc(subtitle_out_max_size);
675 /* Note: DVB subtitle need one packet to draw them and one other
676 packet to clear them */
677 /* XXX: signal it in the codec context ? */
678 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
683 for(i = 0; i < nb; i++) {
684 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
685 subtitle_out_max_size, sub);
687 av_init_packet(&pkt);
688 pkt.stream_index = ost->index;
689 pkt.data = subtitle_out;
690 pkt.size = subtitle_out_size;
691 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);
692 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
693 /* XXX: the pts correction is handled here. Maybe handling
694 it in the codec would be better */
696 pkt.pts += 90 * sub->start_display_time;
698 pkt.pts += 90 * sub->end_display_time;
700 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
704 static int bit_buffer_size= 1024*256;
705 static uint8_t *bit_buffer= NULL;
707 static void do_video_out(AVFormatContext *s,
713 int nb_frames, i, ret;
714 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
715 AVFrame picture_crop_temp, picture_pad_temp;
716 uint8_t *buf = NULL, *buf1 = NULL;
717 AVCodecContext *enc, *dec;
719 avcodec_get_frame_defaults(&picture_crop_temp);
720 avcodec_get_frame_defaults(&picture_pad_temp);
722 enc = ost->st->codec;
723 dec = ist->st->codec;
725 /* by default, we output a single frame */
730 if(video_sync_method){
732 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
733 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
736 else if (vdelta > 1.1)
737 nb_frames = lrintf(vdelta);
738 //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);
742 fprintf(stderr, "*** drop!\n");
743 }else if (nb_frames > 1) {
744 nb_frames_dup += nb_frames;
746 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
749 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
751 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
755 if (ost->video_crop) {
756 if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
757 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
760 formatted_picture = &picture_crop_temp;
762 formatted_picture = in_picture;
765 final_picture = formatted_picture;
766 padding_src = formatted_picture;
767 resampling_dst = &ost->pict_tmp;
768 if (ost->video_pad) {
769 final_picture = &ost->pict_tmp;
770 if (ost->video_resample) {
771 if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
772 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
775 resampling_dst = &picture_pad_temp;
779 if (ost->video_resample) {
781 final_picture = &ost->pict_tmp;
782 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
783 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
786 if (ost->video_pad) {
787 img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
788 enc->height, enc->width, enc->pix_fmt,
789 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
792 /* duplicates frame if needed */
793 for(i=0;i<nb_frames;i++) {
795 av_init_packet(&pkt);
796 pkt.stream_index= ost->index;
798 if (s->oformat->flags & AVFMT_RAWPICTURE) {
799 /* raw pictures are written as AVPicture structure to
800 avoid any copies. We support temorarily the older
802 AVFrame* old_frame = enc->coded_frame;
803 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
804 pkt.data= (uint8_t *)final_picture;
805 pkt.size= sizeof(AVPicture);
806 if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
807 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
808 if(dec->coded_frame && dec->coded_frame->key_frame)
809 pkt.flags |= PKT_FLAG_KEY;
811 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
812 enc->coded_frame = old_frame;
816 big_picture= *final_picture;
817 /* better than nothing: use input picture interlaced
819 big_picture.interlaced_frame = in_picture->interlaced_frame;
820 if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
821 if(top_field_first == -1)
822 big_picture.top_field_first = in_picture->top_field_first;
824 big_picture.top_field_first = top_field_first;
827 /* handles sameq here. This is not correct because it may
828 not be a global option */
830 big_picture.quality = ist->st->quality;
832 big_picture.quality = ost->st->quality;
834 big_picture.pict_type = 0;
835 // big_picture.pts = AV_NOPTS_VALUE;
836 big_picture.pts= ost->sync_opts;
837 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
838 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
839 ret = avcodec_encode_video(enc,
840 bit_buffer, bit_buffer_size,
842 //enc->frame_number = enc->real_pict_num;
844 pkt.data= bit_buffer;
846 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
847 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
848 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
849 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
850 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
852 if(enc->coded_frame && enc->coded_frame->key_frame)
853 pkt.flags |= PKT_FLAG_KEY;
854 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
856 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
857 // enc->frame_number-1, enc->real_pict_num, ret,
859 /* if two pass, output log */
860 if (ost->logfile && enc->stats_out) {
861 fprintf(ost->logfile, "%s", enc->stats_out);
873 static double psnr(double d){
874 if(d==0) return INFINITY;
875 return -10.0*log(d)/log(10.0);
878 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
881 static FILE *fvstats=NULL;
888 double ti1, bitrate, avg_bitrate;
892 today = localtime(&today2);
893 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
896 fvstats = fopen(filename,"w");
904 enc = ost->st->codec;
905 if (enc->codec_type == CODEC_TYPE_VIDEO) {
906 frame_number = ost->frame_number;
907 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
908 if (enc->flags&CODEC_FLAG_PSNR)
909 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
911 fprintf(fvstats,"f_size= %6d ", frame_size);
912 /* compute pts value */
913 ti1 = ost->sync_opts * av_q2d(enc->time_base);
917 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
918 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
919 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
920 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
921 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
925 static void print_report(AVFormatContext **output_files,
926 AVOutputStream **ost_table, int nb_ostreams,
931 AVFormatContext *oc, *os;
934 int frame_number, vid, i;
935 double bitrate, ti1, pts;
936 static int64_t last_time = -1;
937 static int qp_histogram[52];
939 if (!is_last_report) {
941 /* display the report every 0.5 seconds */
942 cur_time = av_gettime();
943 if (last_time == -1) {
944 last_time = cur_time;
947 if ((cur_time - last_time) < 500000)
949 last_time = cur_time;
953 oc = output_files[0];
955 total_size = url_ftell(&oc->pb);
960 for(i=0;i<nb_ostreams;i++) {
962 os = output_files[ost->file_index];
963 enc = ost->st->codec;
964 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
965 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
966 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
968 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
969 frame_number = ost->frame_number;
970 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
971 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
973 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
974 if(qp_hist && enc->coded_frame){
976 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
977 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
980 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
982 if (enc->flags&CODEC_FLAG_PSNR){
984 double error, error_sum=0;
985 double scale, scale_sum=0;
986 char type[3]= {'Y','U','V'};
987 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
990 error= enc->error[j];
991 scale= enc->width*enc->height*255.0*255.0*frame_number;
993 error= enc->coded_frame->error[j];
994 scale= enc->width*enc->height*255.0*255.0;
999 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1001 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1005 /* compute min output value */
1006 pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1007 if ((pts < ti1) && (pts > 0))
1013 if (verbose || is_last_report) {
1014 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1016 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1017 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1018 (double)total_size / 1024, ti1, bitrate);
1021 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1022 nb_frames_dup, nb_frames_drop);
1025 fprintf(stderr, "%s \r", buf);
1030 if (is_last_report && verbose >= 0){
1031 int64_t raw= audio_size + video_size + extra_size;
1032 fprintf(stderr, "\n");
1033 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1037 100.0*(total_size - raw)/raw
1042 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1043 static int output_packet(AVInputStream *ist, int ist_index,
1044 AVOutputStream **ost_table, int nb_ostreams,
1045 const AVPacket *pkt)
1047 AVFormatContext *os;
1048 AVOutputStream *ost;
1052 int data_size, got_picture;
1054 void *buffer_to_free;
1055 static unsigned int samples_size= 0;
1056 static short *samples= NULL;
1057 AVSubtitle subtitle, *subtitle_to_free;
1061 ist->pts= ist->next_pts; // needed for last packet if vsync=0
1062 } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1063 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1065 // assert(ist->pts == ist->next_pts);
1079 /* decode the packet if needed */
1080 data_buf = NULL; /* fail safe */
1082 subtitle_to_free = NULL;
1083 if (ist->decoding_needed) {
1084 switch(ist->st->codec->codec_type) {
1085 case CODEC_TYPE_AUDIO:{
1087 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1088 /* XXX: could avoid copy if PCM 16 bits with same
1089 endianness as CPU */
1090 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1096 /* Some bug in mpeg audio decoder gives */
1097 /* data_size < 0, it seems they are overflows */
1098 if (data_size <= 0) {
1099 /* no audio frame */
1102 data_buf = (uint8_t *)samples;
1103 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1104 (ist->st->codec->sample_rate * ist->st->codec->channels);
1106 case CODEC_TYPE_VIDEO:
1107 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1108 /* XXX: allocate picture correctly */
1109 avcodec_get_frame_defaults(&picture);
1111 ret = avcodec_decode_video(ist->st->codec,
1112 &picture, &got_picture, ptr, len);
1113 ist->st->quality= picture.quality;
1117 /* no picture yet */
1118 goto discard_packet;
1120 if (ist->st->codec->time_base.num != 0) {
1121 ist->next_pts += ((int64_t)AV_TIME_BASE *
1122 ist->st->codec->time_base.num) /
1123 ist->st->codec->time_base.den;
1127 case CODEC_TYPE_SUBTITLE:
1128 ret = avcodec_decode_subtitle(ist->st->codec,
1129 &subtitle, &got_subtitle, ptr, len);
1132 if (!got_subtitle) {
1133 goto discard_packet;
1135 subtitle_to_free = &subtitle;
1142 switch(ist->st->codec->codec_type) {
1143 case CODEC_TYPE_AUDIO:
1144 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1145 (ist->st->codec->sample_rate * ist->st->codec->channels);
1147 case CODEC_TYPE_VIDEO:
1148 if (ist->st->codec->time_base.num != 0) {
1149 ist->next_pts += ((int64_t)AV_TIME_BASE *
1150 ist->st->codec->time_base.num) /
1151 ist->st->codec->time_base.den;
1161 buffer_to_free = NULL;
1162 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1163 pre_process_video_frame(ist, (AVPicture *)&picture,
1167 // preprocess audio (volume)
1168 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1169 if (audio_volume != 256) {
1172 for(i=0;i<(data_size / sizeof(short));i++) {
1173 int v = ((*volp) * audio_volume + 128) >> 8;
1174 if (v < -32768) v = -32768;
1175 if (v > 32767) v = 32767;
1181 /* frame rate emulation */
1182 if (ist->st->codec->rate_emu) {
1183 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1184 int64_t now = av_gettime() - ist->start;
1192 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1193 is the one of the next displayed one */
1194 /* XXX: add mpeg4 too ? */
1195 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1196 if (ist->st->codec->pict_type != B_TYPE) {
1198 tmp = ist->last_ip_pts;
1199 ist->last_ip_pts = ist->frac_pts.val;
1200 ist->frac_pts.val = tmp;
1204 /* if output time reached then transcode raw format,
1205 encode packets and output them */
1206 if (start_time == 0 || ist->pts >= start_time)
1207 for(i=0;i<nb_ostreams;i++) {
1211 if (ost->source_index == ist_index) {
1212 os = output_files[ost->file_index];
1215 printf("%d: got pts=%0.3f %0.3f\n", i,
1216 (double)pkt->pts / AV_TIME_BASE,
1217 ((double)ist->pts / AV_TIME_BASE) -
1218 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1220 /* set the input output pts pairs */
1221 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1223 if (ost->encoding_needed) {
1224 switch(ost->st->codec->codec_type) {
1225 case CODEC_TYPE_AUDIO:
1226 do_audio_out(os, ost, ist, data_buf, data_size);
1228 case CODEC_TYPE_VIDEO:
1229 do_video_out(os, ost, ist, &picture, &frame_size);
1230 video_size += frame_size;
1231 if (do_vstats && frame_size)
1232 do_video_stats(os, ost, frame_size);
1234 case CODEC_TYPE_SUBTITLE:
1235 do_subtitle_out(os, ost, ist, &subtitle,
1242 AVFrame avframe; //FIXME/XXX remove this
1244 av_init_packet(&opkt);
1246 /* no reencoding needed : output the packet directly */
1247 /* force the input stream PTS */
1249 avcodec_get_frame_defaults(&avframe);
1250 ost->st->codec->coded_frame= &avframe;
1251 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1253 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1254 audio_size += data_size;
1255 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1256 video_size += data_size;
1260 opkt.stream_index= ost->index;
1261 if(pkt->pts != AV_NOPTS_VALUE)
1262 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);
1264 opkt.pts= AV_NOPTS_VALUE;
1268 if (pkt->dts == AV_NOPTS_VALUE)
1269 dts = ist->next_pts;
1271 dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1272 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1274 opkt.flags= pkt->flags;
1276 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1277 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1278 opkt.destruct= av_destruct_packet;
1280 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1281 ost->st->codec->frame_number++;
1282 ost->frame_number++;
1283 av_free_packet(&opkt);
1287 av_free(buffer_to_free);
1288 /* XXX: allocate the subtitles in the codec ? */
1289 if (subtitle_to_free) {
1290 if (subtitle_to_free->rects != NULL) {
1291 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1292 av_free(subtitle_to_free->rects[i].bitmap);
1293 av_free(subtitle_to_free->rects[i].rgba_palette);
1295 av_freep(&subtitle_to_free->rects);
1297 subtitle_to_free->num_rects = 0;
1298 subtitle_to_free = NULL;
1305 for(i=0;i<nb_ostreams;i++) {
1307 if (ost->source_index == ist_index) {
1308 AVCodecContext *enc= ost->st->codec;
1309 os = output_files[ost->file_index];
1311 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1313 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1316 if (ost->encoding_needed) {
1320 av_init_packet(&pkt);
1321 pkt.stream_index= ost->index;
1323 switch(ost->st->codec->codec_type) {
1324 case CODEC_TYPE_AUDIO:
1325 fifo_bytes = fifo_size(&ost->fifo, NULL);
1327 /* encode any samples remaining in fifo */
1328 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1329 int fs_tmp = enc->frame_size;
1330 enc->frame_size = fifo_bytes / (2 * enc->channels);
1331 if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1332 &ost->fifo.rptr) == 0) {
1333 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1335 enc->frame_size = fs_tmp;
1338 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1341 pkt.flags |= PKT_FLAG_KEY;
1343 case CODEC_TYPE_VIDEO:
1344 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1346 if(enc->coded_frame && enc->coded_frame->key_frame)
1347 pkt.flags |= PKT_FLAG_KEY;
1348 if (ost->logfile && enc->stats_out) {
1349 fprintf(ost->logfile, "%s", enc->stats_out);
1358 pkt.data= bit_buffer;
1360 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1361 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1362 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1376 * The following code is the main loop of the file converter
1378 static int av_encode(AVFormatContext **output_files,
1379 int nb_output_files,
1380 AVFormatContext **input_files,
1382 AVStreamMap *stream_maps, int nb_stream_maps)
1384 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1385 AVFormatContext *is, *os;
1386 AVCodecContext *codec, *icodec;
1387 AVOutputStream *ost, **ost_table = NULL;
1388 AVInputStream *ist, **ist_table = NULL;
1389 AVInputFile *file_table;
1390 AVFormatContext *stream_no_data;
1393 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1397 /* input stream init */
1399 for(i=0;i<nb_input_files;i++) {
1400 is = input_files[i];
1401 file_table[i].ist_index = j;
1402 file_table[i].nb_streams = is->nb_streams;
1403 j += is->nb_streams;
1407 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1411 for(i=0;i<nb_istreams;i++) {
1412 ist = av_mallocz(sizeof(AVInputStream));
1418 for(i=0;i<nb_input_files;i++) {
1419 is = input_files[i];
1420 for(k=0;k<is->nb_streams;k++) {
1421 ist = ist_table[j++];
1422 ist->st = is->streams[k];
1423 ist->file_index = i;
1425 ist->discard = 1; /* the stream is discarded by default
1428 if (ist->st->codec->rate_emu) {
1429 ist->start = av_gettime();
1435 /* output stream init */
1437 for(i=0;i<nb_output_files;i++) {
1438 os = output_files[i];
1439 nb_ostreams += os->nb_streams;
1441 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1442 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1446 /* Sanity check the mapping args -- do the input files & streams exist? */
1447 for(i=0;i<nb_stream_maps;i++) {
1448 int fi = stream_maps[i].file_index;
1449 int si = stream_maps[i].stream_index;
1451 if (fi < 0 || fi > nb_input_files - 1 ||
1452 si < 0 || si > file_table[fi].nb_streams - 1) {
1453 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1456 fi = stream_maps[i].sync_file_index;
1457 si = stream_maps[i].sync_stream_index;
1458 if (fi < 0 || fi > nb_input_files - 1 ||
1459 si < 0 || si > file_table[fi].nb_streams - 1) {
1460 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1465 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1468 for(i=0;i<nb_ostreams;i++) {
1469 ost = av_mallocz(sizeof(AVOutputStream));
1476 for(k=0;k<nb_output_files;k++) {
1477 os = output_files[k];
1478 for(i=0;i<os->nb_streams;i++) {
1480 ost = ost_table[n++];
1481 ost->file_index = k;
1483 ost->st = os->streams[i];
1484 if (nb_stream_maps > 0) {
1485 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1486 stream_maps[n-1].stream_index;
1488 /* Sanity check that the stream types match */
1489 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1490 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1491 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1492 ost->file_index, ost->index);
1497 /* get corresponding input stream index : we select the first one with the right type */
1499 for(j=0;j<nb_istreams;j++) {
1502 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1503 ost->source_index = j;
1510 /* try again and reuse existing stream */
1511 for(j=0;j<nb_istreams;j++) {
1513 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1514 ost->source_index = j;
1519 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1520 ost->file_index, ost->index);
1525 ist = ist_table[ost->source_index];
1527 ost->sync_ist = (nb_stream_maps > 0) ?
1528 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1529 stream_maps[n-1].sync_stream_index] : ist;
1533 /* for each output stream, we compute the right encoding parameters */
1534 for(i=0;i<nb_ostreams;i++) {
1536 ist = ist_table[ost->source_index];
1538 codec = ost->st->codec;
1539 icodec = ist->st->codec;
1541 if (ost->st->stream_copy) {
1542 /* if stream_copy is selected, no need to decode or encode */
1543 codec->codec_id = icodec->codec_id;
1544 codec->codec_type = icodec->codec_type;
1545 if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1546 codec->bit_rate = icodec->bit_rate;
1547 codec->extradata= icodec->extradata;
1548 codec->extradata_size= icodec->extradata_size;
1549 codec->time_base = icodec->time_base;
1550 switch(codec->codec_type) {
1551 case CODEC_TYPE_AUDIO:
1552 codec->sample_rate = icodec->sample_rate;
1553 codec->channels = icodec->channels;
1554 codec->frame_size = icodec->frame_size;
1555 codec->block_align= icodec->block_align;
1557 case CODEC_TYPE_VIDEO:
1558 codec->pix_fmt = icodec->pix_fmt;
1559 codec->width = icodec->width;
1560 codec->height = icodec->height;
1561 codec->has_b_frames = icodec->has_b_frames;
1563 case CODEC_TYPE_SUBTITLE:
1569 switch(codec->codec_type) {
1570 case CODEC_TYPE_AUDIO:
1571 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1574 if (codec->channels == icodec->channels &&
1575 codec->sample_rate == icodec->sample_rate) {
1576 ost->audio_resample = 0;
1578 if (codec->channels != icodec->channels &&
1579 (icodec->codec_id == CODEC_ID_AC3 ||
1580 icodec->codec_id == CODEC_ID_DTS)) {
1581 /* Special case for 5:1 AC3 and DTS input */
1582 /* and mono or stereo output */
1583 /* Request specific number of channels */
1584 icodec->channels = codec->channels;
1585 if (codec->sample_rate == icodec->sample_rate)
1586 ost->audio_resample = 0;
1588 ost->audio_resample = 1;
1591 ost->audio_resample = 1;
1594 if(audio_sync_method>1)
1595 ost->audio_resample = 1;
1597 if(ost->audio_resample){
1598 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1599 codec->sample_rate, icodec->sample_rate);
1601 printf("Can't resample. Aborting.\n");
1605 ist->decoding_needed = 1;
1606 ost->encoding_needed = 1;
1608 case CODEC_TYPE_VIDEO:
1609 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1610 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1611 ost->video_resample = ((codec->width != icodec->width -
1612 (frame_leftBand + frame_rightBand) +
1613 (frame_padleft + frame_padright)) ||
1614 (codec->height != icodec->height -
1615 (frame_topBand + frame_bottomBand) +
1616 (frame_padtop + frame_padbottom)) ||
1617 (codec->pix_fmt != icodec->pix_fmt));
1618 if (ost->video_crop) {
1619 ost->topBand = frame_topBand;
1620 ost->leftBand = frame_leftBand;
1622 if (ost->video_pad) {
1623 ost->padtop = frame_padtop;
1624 ost->padleft = frame_padleft;
1625 ost->padbottom = frame_padbottom;
1626 ost->padright = frame_padright;
1627 if (!ost->video_resample) {
1628 avcodec_get_frame_defaults(&ost->pict_tmp);
1629 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1630 codec->width, codec->height ) )
1634 if (ost->video_resample) {
1635 avcodec_get_frame_defaults(&ost->pict_tmp);
1636 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1637 codec->width, codec->height ) )
1640 ost->img_resample_ctx = sws_getContext(
1641 icodec->width - (frame_leftBand + frame_rightBand),
1642 icodec->height - (frame_topBand + frame_bottomBand),
1644 codec->width - (frame_padleft + frame_padright),
1645 codec->height - (frame_padtop + frame_padbottom),
1647 sws_flags, NULL, NULL, NULL);
1648 if (ost->img_resample_ctx == NULL) {
1649 fprintf(stderr, "Cannot get resampling context\n");
1652 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1654 ost->encoding_needed = 1;
1655 ist->decoding_needed = 1;
1657 case CODEC_TYPE_SUBTITLE:
1658 ost->encoding_needed = 1;
1659 ist->decoding_needed = 1;
1666 if (ost->encoding_needed &&
1667 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1668 char logfilename[1024];
1673 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1675 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1676 if (codec->flags & CODEC_FLAG_PASS1) {
1677 f = fopen(logfilename, "w");
1679 perror(logfilename);
1684 /* read the log file */
1685 f = fopen(logfilename, "r");
1687 perror(logfilename);
1690 fseek(f, 0, SEEK_END);
1692 fseek(f, 0, SEEK_SET);
1693 logbuffer = av_malloc(size + 1);
1695 fprintf(stderr, "Could not allocate log buffer\n");
1698 size = fread(logbuffer, 1, size, f);
1700 logbuffer[size] = '\0';
1701 codec->stats_in = logbuffer;
1705 if(codec->codec_type == CODEC_TYPE_VIDEO){
1706 int size= codec->width * codec->height;
1707 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1712 bit_buffer = av_malloc(bit_buffer_size);
1716 /* dump the file output parameters - cannot be done before in case
1718 for(i=0;i<nb_output_files;i++) {
1719 dump_format(output_files[i], i, output_files[i]->filename, 1);
1722 /* dump the stream mapping */
1724 fprintf(stderr, "Stream mapping:\n");
1725 for(i=0;i<nb_ostreams;i++) {
1727 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1728 ist_table[ost->source_index]->file_index,
1729 ist_table[ost->source_index]->index,
1732 if (ost->sync_ist != ist_table[ost->source_index])
1733 fprintf(stderr, " [sync #%d.%d]",
1734 ost->sync_ist->file_index,
1735 ost->sync_ist->index);
1736 fprintf(stderr, "\n");
1740 /* open each encoder */
1741 for(i=0;i<nb_ostreams;i++) {
1743 if (ost->encoding_needed) {
1745 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1747 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1748 ost->file_index, ost->index);
1751 if (avcodec_open(ost->st->codec, codec) < 0) {
1752 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1753 ost->file_index, ost->index);
1756 extra_size += ost->st->codec->extradata_size;
1760 /* open each decoder */
1761 for(i=0;i<nb_istreams;i++) {
1763 if (ist->decoding_needed) {
1765 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1767 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1768 ist->st->codec->codec_id, ist->file_index, ist->index);
1771 if (avcodec_open(ist->st->codec, codec) < 0) {
1772 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1773 ist->file_index, ist->index);
1776 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1777 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1782 for(i=0;i<nb_istreams;i++) {
1784 is = input_files[ist->file_index];
1786 ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1787 if(ist->st->start_time == AV_NOPTS_VALUE)
1789 if(input_files_ts_offset[ist->file_index])
1790 ist->next_pts= AV_NOPTS_VALUE;
1794 /* compute buffer size max (should use a complete heuristic) */
1795 for(i=0;i<nb_input_files;i++) {
1796 file_table[i].buffer_size_max = 2048;
1799 /* set meta data information from input file if required */
1800 for (i=0;i<nb_meta_data_maps;i++) {
1801 AVFormatContext *out_file;
1802 AVFormatContext *in_file;
1804 int out_file_index = meta_data_maps[i].out_file;
1805 int in_file_index = meta_data_maps[i].in_file;
1806 if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1807 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1811 if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1812 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1817 out_file = output_files[out_file_index];
1818 in_file = input_files[in_file_index];
1820 strcpy(out_file->title, in_file->title);
1821 strcpy(out_file->author, in_file->author);
1822 strcpy(out_file->copyright, in_file->copyright);
1823 strcpy(out_file->comment, in_file->comment);
1824 strcpy(out_file->album, in_file->album);
1825 out_file->year = in_file->year;
1826 out_file->track = in_file->track;
1827 strcpy(out_file->genre, in_file->genre);
1830 /* open files and write file headers */
1831 for(i=0;i<nb_output_files;i++) {
1832 os = output_files[i];
1833 if (av_write_header(os) < 0) {
1834 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1841 if ( !using_stdin && verbose >= 0) {
1842 fprintf(stderr, "Press [q] to stop encoding\n");
1843 url_set_interrupt_cb(decode_interrupt_cb);
1851 for(; received_sigterm == 0;) {
1852 int file_index, ist_index;
1860 /* if 'q' pressed, exits */
1864 /* read_key() returns 0 on EOF */
1870 /* select the stream that we must read now by looking at the
1871 smallest output pts */
1873 for(i=0;i<nb_ostreams;i++) {
1876 os = output_files[ost->file_index];
1877 ist = ist_table[ost->source_index];
1878 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1879 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1881 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1882 ipts = (double)ist->pts;
1883 if (!file_table[ist->file_index].eof_reached){
1884 if(ipts < ipts_min) {
1886 if(input_sync ) file_index = ist->file_index;
1888 if(opts < opts_min) {
1890 if(!input_sync) file_index = ist->file_index;
1893 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1898 /* if none, if is finished */
1899 if (file_index < 0) {
1903 /* finish if recording time exhausted */
1904 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1907 /* finish if limit size exhausted */
1908 if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1911 /* read a frame from it and output it in the fifo */
1912 is = input_files[file_index];
1913 if (av_read_frame(is, &pkt) < 0) {
1914 file_table[file_index].eof_reached = 1;
1915 if (opt_shortest) break; else continue; //
1919 stream_no_data = is;
1924 av_pkt_dump(stdout, &pkt, do_hex_dump);
1926 /* the following test is needed in case new streams appear
1927 dynamically in stream : we ignore them */
1928 if (pkt.stream_index >= file_table[file_index].nb_streams)
1929 goto discard_packet;
1930 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1931 ist = ist_table[ist_index];
1933 goto discard_packet;
1935 // 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);
1936 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1937 int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1938 if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1939 input_files_ts_offset[ist->file_index]-= delta;
1941 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1942 for(i=0; i<file_table[file_index].nb_streams; i++){
1943 int index= file_table[file_index].ist_index + i;
1944 ist_table[index]->next_pts += delta;
1945 ist_table[index]->is_start=1;
1950 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1951 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1954 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1955 ist->file_index, ist->index);
1957 av_free_packet(&pkt);
1962 av_free_packet(&pkt);
1964 /* dump report by using the output first video and audio streams */
1965 print_report(output_files, ost_table, nb_ostreams, 0);
1968 /* at the end of stream, we must flush the decoder buffers */
1969 for(i=0;i<nb_istreams;i++) {
1971 if (ist->decoding_needed) {
1972 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1978 /* write the trailer if needed and close file */
1979 for(i=0;i<nb_output_files;i++) {
1980 os = output_files[i];
1981 av_write_trailer(os);
1984 /* dump report by using the first video and audio streams */
1985 print_report(output_files, ost_table, nb_ostreams, 1);
1987 /* close each encoder */
1988 for(i=0;i<nb_ostreams;i++) {
1990 if (ost->encoding_needed) {
1991 av_freep(&ost->st->codec->stats_in);
1992 avcodec_close(ost->st->codec);
1996 /* close each decoder */
1997 for(i=0;i<nb_istreams;i++) {
1999 if (ist->decoding_needed) {
2000 avcodec_close(ist->st->codec);
2008 av_freep(&bit_buffer);
2009 av_free(file_table);
2012 for(i=0;i<nb_istreams;i++) {
2019 for(i=0;i<nb_ostreams;i++) {
2023 fclose(ost->logfile);
2024 ost->logfile = NULL;
2026 fifo_free(&ost->fifo); /* works even if fifo is not
2027 initialized but set to zero */
2028 av_free(ost->pict_tmp.data[0]);
2029 if (ost->video_resample)
2030 sws_freeContext(ost->img_resample_ctx);
2031 if (ost->audio_resample)
2032 audio_resample_close(ost->resample);
2045 int file_read(const char *filename)
2048 unsigned char buffer[1024];
2051 if (url_open(&h, filename, O_RDONLY) < 0) {
2052 printf("could not open '%s'\n", filename);
2056 len = url_read(h, buffer, sizeof(buffer));
2059 for(i=0;i<len;i++) putchar(buffer[i]);
2066 static void opt_image_format(const char *arg)
2070 for(f = first_image_format; f != NULL; f = f->next) {
2071 if (!strcmp(arg, f->name))
2075 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2081 static void opt_format(const char *arg)
2083 /* compatibility stuff for pgmyuv */
2084 if (!strcmp(arg, "pgmyuv")) {
2085 pgmyuv_compatibility_hack=1;
2086 // opt_image_format(arg);
2090 file_iformat = av_find_input_format(arg);
2091 file_oformat = guess_format(arg, NULL, NULL);
2092 if (!file_iformat && !file_oformat) {
2093 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2098 static void opt_video_rc_eq(char *arg)
2103 static void opt_video_rc_override_string(char *arg)
2105 video_rc_override_string = arg;
2109 static void opt_workaround_bugs(const char *arg)
2111 workaround_bugs = atoi(arg);
2114 static void opt_me_threshold(const char *arg)
2116 me_threshold = atoi(arg);
2119 static void opt_mb_threshold(const char *arg)
2121 mb_threshold = atoi(arg);
2124 static void opt_verbose(const char *arg)
2126 verbose = atoi(arg);
2127 av_log_set_level(atoi(arg));
2130 static void opt_frame_rate(const char *arg)
2132 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2133 fprintf(stderr, "Incorrect frame rate\n");
2138 static void opt_frame_crop_top(const char *arg)
2140 frame_topBand = atoi(arg);
2141 if (frame_topBand < 0) {
2142 fprintf(stderr, "Incorrect top crop size\n");
2145 if ((frame_topBand % 2) != 0) {
2146 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2149 if ((frame_topBand) >= frame_height){
2150 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2153 frame_height -= frame_topBand;
2156 static void opt_frame_crop_bottom(const char *arg)
2158 frame_bottomBand = atoi(arg);
2159 if (frame_bottomBand < 0) {
2160 fprintf(stderr, "Incorrect bottom crop size\n");
2163 if ((frame_bottomBand % 2) != 0) {
2164 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2167 if ((frame_bottomBand) >= frame_height){
2168 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2171 frame_height -= frame_bottomBand;
2174 static void opt_frame_crop_left(const char *arg)
2176 frame_leftBand = atoi(arg);
2177 if (frame_leftBand < 0) {
2178 fprintf(stderr, "Incorrect left crop size\n");
2181 if ((frame_leftBand % 2) != 0) {
2182 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2185 if ((frame_leftBand) >= frame_width){
2186 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2189 frame_width -= frame_leftBand;
2192 static void opt_frame_crop_right(const char *arg)
2194 frame_rightBand = atoi(arg);
2195 if (frame_rightBand < 0) {
2196 fprintf(stderr, "Incorrect right crop size\n");
2199 if ((frame_rightBand % 2) != 0) {
2200 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2203 if ((frame_rightBand) >= frame_width){
2204 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2207 frame_width -= frame_rightBand;
2210 static void opt_frame_size(const char *arg)
2212 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2213 fprintf(stderr, "Incorrect frame size\n");
2216 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2217 fprintf(stderr, "Frame size must be a multiple of 2\n");
2223 #define SCALEBITS 10
2224 #define ONE_HALF (1 << (SCALEBITS - 1))
2225 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2227 #define RGB_TO_Y(r, g, b) \
2228 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2229 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2231 #define RGB_TO_U(r1, g1, b1, shift)\
2232 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2233 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2235 #define RGB_TO_V(r1, g1, b1, shift)\
2236 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2237 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2239 static void opt_pad_color(const char *arg) {
2240 /* Input is expected to be six hex digits similar to
2241 how colors are expressed in html tags (but without the #) */
2242 int rgb = strtol(arg, NULL, 16);
2246 g = ((rgb >> 8) & 255);
2249 padcolor[0] = RGB_TO_Y(r,g,b);
2250 padcolor[1] = RGB_TO_U(r,g,b,0);
2251 padcolor[2] = RGB_TO_V(r,g,b,0);
2254 static void opt_frame_pad_top(const char *arg)
2256 frame_padtop = atoi(arg);
2257 if (frame_padtop < 0) {
2258 fprintf(stderr, "Incorrect top pad size\n");
2261 if ((frame_padtop % 2) != 0) {
2262 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2267 static void opt_frame_pad_bottom(const char *arg)
2269 frame_padbottom = atoi(arg);
2270 if (frame_padbottom < 0) {
2271 fprintf(stderr, "Incorrect bottom pad size\n");
2274 if ((frame_padbottom % 2) != 0) {
2275 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2281 static void opt_frame_pad_left(const char *arg)
2283 frame_padleft = atoi(arg);
2284 if (frame_padleft < 0) {
2285 fprintf(stderr, "Incorrect left pad size\n");
2288 if ((frame_padleft % 2) != 0) {
2289 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2295 static void opt_frame_pad_right(const char *arg)
2297 frame_padright = atoi(arg);
2298 if (frame_padright < 0) {
2299 fprintf(stderr, "Incorrect right pad size\n");
2302 if ((frame_padright % 2) != 0) {
2303 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2309 static void opt_frame_pix_fmt(const char *arg)
2311 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2314 static void opt_frame_aspect_ratio(const char *arg)
2320 p = strchr(arg, ':');
2322 x = strtol(arg, (char **)&arg, 10);
2324 y = strtol(arg+1, (char **)&arg, 10);
2326 ar = (double)x / (double)y;
2328 ar = strtod(arg, (char **)&arg);
2331 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2334 frame_aspect_ratio = ar;
2337 static void opt_qscale(const char *arg)
2339 video_qscale = atof(arg);
2340 if (video_qscale <= 0 ||
2341 video_qscale > 255) {
2342 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2347 static void opt_qsquish(const char *arg)
2349 video_qsquish = atof(arg);
2350 if (video_qsquish < 0.0 ||
2351 video_qsquish > 99.0) {
2352 fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2357 static void opt_lmax(const char *arg)
2359 video_lmax = atof(arg)*FF_QP2LAMBDA;
2362 static void opt_lmin(const char *arg)
2364 video_lmin = atof(arg)*FF_QP2LAMBDA;
2367 static void opt_qmax(const char *arg)
2369 video_qmax = atoi(arg);
2370 if (video_qmax < 1 ||
2372 fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2377 static void opt_mb_lmin(const char *arg)
2379 video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2380 if (video_mb_lmin < 1 ||
2381 video_mb_lmin > FF_LAMBDA_MAX) {
2382 fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2387 static void opt_mb_lmax(const char *arg)
2389 video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2390 if (video_mb_lmax < 1 ||
2391 video_mb_lmax > FF_LAMBDA_MAX) {
2392 fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2397 static void opt_qdiff(const char *arg)
2399 video_qdiff = atoi(arg);
2400 if (video_qdiff < 0 ||
2402 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2407 static void opt_packet_size(const char *arg)
2409 packet_size= atoi(arg);
2412 static void opt_error_rate(const char *arg)
2414 error_rate= atoi(arg);
2417 static void opt_strict(const char *arg)
2422 static void opt_top_field_first(const char *arg)
2424 top_field_first= atoi(arg);
2427 static void opt_sc_threshold(const char *arg)
2429 sc_threshold= atoi(arg);
2432 static void opt_thread_count(const char *arg)
2434 thread_count= atoi(arg);
2435 #if !defined(HAVE_THREADS)
2437 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2441 static void opt_audio_bitrate(const char *arg)
2443 audio_bit_rate = atoi(arg) * 1000;
2446 static void opt_audio_rate(const char *arg)
2448 audio_sample_rate = atoi(arg);
2451 static void opt_audio_channels(const char *arg)
2453 audio_channels = atoi(arg);
2456 static void opt_video_device(const char *arg)
2458 video_device = av_strdup(arg);
2461 static void opt_grab_device(const char *arg)
2463 grab_device = av_strdup(arg);
2466 static void opt_video_channel(const char *arg)
2468 video_channel = strtol(arg, NULL, 0);
2471 static void opt_video_standard(const char *arg)
2473 video_standard = av_strdup(arg);
2476 static void opt_audio_device(const char *arg)
2478 audio_device = av_strdup(arg);
2481 static void opt_codec(int *pstream_copy, int *pcodec_id,
2482 int codec_type, const char *arg)
2486 if (!strcmp(arg, "copy")) {
2491 if (!strcmp(p->name, arg) && p->type == codec_type)
2496 fprintf(stderr, "Unknown codec '%s'\n", arg);
2504 static void opt_audio_codec(const char *arg)
2506 opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2509 static void opt_audio_tag(const char *arg)
2512 audio_codec_tag= strtol(arg, &tail, 0);
2515 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2518 static void opt_video_tag(const char *arg)
2521 video_codec_tag= strtol(arg, &tail, 0);
2524 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2527 static void add_frame_hooker(const char *arg)
2532 char *args = av_strdup(arg);
2536 argv[0] = strtok(args, " ");
2537 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2540 i = frame_hook_add(argc, argv);
2543 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2548 const char *motion_str[] = {
2561 static void opt_motion_estimation(const char *arg)
2567 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2570 if (!strcmp(*p, arg))
2574 me_method = (p - motion_str) + 1;
2577 static void opt_video_codec(const char *arg)
2579 opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2582 static void opt_subtitle_codec(const char *arg)
2584 opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2587 static void opt_map(const char *arg)
2593 m = &stream_maps[nb_stream_maps++];
2595 m->file_index = strtol(arg, (char **)&p, 0);
2599 m->stream_index = strtol(p, (char **)&p, 0);
2602 m->sync_file_index = strtol(p, (char **)&p, 0);
2605 m->sync_stream_index = strtol(p, (char **)&p, 0);
2607 m->sync_file_index = m->file_index;
2608 m->sync_stream_index = m->stream_index;
2612 static void opt_map_meta_data(const char *arg)
2618 m = &meta_data_maps[nb_meta_data_maps++];
2620 m->out_file = strtol(arg, (char **)&p, 0);
2624 m->in_file = strtol(p, (char **)&p, 0);
2627 static void opt_recording_time(const char *arg)
2629 recording_time = parse_date(arg, 1);
2632 static void opt_start_time(const char *arg)
2634 start_time = parse_date(arg, 1);
2637 static void opt_rec_timestamp(const char *arg)
2639 rec_timestamp = parse_date(arg, 0) / 1000000;
2642 static void opt_input_ts_offset(const char *arg)
2644 input_ts_offset = parse_date(arg, 1);
2647 static void opt_input_file(const char *filename)
2649 AVFormatContext *ic;
2650 AVFormatParameters params, *ap = ¶ms;
2651 int err, i, ret, rfps, rfps_base;
2654 if (!strcmp(filename, "-"))
2657 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2658 !strcmp( filename, "/dev/stdin" );
2660 /* get default parameters from command line */
2661 ic = av_alloc_format_context();
2663 memset(ap, 0, sizeof(*ap));
2664 ap->prealloced_context = 1;
2665 ap->sample_rate = audio_sample_rate;
2666 ap->channels = audio_channels;
2667 ap->time_base.den = frame_rate;
2668 ap->time_base.num = frame_rate_base;
2669 ap->width = frame_width + frame_padleft + frame_padright;
2670 ap->height = frame_height + frame_padtop + frame_padbottom;
2671 ap->image_format = image_format;
2672 ap->pix_fmt = frame_pix_fmt;
2673 ap->device = grab_device;
2674 ap->channel = video_channel;
2675 ap->standard = video_standard;
2676 ap->video_codec_id = video_codec_id;
2677 ap->audio_codec_id = audio_codec_id;
2678 if(pgmyuv_compatibility_hack)
2679 ap->video_codec_id= CODEC_ID_PGMYUV;
2681 for(i=0; i<opt_name_count; i++){
2683 double d= av_get_double(avformat_opts, opt_names[i], &opt);
2684 if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2685 av_set_double(ic, opt_names[i], d);
2687 /* open the input file with generic libav function */
2688 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2690 print_error(filename, err);
2694 ic->loop_input = loop_input;
2696 /* If not enough info to get the stream parameters, we decode the
2697 first frames to get it. (used in mpeg case for example) */
2698 ret = av_find_stream_info(ic);
2699 if (ret < 0 && verbose >= 0) {
2700 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2704 timestamp = start_time;
2705 /* add the stream start time */
2706 if (ic->start_time != AV_NOPTS_VALUE)
2707 timestamp += ic->start_time;
2709 /* if seeking requested, we execute it */
2710 if (start_time != 0) {
2711 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2713 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2714 filename, (double)timestamp / AV_TIME_BASE);
2716 /* reset seek info */
2720 /* update the current parameters so that they match the one of the input stream */
2721 for(i=0;i<ic->nb_streams;i++) {
2723 AVCodecContext *enc = ic->streams[i]->codec;
2724 #if defined(HAVE_THREADS)
2726 avcodec_thread_init(enc, thread_count);
2728 enc->thread_count= thread_count;
2729 switch(enc->codec_type) {
2730 case CODEC_TYPE_AUDIO:
2731 for(j=0; j<opt_name_count; j++){
2733 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2734 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2735 av_set_double(enc, opt_names[j], d);
2737 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2738 audio_channels = enc->channels;
2739 audio_sample_rate = enc->sample_rate;
2741 ic->streams[i]->discard= AVDISCARD_ALL;
2743 case CODEC_TYPE_VIDEO:
2744 for(j=0; j<opt_name_count; j++){
2746 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2747 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2748 av_set_double(enc, opt_names[j], d);
2750 frame_height = enc->height;
2751 frame_width = enc->width;
2752 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2753 frame_pix_fmt = enc->pix_fmt;
2754 rfps = ic->streams[i]->r_frame_rate.num;
2755 rfps_base = ic->streams[i]->r_frame_rate.den;
2756 enc->workaround_bugs = workaround_bugs;
2757 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2759 enc->debug |= FF_DEBUG_MV;
2761 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2764 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2765 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2767 (float)rfps / rfps_base, rfps, rfps_base);
2769 /* update the current frame rate to match the stream frame rate */
2771 frame_rate_base = rfps_base;
2773 enc->rate_emu = rate_emu;
2775 ic->streams[i]->discard= AVDISCARD_ALL;
2776 else if(video_discard)
2777 ic->streams[i]->discard= video_discard;
2779 case CODEC_TYPE_DATA:
2781 case CODEC_TYPE_SUBTITLE:
2783 case CODEC_TYPE_UNKNOWN:
2790 input_files[nb_input_files] = ic;
2791 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2792 /* dump the file content */
2794 dump_format(ic, nb_input_files, filename, 0);
2797 file_iformat = NULL;
2798 file_oformat = NULL;
2799 image_format = NULL;
2807 static void opt_grab(const char *arg)
2809 file_iformat = av_find_input_format(arg);
2813 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2815 int has_video, has_audio, i, j;
2816 AVFormatContext *ic;
2820 for(j=0;j<nb_input_files;j++) {
2821 ic = input_files[j];
2822 for(i=0;i<ic->nb_streams;i++) {
2823 AVCodecContext *enc = ic->streams[i]->codec;
2824 switch(enc->codec_type) {
2825 case CODEC_TYPE_AUDIO:
2828 case CODEC_TYPE_VIDEO:
2831 case CODEC_TYPE_DATA:
2832 case CODEC_TYPE_UNKNOWN:
2833 case CODEC_TYPE_SUBTITLE:
2840 *has_video_ptr = has_video;
2841 *has_audio_ptr = has_audio;
2844 static void new_video_stream(AVFormatContext *oc)
2847 AVCodecContext *video_enc;
2850 st = av_new_stream(oc, oc->nb_streams);
2852 fprintf(stderr, "Could not alloc stream\n");
2855 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2856 video_bitstream_filters= NULL;
2858 #if defined(HAVE_THREADS)
2860 avcodec_thread_init(st->codec, thread_count);
2863 video_enc = st->codec;
2866 video_enc->codec_tag= video_codec_tag;
2868 if( (video_global_header&1)
2869 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2870 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2871 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2873 if(video_global_header&2){
2874 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2875 avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2878 if (video_stream_copy) {
2879 st->stream_copy = 1;
2880 video_enc->codec_type = CODEC_TYPE_VIDEO;
2886 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2887 if (video_codec_id != CODEC_ID_NONE)
2888 codec_id = video_codec_id;
2890 video_enc->codec_id = codec_id;
2891 codec = avcodec_find_encoder(codec_id);
2893 for(i=0; i<opt_name_count; i++){
2895 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2896 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2897 av_set_double(video_enc, opt_names[i], d);
2900 video_enc->time_base.den = frame_rate;
2901 video_enc->time_base.num = frame_rate_base;
2902 if(codec && codec->supported_framerates){
2903 const AVRational *p= codec->supported_framerates;
2904 AVRational req= (AVRational){frame_rate, frame_rate_base};
2905 const AVRational *best=NULL;
2906 AVRational best_error= (AVRational){INT_MAX, 1};
2907 for(; p->den!=0; p++){
2908 AVRational error= av_sub_q(req, *p);
2909 if(error.num <0) error.num *= -1;
2910 if(av_cmp_q(error, best_error) < 0){
2915 video_enc->time_base.den= best->num;
2916 video_enc->time_base.num= best->den;
2919 video_enc->width = frame_width + frame_padright + frame_padleft;
2920 video_enc->height = frame_height + frame_padtop + frame_padbottom;
2921 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2922 video_enc->pix_fmt = frame_pix_fmt;
2924 if(codec && codec->pix_fmts){
2925 const enum PixelFormat *p= codec->pix_fmts;
2927 if(*p == video_enc->pix_fmt)
2931 video_enc->pix_fmt = codec->pix_fmts[0];
2935 video_enc->gop_size = 0;
2936 if (video_qscale || same_quality) {
2937 video_enc->flags |= CODEC_FLAG_QSCALE;
2938 video_enc->global_quality=
2939 st->quality = FF_QP2LAMBDA * video_qscale;
2943 video_enc->intra_matrix = intra_matrix;
2945 video_enc->inter_matrix = inter_matrix;
2947 video_enc->qmax = video_qmax;
2948 video_enc->lmin = video_lmin;
2949 video_enc->lmax = video_lmax;
2950 video_enc->rc_qsquish = video_qsquish;
2951 video_enc->mb_lmin = video_mb_lmin;
2952 video_enc->mb_lmax = video_mb_lmax;
2953 video_enc->max_qdiff = video_qdiff;
2954 video_enc->rc_eq = video_rc_eq;
2955 video_enc->workaround_bugs = workaround_bugs;
2956 video_enc->thread_count = thread_count;
2957 p= video_rc_override_string;
2960 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2962 fprintf(stderr, "error parsing rc_override\n");
2965 video_enc->rc_override=
2966 av_realloc(video_enc->rc_override,
2967 sizeof(RcOverride)*(i+1));
2968 video_enc->rc_override[i].start_frame= start;
2969 video_enc->rc_override[i].end_frame = end;
2971 video_enc->rc_override[i].qscale= q;
2972 video_enc->rc_override[i].quality_factor= 1.0;
2975 video_enc->rc_override[i].qscale= 0;
2976 video_enc->rc_override[i].quality_factor= -q/100.0;
2981 video_enc->rc_override_count=i;
2982 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
2983 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2984 video_enc->me_threshold= me_threshold;
2985 video_enc->mb_threshold= mb_threshold;
2986 video_enc->intra_dc_precision= intra_dc_precision - 8;
2987 video_enc->strict_std_compliance = strict;
2988 video_enc->error_rate = error_rate;
2989 video_enc->scenechange_threshold= sc_threshold;
2990 video_enc->me_penalty_compensation= me_penalty_compensation;
2991 video_enc->frame_skip_threshold= frame_skip_threshold;
2992 video_enc->frame_skip_factor= frame_skip_factor;
2993 video_enc->frame_skip_exp= frame_skip_exp;
2996 video_enc->rtp_mode= 1;
2997 video_enc->rtp_payload_size= packet_size;
3001 video_enc->flags|= CODEC_FLAG_PSNR;
3003 video_enc->me_method = me_method;
3008 video_enc->flags |= CODEC_FLAG_PASS1;
3010 video_enc->flags |= CODEC_FLAG_PASS2;
3015 /* reset some key parameters */
3017 video_codec_id = CODEC_ID_NONE;
3018 video_stream_copy = 0;
3021 static void new_audio_stream(AVFormatContext *oc)
3024 AVCodecContext *audio_enc;
3027 st = av_new_stream(oc, oc->nb_streams);
3029 fprintf(stderr, "Could not alloc stream\n");
3033 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3034 audio_bitstream_filters= NULL;
3036 #if defined(HAVE_THREADS)
3038 avcodec_thread_init(st->codec, thread_count);
3041 audio_enc = st->codec;
3042 audio_enc->codec_type = CODEC_TYPE_AUDIO;
3045 audio_enc->codec_tag= audio_codec_tag;
3047 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3048 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3049 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3051 if (audio_stream_copy) {
3052 st->stream_copy = 1;
3053 audio_enc->channels = audio_channels;
3055 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3057 for(i=0; i<opt_name_count; i++){
3059 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3060 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3061 av_set_double(audio_enc, opt_names[i], d);
3064 if (audio_codec_id != CODEC_ID_NONE)
3065 codec_id = audio_codec_id;
3066 audio_enc->codec_id = codec_id;
3068 audio_enc->bit_rate = audio_bit_rate;
3069 if (audio_qscale > QSCALE_NONE) {
3070 audio_enc->flags |= CODEC_FLAG_QSCALE;
3071 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3073 audio_enc->strict_std_compliance = strict;
3074 audio_enc->thread_count = thread_count;
3075 /* For audio codecs other than AC3 or DTS we limit */
3076 /* the number of coded channels to stereo */
3077 if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3078 && codec_id != CODEC_ID_DTS) {
3079 audio_enc->channels = 2;
3081 audio_enc->channels = audio_channels;
3083 audio_enc->sample_rate = audio_sample_rate;
3084 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3085 if (audio_language) {
3086 pstrcpy(st->language, sizeof(st->language), audio_language);
3087 av_free(audio_language);
3088 audio_language = NULL;
3091 /* reset some key parameters */
3093 audio_codec_id = CODEC_ID_NONE;
3094 audio_stream_copy = 0;
3097 static void opt_new_subtitle_stream(void)
3099 AVFormatContext *oc;
3101 AVCodecContext *subtitle_enc;
3104 if (nb_output_files <= 0) {
3105 fprintf(stderr, "At least one output file must be specified\n");
3108 oc = output_files[nb_output_files - 1];
3110 st = av_new_stream(oc, oc->nb_streams);
3112 fprintf(stderr, "Could not alloc stream\n");
3116 subtitle_enc = st->codec;
3117 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3118 if (subtitle_stream_copy) {
3119 st->stream_copy = 1;
3121 for(i=0; i<opt_name_count; i++){
3123 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3124 if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3125 av_set_double(subtitle_enc, opt_names[i], d);
3127 subtitle_enc->codec_id = subtitle_codec_id;
3130 if (subtitle_language) {
3131 pstrcpy(st->language, sizeof(st->language), subtitle_language);
3132 av_free(subtitle_language);
3133 subtitle_language = NULL;
3136 subtitle_codec_id = CODEC_ID_NONE;
3137 subtitle_stream_copy = 0;
3140 static void opt_new_audio_stream(void)
3142 AVFormatContext *oc;
3143 if (nb_output_files <= 0) {
3144 fprintf(stderr, "At least one output file must be specified\n");
3147 oc = output_files[nb_output_files - 1];
3148 new_audio_stream(oc);
3151 static void opt_new_video_stream(void)
3153 AVFormatContext *oc;
3154 if (nb_output_files <= 0) {
3155 fprintf(stderr, "At least one output file must be specified\n");
3158 oc = output_files[nb_output_files - 1];
3159 new_video_stream(oc);
3162 static void opt_output_file(const char *filename)
3164 AVFormatContext *oc;
3165 int use_video, use_audio, input_has_video, input_has_audio, i;
3166 AVFormatParameters params, *ap = ¶ms;
3168 if (!strcmp(filename, "-"))
3171 oc = av_alloc_format_context();
3173 if (!file_oformat) {
3174 file_oformat = guess_format(NULL, filename, NULL);
3175 if (!file_oformat) {
3176 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3182 oc->oformat = file_oformat;
3183 pstrcpy(oc->filename, sizeof(oc->filename), filename);
3185 if (!strcmp(file_oformat->name, "ffm") &&
3186 strstart(filename, "http:", NULL)) {
3187 /* special case for files sent to ffserver: we get the stream
3188 parameters from ffserver */
3189 if (read_ffserver_streams(oc, filename) < 0) {
3190 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3194 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3195 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3197 /* disable if no corresponding type found and at least one
3199 if (nb_input_files > 0) {
3200 check_audio_video_inputs(&input_has_video, &input_has_audio);
3201 if (!input_has_video)
3203 if (!input_has_audio)
3207 /* manual disable */
3208 if (audio_disable) {
3211 if (video_disable) {
3216 new_video_stream(oc);
3220 new_audio_stream(oc);
3223 if (!oc->nb_streams) {
3224 fprintf(stderr, "No audio or video streams available\n");
3228 oc->timestamp = rec_timestamp;
3231 pstrcpy(oc->title, sizeof(oc->title), str_title);
3233 pstrcpy(oc->author, sizeof(oc->author), str_author);
3235 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3237 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3239 pstrcpy(oc->album, sizeof(oc->album), str_album);
3242 output_files[nb_output_files++] = oc;
3244 /* check filename in case of an image number is expected */
3245 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3246 if (!av_filename_number_test(oc->filename)) {
3247 print_error(oc->filename, AVERROR_NUMEXPECTED);
3252 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3253 /* test if it already exists to avoid loosing precious files */
3254 if (!file_overwrite &&
3255 (strchr(filename, ':') == NULL ||
3256 strstart(filename, "file:", NULL))) {
3257 if (url_exist(filename)) {
3260 if ( !using_stdin ) {
3261 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3264 if (toupper(c) != 'Y') {
3265 fprintf(stderr, "Not overwriting - exiting\n");
3270 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3277 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3278 fprintf(stderr, "Could not open '%s'\n", filename);
3283 memset(ap, 0, sizeof(*ap));
3284 ap->image_format = image_format;
3285 if (av_set_parameters(oc, ap) < 0) {
3286 fprintf(stderr, "%s: Invalid encoding parameters\n",
3291 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3292 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3293 oc->loop_output = loop_output;
3295 for(i=0; i<opt_name_count; i++){
3297 double d = av_get_double(avformat_opts, opt_names[i], &opt);
3298 if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3299 av_set_double(oc, opt_names[i], d);
3302 /* reset some options */
3303 file_oformat = NULL;
3304 file_iformat = NULL;
3305 image_format = NULL;
3308 /* prepare dummy protocols for grab */
3309 static void prepare_grab(void)
3311 int has_video, has_audio, i, j;
3312 AVFormatContext *oc;
3313 AVFormatContext *ic;
3314 AVFormatParameters vp1, *vp = &vp1;
3315 AVFormatParameters ap1, *ap = &ap1;
3317 /* see if audio/video inputs are needed */
3320 memset(ap, 0, sizeof(*ap));
3321 memset(vp, 0, sizeof(*vp));
3322 vp->time_base.num= 1;
3323 for(j=0;j<nb_output_files;j++) {
3324 oc = output_files[j];
3325 for(i=0;i<oc->nb_streams;i++) {
3326 AVCodecContext *enc = oc->streams[i]->codec;
3327 switch(enc->codec_type) {
3328 case CODEC_TYPE_AUDIO:
3329 if (enc->sample_rate > ap->sample_rate)
3330 ap->sample_rate = enc->sample_rate;
3331 if (enc->channels > ap->channels)
3332 ap->channels = enc->channels;
3335 case CODEC_TYPE_VIDEO:
3336 if (enc->width > vp->width)
3337 vp->width = enc->width;
3338 if (enc->height > vp->height)
3339 vp->height = enc->height;
3341 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3342 vp->time_base = enc->time_base;
3343 vp->width += frame_leftBand + frame_rightBand;
3344 vp->width -= (frame_padleft + frame_padright);
3345 vp->height += frame_topBand + frame_bottomBand;
3346 vp->height -= (frame_padtop + frame_padbottom);
3356 if (has_video == 0 && has_audio == 0) {
3357 fprintf(stderr, "Output file must have at least one audio or video stream\n");
3362 AVInputFormat *fmt1;
3363 fmt1 = av_find_input_format(video_grab_format);
3364 vp->device = video_device;
3365 vp->channel = video_channel;
3366 vp->standard = video_standard;
3367 vp->pix_fmt = frame_pix_fmt;
3368 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3369 fprintf(stderr, "Could not find video grab device\n");
3372 /* If not enough info to get the stream parameters, we decode the
3373 first frames to get it. */
3374 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3375 fprintf(stderr, "Could not find video grab parameters\n");
3378 /* by now video grab has one stream */
3379 ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3380 ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3381 input_files[nb_input_files] = ic;
3384 dump_format(ic, nb_input_files, "", 0);
3388 if (has_audio && audio_grab_format) {
3389 AVInputFormat *fmt1;
3390 fmt1 = av_find_input_format(audio_grab_format);
3391 ap->device = audio_device;
3392 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3393 fprintf(stderr, "Could not find audio grab device\n");
3396 input_files[nb_input_files] = ic;
3399 dump_format(ic, nb_input_files, "", 0);
3405 /* same option as mencoder */
3406 static void opt_pass(const char *pass_str)
3409 pass = atoi(pass_str);
3410 if (pass != 1 && pass != 2) {
3411 fprintf(stderr, "pass number can be only 1 or 2\n");
3417 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3418 static int64_t getutime(void)
3420 return av_gettime();
3423 static int64_t getutime(void)
3425 struct rusage rusage;
3427 getrusage(RUSAGE_SELF, &rusage);
3428 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3432 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3433 extern int ffm_nopts;
3436 static void show_formats(void)
3438 AVInputFormat *ifmt;
3439 AVOutputFormat *ofmt;
3440 AVImageFormat *image_fmt;
3443 const char **pp, *last_name;
3445 printf("File formats:\n");
3450 const char *name=NULL;
3451 const char *long_name=NULL;
3453 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3454 if((name == NULL || strcmp(ofmt->name, name)<0) &&
3455 strcmp(ofmt->name, last_name)>0){
3457 long_name= ofmt->long_name;
3461 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3462 if((name == NULL || strcmp(ifmt->name, name)<0) &&
3463 strcmp(ifmt->name, last_name)>0){
3465 long_name= ifmt->long_name;
3468 if(name && strcmp(ifmt->name, name)==0)
3480 long_name ? long_name:" ");
3484 printf("Image formats (filename extensions, if any, follow):\n");
3485 for(image_fmt = first_image_format; image_fmt != NULL;
3486 image_fmt = image_fmt->next) {
3489 image_fmt->img_read ? "D":" ",
3490 image_fmt->img_write ? "E":" ",
3492 image_fmt->extensions ? image_fmt->extensions:" ");
3496 printf("Codecs:\n");
3502 const char *type_str;
3505 for(p = first_avcodec; p != NULL; p = p->next) {
3506 if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3507 strcmp(p->name, last_name)>0){
3509 decode= encode= cap=0;
3511 if(p2 && strcmp(p->name, p2->name)==0){
3512 if(p->decode) decode=1;
3513 if(p->encode) encode=1;
3514 cap |= p->capabilities;
3519 last_name= p2->name;
3522 case CODEC_TYPE_VIDEO:
3525 case CODEC_TYPE_AUDIO:
3528 case CODEC_TYPE_SUBTITLE:
3537 decode ? "D": (/*p2->decoder ? "d":*/" "),
3540 cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3541 cap & CODEC_CAP_DR1 ? "D":" ",
3542 cap & CODEC_CAP_TRUNCATED ? "T":" ",
3544 /* if(p2->decoder && decode==0)
3545 printf(" use %s for decoding", p2->decoder->name);*/
3550 printf("Supported file protocols:\n");
3551 for(up = first_protocol; up != NULL; up = up->next)
3552 printf(" %s:", up->name);
3555 printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3556 printf("Motion estimation methods:\n");
3560 if ((pp - motion_str + 1) == ME_ZERO)
3561 printf("(fastest)");
3562 else if ((pp - motion_str + 1) == ME_FULL)
3563 printf("(slowest)");
3564 else if ((pp - motion_str + 1) == ME_EPZS)
3565 printf("(default)");
3570 "Note, the names of encoders and decoders dont always match, so there are\n"
3571 "several cases where the above table shows encoder only or decoder only entries\n"
3572 "even though both encoding and decoding are supported for example, the h263\n"
3573 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3578 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3581 const char *p = str;
3588 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3595 static void opt_inter_matrix(const char *arg)
3597 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3598 parse_matrix_coeffs(inter_matrix, arg);
3601 static void opt_intra_matrix(const char *arg)
3603 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3604 parse_matrix_coeffs(intra_matrix, arg);
3607 static void opt_target(const char *arg)
3610 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3612 if(!strncmp(arg, "pal-", 4)) {
3615 } else if(!strncmp(arg, "ntsc-", 5)) {
3618 } else if(!strncmp(arg, "film-", 5)) {
3623 /* Calculate FR via float to avoid int overflow */
3624 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3627 } else if((fr == 29970) || (fr == 23976)) {
3630 /* Try to determine PAL/NTSC by peeking in the input files */
3631 if(nb_input_files) {
3633 for(j = 0; j < nb_input_files; j++) {
3634 for(i = 0; i < input_files[j]->nb_streams; i++) {
3635 AVCodecContext *c = input_files[j]->streams[i]->codec;
3636 if(c->codec_type != CODEC_TYPE_VIDEO)
3638 fr = c->time_base.den * 1000 / c->time_base.num;
3642 } else if((fr == 29970) || (fr == 23976)) {
3652 if(verbose && norm >= 0)
3653 fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3657 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3658 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3659 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3663 if(!strcmp(arg, "vcd")) {
3665 opt_video_codec("mpeg1video");
3666 opt_audio_codec("mp2");
3669 opt_frame_size(norm ? "352x240" : "352x288");
3670 opt_frame_rate(frame_rates[norm]);
3671 opt_default("gop", norm ? "18" : "15");
3673 opt_default("b", "1150000");
3674 opt_default("maxrate", "1150000");
3675 opt_default("minrate", "1150000");
3676 opt_default("bufsize", "327680"); // 40*1024*8;
3678 audio_bit_rate = 224000;
3679 audio_sample_rate = 44100;
3681 opt_default("packetsize", "2324");
3682 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3684 /* We have to offset the PTS, so that it is consistent with the SCR.
3685 SCR starts at 36000, but the first two packs contain only padding
3686 and the first pack from the other stream, respectively, may also have
3687 been written before.
3688 So the real data starts at SCR 36000+3*1200. */
3689 mux_preload= (36000+3*1200) / 90000.0; //0.44
3690 } else if(!strcmp(arg, "svcd")) {
3692 opt_video_codec("mpeg2video");
3693 opt_audio_codec("mp2");
3696 opt_frame_size(norm ? "480x480" : "480x576");
3697 opt_frame_rate(frame_rates[norm]);
3698 opt_default("gop", norm ? "18" : "15");
3700 opt_default("b", "2040000");
3701 opt_default("maxrate", "2516000");
3702 opt_default("minrate", "0"); //1145000;
3703 opt_default("bufsize", "1835008"); //224*1024*8;
3704 opt_default("flags", "+SCAN_OFFSET");
3707 audio_bit_rate = 224000;
3708 audio_sample_rate = 44100;
3710 opt_default("packetsize", "2324");
3712 } else if(!strcmp(arg, "dvd")) {
3714 opt_video_codec("mpeg2video");
3715 opt_audio_codec("ac3");
3718 opt_frame_size(norm ? "720x480" : "720x576");
3719 opt_frame_rate(frame_rates[norm]);
3720 opt_default("gop", norm ? "18" : "15");
3722 opt_default("b", "6000000");
3723 opt_default("maxrate", "9000000");
3724 opt_default("minrate", "0"); //1500000;
3725 opt_default("bufsize", "1835008"); //224*1024*8;
3727 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3728 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3730 audio_bit_rate = 448000;