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"
31 #include <sys/ioctl.h>
34 #include <sys/resource.h>
38 #include <sys/types.h>
39 #include <sys/select.h>
42 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
51 #if !defined(INFINITY) && defined(HUGE_VAL)
52 #define INFINITY HUGE_VAL
55 /* select an input stream for an output stream */
56 typedef struct AVStreamMap {
60 int sync_stream_index;
63 /** select an input file for an output file */
64 typedef struct AVMetaDataMap {
69 extern const OptionDef options[];
71 static void show_help(void);
72 static void show_license(void);
73 static int opt_default(const char *opt, const char *arg);
77 static AVFormatContext *input_files[MAX_FILES];
78 static int64_t input_files_ts_offset[MAX_FILES];
79 static int nb_input_files = 0;
81 static AVFormatContext *output_files[MAX_FILES];
82 static int nb_output_files = 0;
84 static AVStreamMap stream_maps[MAX_FILES];
85 static int nb_stream_maps;
87 static AVMetaDataMap meta_data_maps[MAX_FILES];
88 static int nb_meta_data_maps;
90 static AVInputFormat *file_iformat;
91 static AVOutputFormat *file_oformat;
92 static AVImageFormat *image_format;
93 static int frame_width = 0;
94 static int frame_height = 0;
95 static float frame_aspect_ratio = 0;
96 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
97 static int frame_padtop = 0;
98 static int frame_padbottom = 0;
99 static int frame_padleft = 0;
100 static int frame_padright = 0;
101 static int padcolor[3] = {16,128,128}; /* default to black */
102 static int frame_topBand = 0;
103 static int frame_bottomBand = 0;
104 static int frame_leftBand = 0;
105 static int frame_rightBand = 0;
106 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
107 static int frame_rate = 25;
108 static int frame_rate_base = 1;
109 static float video_qscale = 0;
110 static int video_lmin = 2*FF_QP2LAMBDA;
111 static int video_mb_lmin = 2*FF_QP2LAMBDA;
112 static int video_mb_lmax = 31*FF_QP2LAMBDA;
113 static int video_qdiff = 3;
114 static uint16_t *intra_matrix = NULL;
115 static uint16_t *inter_matrix = NULL;
116 #if 0 //experimental, (can be removed)
117 static float video_rc_qsquish=1.0;
118 static float video_rc_qmod_amp=0;
119 static int video_rc_qmod_freq=0;
121 static char *video_rc_override_string=NULL;
122 static char *video_rc_eq="tex^qComp";
123 static int me_method = ME_EPZS;
124 static int video_disable = 0;
125 static int video_discard = 0;
126 static int video_codec_id = CODEC_ID_NONE;
127 static int video_codec_tag = 0;
128 static int same_quality = 0;
129 static int do_deinterlace = 0;
130 static int packet_size = 0;
131 static int strict = 0;
132 static int top_field_first = -1;
133 static int me_threshold = 0;
134 static int intra_dc_precision = 8;
135 static int loop_input = 0;
136 static int loop_output = AVFMT_NOOUTPUTLOOP;
137 static int qp_hist = 0;
139 static int intra_only = 0;
140 static int audio_sample_rate = 44100;
141 static int audio_bit_rate = 64000;
142 #define QSCALE_NONE -99999
143 static float audio_qscale = QSCALE_NONE;
144 static int audio_disable = 0;
145 static int audio_channels = 1;
146 static int audio_codec_id = CODEC_ID_NONE;
147 static int audio_codec_tag = 0;
148 static char *audio_language = NULL;
150 static int subtitle_codec_id = CODEC_ID_NONE;
151 static char *subtitle_language = NULL;
153 static float mux_preload= 0.5;
154 static float mux_max_delay= 0.7;
156 static int64_t recording_time = 0;
157 static int64_t start_time = 0;
158 static int64_t rec_timestamp = 0;
159 static int64_t input_ts_offset = 0;
160 static int file_overwrite = 0;
161 static char *str_title = NULL;
162 static char *str_author = NULL;
163 static char *str_copyright = NULL;
164 static char *str_comment = NULL;
165 static char *str_album = NULL;
166 static int do_benchmark = 0;
167 static int do_hex_dump = 0;
168 static int do_pkt_dump = 0;
169 static int do_psnr = 0;
170 static int do_vstats = 0;
171 static int do_pass = 0;
172 static char *pass_logfilename = NULL;
173 static int audio_stream_copy = 0;
174 static int video_stream_copy = 0;
175 static int subtitle_stream_copy = 0;
176 static int video_sync_method= 1;
177 static int audio_sync_method= 0;
178 static int copy_ts= 0;
179 static int opt_shortest = 0; //
180 static int video_global_header = 0;
182 static int rate_emu = 0;
185 static const char *video_grab_format = "bktr";
187 #ifdef CONFIG_VIDEO4LINUX2
188 static const char *video_grab_format = "video4linux2";
190 static const char *video_grab_format = "video4linux";
193 static char *video_device = NULL;
194 static char *grab_device = NULL;
195 static int video_channel = 0;
196 static char *video_standard = "ntsc";
198 static const char *audio_grab_format = "audio_device";
199 static char *audio_device = NULL;
200 static int audio_volume = 256;
202 static int using_stdin = 0;
203 static int using_vhook = 0;
204 static int verbose = 1;
205 static int thread_count= 1;
206 static int q_pressed = 0;
207 static int64_t video_size = 0;
208 static int64_t audio_size = 0;
209 static int64_t extra_size = 0;
210 static int nb_frames_dup = 0;
211 static int nb_frames_drop = 0;
212 static int input_sync;
213 static int limit_filesize = 0; //
215 static int pgmyuv_compatibility_hack=0;
216 static int dts_delta_threshold = 10;
218 static int sws_flags = SWS_BICUBIC;
220 const char **opt_names=NULL;
221 int opt_name_count=0;
222 AVCodecContext *avctx_opts;
223 AVFormatContext *avformat_opts;
225 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
226 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
227 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
229 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
231 struct AVInputStream;
233 typedef struct AVOutputStream {
234 int file_index; /* file index */
235 int index; /* stream index in the output file */
236 int source_index; /* AVInputStream index */
237 AVStream *st; /* stream in the output file */
238 int encoding_needed; /* true if encoding needed for this stream */
240 /* input pts and corresponding output pts
242 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
243 struct AVInputStream *sync_ist; /* input stream to sync against */
244 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
247 AVFrame pict_tmp; /* temporary image for resampling */
248 struct SwsContext *img_resample_ctx; /* for image resampling */
252 int topBand; /* cropping area sizes */
256 int padtop; /* padding area sizes */
263 ReSampleContext *resample; /* for audio resampling */
264 AVFifoBuffer fifo; /* for compression: one audio fifo per codec */
268 typedef struct AVInputStream {
272 int discard; /* true if stream data should be discarded */
273 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
274 int64_t sample_index; /* current sample */
276 int64_t start; /* time when read started */
277 unsigned long frame; /* current frame */
278 int64_t next_pts; /* synthetic pts for cases where pkt.pts
280 int64_t pts; /* current pts */
281 int is_start; /* is 1 at the start and after a discontinuity */
284 typedef struct AVInputFile {
285 int eof_reached; /* true if eof reached */
286 int ist_index; /* index of first stream in ist_table */
287 int buffer_size; /* current total buffer size */
288 int buffer_size_max; /* buffer size at which we consider we can stop
290 int nb_streams; /* nb streams we are aware of */
295 /* init terminal so that we can grab keys */
296 static struct termios oldtty;
298 static void term_exit(void)
300 tcsetattr (0, TCSANOW, &oldtty);
303 static volatile sig_atomic_t received_sigterm = 0;
306 sigterm_handler(int sig)
308 received_sigterm = sig;
312 static void term_init(void)
319 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
320 |INLCR|IGNCR|ICRNL|IXON);
321 tty.c_oflag |= OPOST;
322 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
323 tty.c_cflag &= ~(CSIZE|PARENB);
328 tcsetattr (0, TCSANOW, &tty);
330 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
331 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
332 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
334 register a function to be called at normal program termination
337 #ifdef CONFIG_BEOS_NETSERVER
338 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
342 /* read a key without blocking */
343 static int read_key(void)
347 #ifndef CONFIG_BEOS_NETSERVER
355 n = select(1, &rfds, NULL, NULL, &tv);
367 static int decode_interrupt_cb(void)
369 return q_pressed || (q_pressed = read_key() == 'q');
374 static volatile int received_sigterm = 0;
376 /* no interactive support */
377 static void term_exit(void)
381 static void term_init(void)
385 static int read_key(void)
392 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
397 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
400 /* copy stream format */
401 s->nb_streams = ic->nb_streams;
402 for(i=0;i<ic->nb_streams;i++) {
405 // FIXME: a more elegant solution is needed
406 st = av_mallocz(sizeof(AVStream));
407 memcpy(st, ic->streams[i], sizeof(AVStream));
408 st->codec = avcodec_alloc_context();
409 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
413 av_close_input_file(ic);
418 get_sync_ipts(const AVOutputStream *ost)
420 const AVInputStream *ist = ost->sync_ist;
421 return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
424 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
426 AVPacket new_pkt= *pkt;
427 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
428 &new_pkt.data, &new_pkt.size,
429 pkt->data, pkt->size,
430 pkt->flags & PKT_FLAG_KEY);
433 new_pkt.destruct= av_destruct_packet;
440 av_interleaved_write_frame(s, pkt);
443 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
445 static void do_audio_out(AVFormatContext *s,
448 unsigned char *buf, int size)
451 static uint8_t *audio_buf = NULL;
452 static uint8_t *audio_out = NULL;
453 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
455 int size_out, frame_bytes, ret;
456 AVCodecContext *enc= ost->st->codec;
458 /* SC: dynamic allocation of buffers */
460 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
462 audio_out = av_malloc(audio_out_size);
463 if (!audio_buf || !audio_out)
464 return; /* Should signal an error ! */
466 if(audio_sync_method){
467 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
468 - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
469 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
470 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
472 //FIXME resample delay
473 if(fabs(delta) > 50){
476 byte_delta= FFMAX(byte_delta, -size);
480 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
485 static uint8_t *input_tmp= NULL;
486 input_tmp= av_realloc(input_tmp, byte_delta + size);
488 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
491 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
493 memset(input_tmp, 0, byte_delta);
494 memcpy(input_tmp + byte_delta, buf, size);
498 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
500 }else if(audio_sync_method>1){
501 int comp= clip(delta, -audio_sync_method, audio_sync_method);
502 assert(ost->audio_resample);
504 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
505 // 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), av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2));
506 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
510 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
511 - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
513 if (ost->audio_resample) {
515 size_out = audio_resample(ost->resample,
516 (short *)buftmp, (short *)buf,
517 size / (ist->st->codec->channels * 2));
518 size_out = size_out * enc->channels * 2;
524 /* now encode as many frames as possible */
525 if (enc->frame_size > 1) {
526 /* output resampled raw samples */
527 av_fifo_write(&ost->fifo, buftmp, size_out);
529 frame_bytes = enc->frame_size * 2 * enc->channels;
531 while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {
533 av_init_packet(&pkt);
535 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
538 pkt.stream_index= ost->index;
541 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
542 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
543 pkt.flags |= PKT_FLAG_KEY;
544 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
546 ost->sync_opts += enc->frame_size;
550 av_init_packet(&pkt);
552 ost->sync_opts += size_out / (2 * enc->channels);
554 /* output a pcm frame */
555 /* XXX: change encoding codec API to avoid this ? */
556 switch(enc->codec->id) {
557 case CODEC_ID_PCM_S32LE:
558 case CODEC_ID_PCM_S32BE:
559 case CODEC_ID_PCM_U32LE:
560 case CODEC_ID_PCM_U32BE:
561 size_out = size_out << 1;
563 case CODEC_ID_PCM_S24LE:
564 case CODEC_ID_PCM_S24BE:
565 case CODEC_ID_PCM_U24LE:
566 case CODEC_ID_PCM_U24BE:
567 case CODEC_ID_PCM_S24DAUD:
568 size_out = size_out / 2 * 3;
570 case CODEC_ID_PCM_S16LE:
571 case CODEC_ID_PCM_S16BE:
572 case CODEC_ID_PCM_U16LE:
573 case CODEC_ID_PCM_U16BE:
576 size_out = size_out >> 1;
579 ret = avcodec_encode_audio(enc, audio_out, size_out,
582 pkt.stream_index= ost->index;
585 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
586 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
587 pkt.flags |= PKT_FLAG_KEY;
588 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
592 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
596 AVPicture picture_tmp;
599 dec = ist->st->codec;
601 /* deinterlace : must be done before any resize */
602 if (do_deinterlace || using_vhook) {
605 /* create temporary picture */
606 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
607 buf = av_malloc(size);
611 picture2 = &picture_tmp;
612 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
615 if(avpicture_deinterlace(picture2, picture,
616 dec->pix_fmt, dec->width, dec->height) < 0) {
617 /* if error, do not deinterlace */
623 img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
629 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
631 if (picture != picture2)
632 *picture = *picture2;
636 /* we begin to correct av delay at this threshold */
637 #define AV_DELAY_MAX 0.100
639 static void do_subtitle_out(AVFormatContext *s,
645 static uint8_t *subtitle_out = NULL;
646 int subtitle_out_max_size = 65536;
647 int subtitle_out_size, nb, i;
651 if (pts == AV_NOPTS_VALUE) {
652 fprintf(stderr, "Subtitle packets must have a pts\n");
656 enc = ost->st->codec;
659 subtitle_out = av_malloc(subtitle_out_max_size);
662 /* Note: DVB subtitle need one packet to draw them and one other
663 packet to clear them */
664 /* XXX: signal it in the codec context ? */
665 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
670 for(i = 0; i < nb; i++) {
671 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
672 subtitle_out_max_size, sub);
674 av_init_packet(&pkt);
675 pkt.stream_index = ost->index;
676 pkt.data = subtitle_out;
677 pkt.size = subtitle_out_size;
678 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);
679 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
680 /* XXX: the pts correction is handled here. Maybe handling
681 it in the codec would be better */
683 pkt.pts += 90 * sub->start_display_time;
685 pkt.pts += 90 * sub->end_display_time;
687 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
691 static int bit_buffer_size= 1024*256;
692 static uint8_t *bit_buffer= NULL;
694 static void do_video_out(AVFormatContext *s,
700 int nb_frames, i, ret;
701 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
702 AVFrame picture_crop_temp, picture_pad_temp;
703 uint8_t *buf = NULL, *buf1 = NULL;
704 AVCodecContext *enc, *dec;
706 avcodec_get_frame_defaults(&picture_crop_temp);
707 avcodec_get_frame_defaults(&picture_pad_temp);
709 enc = ost->st->codec;
710 dec = ist->st->codec;
712 /* by default, we output a single frame */
717 if(video_sync_method){
719 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
720 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
723 else if (vdelta > 1.1)
724 nb_frames = lrintf(vdelta);
725 //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);
729 fprintf(stderr, "*** drop!\n");
730 }else if (nb_frames > 1) {
731 nb_frames_dup += nb_frames;
733 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
736 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
738 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
742 if (ost->video_crop) {
743 if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
744 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
747 formatted_picture = &picture_crop_temp;
749 formatted_picture = in_picture;
752 final_picture = formatted_picture;
753 padding_src = formatted_picture;
754 resampling_dst = &ost->pict_tmp;
755 if (ost->video_pad) {
756 final_picture = &ost->pict_tmp;
757 if (ost->video_resample) {
758 if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
759 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
762 resampling_dst = &picture_pad_temp;
766 if (ost->video_resample) {
768 final_picture = &ost->pict_tmp;
769 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
770 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
773 if (ost->video_pad) {
774 img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
775 enc->height, enc->width, enc->pix_fmt,
776 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
779 /* duplicates frame if needed */
780 for(i=0;i<nb_frames;i++) {
782 av_init_packet(&pkt);
783 pkt.stream_index= ost->index;
785 if (s->oformat->flags & AVFMT_RAWPICTURE) {
786 /* raw pictures are written as AVPicture structure to
787 avoid any copies. We support temorarily the older
789 AVFrame* old_frame = enc->coded_frame;
790 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
791 pkt.data= (uint8_t *)final_picture;
792 pkt.size= sizeof(AVPicture);
793 if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
794 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
795 if(dec->coded_frame && dec->coded_frame->key_frame)
796 pkt.flags |= PKT_FLAG_KEY;
798 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
799 enc->coded_frame = old_frame;
803 big_picture= *final_picture;
804 /* better than nothing: use input picture interlaced
806 big_picture.interlaced_frame = in_picture->interlaced_frame;
807 if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
808 if(top_field_first == -1)
809 big_picture.top_field_first = in_picture->top_field_first;
811 big_picture.top_field_first = top_field_first;
814 /* handles sameq here. This is not correct because it may
815 not be a global option */
817 big_picture.quality = ist->st->quality;
819 big_picture.quality = ost->st->quality;
821 big_picture.pict_type = 0;
822 // big_picture.pts = AV_NOPTS_VALUE;
823 big_picture.pts= ost->sync_opts;
824 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
825 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
826 ret = avcodec_encode_video(enc,
827 bit_buffer, bit_buffer_size,
830 fprintf(stderr, "Video encoding failed\n");
833 //enc->frame_number = enc->real_pict_num;
835 pkt.data= bit_buffer;
837 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
838 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
839 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
840 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
841 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
843 if(enc->coded_frame && enc->coded_frame->key_frame)
844 pkt.flags |= PKT_FLAG_KEY;
845 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
847 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
848 // enc->frame_number-1, enc->real_pict_num, ret,
850 /* if two pass, output log */
851 if (ost->logfile && enc->stats_out) {
852 fprintf(ost->logfile, "%s", enc->stats_out);
864 static double psnr(double d){
865 if(d==0) return INFINITY;
866 return -10.0*log(d)/log(10.0);
869 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
872 static FILE *fvstats=NULL;
879 double ti1, bitrate, avg_bitrate;
883 today = localtime(&today2);
884 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
887 fvstats = fopen(filename,"w");
895 enc = ost->st->codec;
896 if (enc->codec_type == CODEC_TYPE_VIDEO) {
897 frame_number = ost->frame_number;
898 fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
899 if (enc->flags&CODEC_FLAG_PSNR)
900 fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
902 fprintf(fvstats,"f_size= %6d ", frame_size);
903 /* compute pts value */
904 ti1 = ost->sync_opts * av_q2d(enc->time_base);
908 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
909 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
910 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
911 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
912 fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
916 static void print_report(AVFormatContext **output_files,
917 AVOutputStream **ost_table, int nb_ostreams,
922 AVFormatContext *oc, *os;
925 int frame_number, vid, i;
926 double bitrate, ti1, pts;
927 static int64_t last_time = -1;
928 static int qp_histogram[52];
930 if (!is_last_report) {
932 /* display the report every 0.5 seconds */
933 cur_time = av_gettime();
934 if (last_time == -1) {
935 last_time = cur_time;
938 if ((cur_time - last_time) < 500000)
940 last_time = cur_time;
944 oc = output_files[0];
946 total_size = url_ftell(&oc->pb);
951 for(i=0;i<nb_ostreams;i++) {
953 os = output_files[ost->file_index];
954 enc = ost->st->codec;
955 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
956 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
957 enc->coded_frame->quality/(float)FF_QP2LAMBDA);
959 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
960 frame_number = ost->frame_number;
961 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
962 frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
964 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
965 if(qp_hist && enc->coded_frame){
967 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
968 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
971 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
973 if (enc->flags&CODEC_FLAG_PSNR){
975 double error, error_sum=0;
976 double scale, scale_sum=0;
977 char type[3]= {'Y','U','V'};
978 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
981 error= enc->error[j];
982 scale= enc->width*enc->height*255.0*255.0*frame_number;
984 error= enc->coded_frame->error[j];
985 scale= enc->width*enc->height*255.0*255.0;
990 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
992 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
996 /* compute min output value */
997 pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
998 if ((pts < ti1) && (pts > 0))
1004 if (verbose || is_last_report) {
1005 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1007 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1008 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1009 (double)total_size / 1024, ti1, bitrate);
1012 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1013 nb_frames_dup, nb_frames_drop);
1016 fprintf(stderr, "%s \r", buf);
1021 if (is_last_report && verbose >= 0){
1022 int64_t raw= audio_size + video_size + extra_size;
1023 fprintf(stderr, "\n");
1024 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1028 100.0*(total_size - raw)/raw
1033 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1034 static int output_packet(AVInputStream *ist, int ist_index,
1035 AVOutputStream **ost_table, int nb_ostreams,
1036 const AVPacket *pkt)
1038 AVFormatContext *os;
1039 AVOutputStream *ost;
1043 int data_size, got_picture;
1045 void *buffer_to_free;
1046 static unsigned int samples_size= 0;
1047 static short *samples= NULL;
1048 AVSubtitle subtitle, *subtitle_to_free;
1052 ist->pts= ist->next_pts; // needed for last packet if vsync=0
1053 } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1054 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1056 // assert(ist->pts == ist->next_pts);
1070 /* decode the packet if needed */
1071 data_buf = NULL; /* fail safe */
1073 subtitle_to_free = NULL;
1074 if (ist->decoding_needed) {
1075 switch(ist->st->codec->codec_type) {
1076 case CODEC_TYPE_AUDIO:{
1078 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1079 /* XXX: could avoid copy if PCM 16 bits with same
1080 endianness as CPU */
1081 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1087 /* Some bug in mpeg audio decoder gives */
1088 /* data_size < 0, it seems they are overflows */
1089 if (data_size <= 0) {
1090 /* no audio frame */
1093 data_buf = (uint8_t *)samples;
1094 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1095 (ist->st->codec->sample_rate * ist->st->codec->channels);
1097 case CODEC_TYPE_VIDEO:
1098 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1099 /* XXX: allocate picture correctly */
1100 avcodec_get_frame_defaults(&picture);
1102 ret = avcodec_decode_video(ist->st->codec,
1103 &picture, &got_picture, ptr, len);
1104 ist->st->quality= picture.quality;
1108 /* no picture yet */
1109 goto discard_packet;
1111 if (ist->st->codec->time_base.num != 0) {
1112 ist->next_pts += ((int64_t)AV_TIME_BASE *
1113 ist->st->codec->time_base.num) /
1114 ist->st->codec->time_base.den;
1118 case CODEC_TYPE_SUBTITLE:
1119 ret = avcodec_decode_subtitle(ist->st->codec,
1120 &subtitle, &got_subtitle, ptr, len);
1123 if (!got_subtitle) {
1124 goto discard_packet;
1126 subtitle_to_free = &subtitle;
1133 switch(ist->st->codec->codec_type) {
1134 case CODEC_TYPE_AUDIO:
1135 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1136 (ist->st->codec->sample_rate * ist->st->codec->channels);
1138 case CODEC_TYPE_VIDEO:
1139 if (ist->st->codec->time_base.num != 0) {
1140 ist->next_pts += ((int64_t)AV_TIME_BASE *
1141 ist->st->codec->time_base.num) /
1142 ist->st->codec->time_base.den;
1152 buffer_to_free = NULL;
1153 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1154 pre_process_video_frame(ist, (AVPicture *)&picture,
1158 // preprocess audio (volume)
1159 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1160 if (audio_volume != 256) {
1163 for(i=0;i<(data_size / sizeof(short));i++) {
1164 int v = ((*volp) * audio_volume + 128) >> 8;
1165 if (v < -32768) v = -32768;
1166 if (v > 32767) v = 32767;
1172 /* frame rate emulation */
1173 if (ist->st->codec->rate_emu) {
1174 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1175 int64_t now = av_gettime() - ist->start;
1183 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1184 is the one of the next displayed one */
1185 /* XXX: add mpeg4 too ? */
1186 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1187 if (ist->st->codec->pict_type != B_TYPE) {
1189 tmp = ist->last_ip_pts;
1190 ist->last_ip_pts = ist->frac_pts.val;
1191 ist->frac_pts.val = tmp;
1195 /* if output time reached then transcode raw format,
1196 encode packets and output them */
1197 if (start_time == 0 || ist->pts >= start_time)
1198 for(i=0;i<nb_ostreams;i++) {
1202 if (ost->source_index == ist_index) {
1203 os = output_files[ost->file_index];
1206 printf("%d: got pts=%0.3f %0.3f\n", i,
1207 (double)pkt->pts / AV_TIME_BASE,
1208 ((double)ist->pts / AV_TIME_BASE) -
1209 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1211 /* set the input output pts pairs */
1212 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1214 if (ost->encoding_needed) {
1215 switch(ost->st->codec->codec_type) {
1216 case CODEC_TYPE_AUDIO:
1217 do_audio_out(os, ost, ist, data_buf, data_size);
1219 case CODEC_TYPE_VIDEO:
1220 do_video_out(os, ost, ist, &picture, &frame_size);
1221 video_size += frame_size;
1222 if (do_vstats && frame_size)
1223 do_video_stats(os, ost, frame_size);
1225 case CODEC_TYPE_SUBTITLE:
1226 do_subtitle_out(os, ost, ist, &subtitle,
1233 AVFrame avframe; //FIXME/XXX remove this
1235 av_init_packet(&opkt);
1237 /* no reencoding needed : output the packet directly */
1238 /* force the input stream PTS */
1240 avcodec_get_frame_defaults(&avframe);
1241 ost->st->codec->coded_frame= &avframe;
1242 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1244 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1245 audio_size += data_size;
1246 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1247 video_size += data_size;
1251 opkt.stream_index= ost->index;
1252 if(pkt->pts != AV_NOPTS_VALUE)
1253 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);
1255 opkt.pts= AV_NOPTS_VALUE;
1259 if (pkt->dts == AV_NOPTS_VALUE)
1260 dts = ist->next_pts;
1262 dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1263 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ost->st->time_base);
1265 opkt.flags= pkt->flags;
1267 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1268 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1269 opkt.destruct= av_destruct_packet;
1271 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1272 ost->st->codec->frame_number++;
1273 ost->frame_number++;
1274 av_free_packet(&opkt);
1278 av_free(buffer_to_free);
1279 /* XXX: allocate the subtitles in the codec ? */
1280 if (subtitle_to_free) {
1281 if (subtitle_to_free->rects != NULL) {
1282 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1283 av_free(subtitle_to_free->rects[i].bitmap);
1284 av_free(subtitle_to_free->rects[i].rgba_palette);
1286 av_freep(&subtitle_to_free->rects);
1288 subtitle_to_free->num_rects = 0;
1289 subtitle_to_free = NULL;
1296 for(i=0;i<nb_ostreams;i++) {
1298 if (ost->source_index == ist_index) {
1299 AVCodecContext *enc= ost->st->codec;
1300 os = output_files[ost->file_index];
1302 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1304 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1307 if (ost->encoding_needed) {
1311 av_init_packet(&pkt);
1312 pkt.stream_index= ost->index;
1314 switch(ost->st->codec->codec_type) {
1315 case CODEC_TYPE_AUDIO:
1316 fifo_bytes = av_fifo_size(&ost->fifo);
1318 /* encode any samples remaining in fifo */
1319 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1320 int fs_tmp = enc->frame_size;
1321 enc->frame_size = fifo_bytes / (2 * enc->channels);
1322 if(av_fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes) == 0) {
1323 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1325 enc->frame_size = fs_tmp;
1328 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1331 pkt.flags |= PKT_FLAG_KEY;
1333 case CODEC_TYPE_VIDEO:
1334 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1336 if(enc->coded_frame && enc->coded_frame->key_frame)
1337 pkt.flags |= PKT_FLAG_KEY;
1338 if (ost->logfile && enc->stats_out) {
1339 fprintf(ost->logfile, "%s", enc->stats_out);
1348 pkt.data= bit_buffer;
1350 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1351 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1352 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1366 * The following code is the main loop of the file converter
1368 static int av_encode(AVFormatContext **output_files,
1369 int nb_output_files,
1370 AVFormatContext **input_files,
1372 AVStreamMap *stream_maps, int nb_stream_maps)
1374 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1375 AVFormatContext *is, *os;
1376 AVCodecContext *codec, *icodec;
1377 AVOutputStream *ost, **ost_table = NULL;
1378 AVInputStream *ist, **ist_table = NULL;
1379 AVInputFile *file_table;
1380 AVFormatContext *stream_no_data;
1383 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1387 /* input stream init */
1389 for(i=0;i<nb_input_files;i++) {
1390 is = input_files[i];
1391 file_table[i].ist_index = j;
1392 file_table[i].nb_streams = is->nb_streams;
1393 j += is->nb_streams;
1397 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1401 for(i=0;i<nb_istreams;i++) {
1402 ist = av_mallocz(sizeof(AVInputStream));
1408 for(i=0;i<nb_input_files;i++) {
1409 is = input_files[i];
1410 for(k=0;k<is->nb_streams;k++) {
1411 ist = ist_table[j++];
1412 ist->st = is->streams[k];
1413 ist->file_index = i;
1415 ist->discard = 1; /* the stream is discarded by default
1418 if (ist->st->codec->rate_emu) {
1419 ist->start = av_gettime();
1425 /* output stream init */
1427 for(i=0;i<nb_output_files;i++) {
1428 os = output_files[i];
1429 nb_ostreams += os->nb_streams;
1431 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1432 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1436 /* Sanity check the mapping args -- do the input files & streams exist? */
1437 for(i=0;i<nb_stream_maps;i++) {
1438 int fi = stream_maps[i].file_index;
1439 int si = stream_maps[i].stream_index;
1441 if (fi < 0 || fi > nb_input_files - 1 ||
1442 si < 0 || si > file_table[fi].nb_streams - 1) {
1443 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1446 fi = stream_maps[i].sync_file_index;
1447 si = stream_maps[i].sync_stream_index;
1448 if (fi < 0 || fi > nb_input_files - 1 ||
1449 si < 0 || si > file_table[fi].nb_streams - 1) {
1450 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1455 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1458 for(i=0;i<nb_ostreams;i++) {
1459 ost = av_mallocz(sizeof(AVOutputStream));
1466 for(k=0;k<nb_output_files;k++) {
1467 os = output_files[k];
1468 for(i=0;i<os->nb_streams;i++) {
1470 ost = ost_table[n++];
1471 ost->file_index = k;
1473 ost->st = os->streams[i];
1474 if (nb_stream_maps > 0) {
1475 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1476 stream_maps[n-1].stream_index;
1478 /* Sanity check that the stream types match */
1479 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1480 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1481 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1482 ost->file_index, ost->index);
1487 /* get corresponding input stream index : we select the first one with the right type */
1489 for(j=0;j<nb_istreams;j++) {
1492 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1493 ost->source_index = j;
1500 /* try again and reuse existing stream */
1501 for(j=0;j<nb_istreams;j++) {
1503 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1504 ost->source_index = j;
1509 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1510 ost->file_index, ost->index);
1515 ist = ist_table[ost->source_index];
1517 ost->sync_ist = (nb_stream_maps > 0) ?
1518 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1519 stream_maps[n-1].sync_stream_index] : ist;
1523 /* for each output stream, we compute the right encoding parameters */
1524 for(i=0;i<nb_ostreams;i++) {
1526 ist = ist_table[ost->source_index];
1528 codec = ost->st->codec;
1529 icodec = ist->st->codec;
1531 if (ost->st->stream_copy) {
1532 /* if stream_copy is selected, no need to decode or encode */
1533 codec->codec_id = icodec->codec_id;
1534 codec->codec_type = icodec->codec_type;
1535 if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1536 codec->bit_rate = icodec->bit_rate;
1537 codec->extradata= icodec->extradata;
1538 codec->extradata_size= icodec->extradata_size;
1539 codec->time_base = icodec->time_base;
1540 switch(codec->codec_type) {
1541 case CODEC_TYPE_AUDIO:
1542 codec->sample_rate = icodec->sample_rate;
1543 codec->channels = icodec->channels;
1544 codec->frame_size = icodec->frame_size;
1545 codec->block_align= icodec->block_align;
1547 case CODEC_TYPE_VIDEO:
1548 codec->pix_fmt = icodec->pix_fmt;
1549 codec->width = icodec->width;
1550 codec->height = icodec->height;
1551 codec->has_b_frames = icodec->has_b_frames;
1553 case CODEC_TYPE_SUBTITLE:
1559 switch(codec->codec_type) {
1560 case CODEC_TYPE_AUDIO:
1561 if (av_fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1564 if (codec->channels == icodec->channels &&
1565 codec->sample_rate == icodec->sample_rate) {
1566 ost->audio_resample = 0;
1568 if (codec->channels != icodec->channels &&
1569 (icodec->codec_id == CODEC_ID_AC3 ||
1570 icodec->codec_id == CODEC_ID_DTS)) {
1571 /* Special case for 5:1 AC3 and DTS input */
1572 /* and mono or stereo output */
1573 /* Request specific number of channels */
1574 icodec->channels = codec->channels;
1575 if (codec->sample_rate == icodec->sample_rate)
1576 ost->audio_resample = 0;
1578 ost->audio_resample = 1;
1581 ost->audio_resample = 1;
1584 if(audio_sync_method>1)
1585 ost->audio_resample = 1;
1587 if(ost->audio_resample){
1588 ost->resample = audio_resample_init(codec->channels, icodec->channels,
1589 codec->sample_rate, icodec->sample_rate);
1591 printf("Can't resample. Aborting.\n");
1595 ist->decoding_needed = 1;
1596 ost->encoding_needed = 1;
1598 case CODEC_TYPE_VIDEO:
1599 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1600 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1601 ost->video_resample = ((codec->width != icodec->width -
1602 (frame_leftBand + frame_rightBand) +
1603 (frame_padleft + frame_padright)) ||
1604 (codec->height != icodec->height -
1605 (frame_topBand + frame_bottomBand) +
1606 (frame_padtop + frame_padbottom)) ||
1607 (codec->pix_fmt != icodec->pix_fmt));
1608 if (ost->video_crop) {
1609 ost->topBand = frame_topBand;
1610 ost->leftBand = frame_leftBand;
1612 if (ost->video_pad) {
1613 ost->padtop = frame_padtop;
1614 ost->padleft = frame_padleft;
1615 ost->padbottom = frame_padbottom;
1616 ost->padright = frame_padright;
1617 if (!ost->video_resample) {
1618 avcodec_get_frame_defaults(&ost->pict_tmp);
1619 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1620 codec->width, codec->height ) )
1624 if (ost->video_resample) {
1625 avcodec_get_frame_defaults(&ost->pict_tmp);
1626 if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1627 codec->width, codec->height ) )
1630 ost->img_resample_ctx = sws_getContext(
1631 icodec->width - (frame_leftBand + frame_rightBand),
1632 icodec->height - (frame_topBand + frame_bottomBand),
1634 codec->width - (frame_padleft + frame_padright),
1635 codec->height - (frame_padtop + frame_padbottom),
1637 sws_flags, NULL, NULL, NULL);
1638 if (ost->img_resample_ctx == NULL) {
1639 fprintf(stderr, "Cannot get resampling context\n");
1642 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1644 ost->encoding_needed = 1;
1645 ist->decoding_needed = 1;
1647 case CODEC_TYPE_SUBTITLE:
1648 ost->encoding_needed = 1;
1649 ist->decoding_needed = 1;
1656 if (ost->encoding_needed &&
1657 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1658 char logfilename[1024];
1663 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1665 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1666 if (codec->flags & CODEC_FLAG_PASS1) {
1667 f = fopen(logfilename, "w");
1669 perror(logfilename);
1674 /* read the log file */
1675 f = fopen(logfilename, "r");
1677 perror(logfilename);
1680 fseek(f, 0, SEEK_END);
1682 fseek(f, 0, SEEK_SET);
1683 logbuffer = av_malloc(size + 1);
1685 fprintf(stderr, "Could not allocate log buffer\n");
1688 size = fread(logbuffer, 1, size, f);
1690 logbuffer[size] = '\0';
1691 codec->stats_in = logbuffer;
1695 if(codec->codec_type == CODEC_TYPE_VIDEO){
1696 int size= codec->width * codec->height;
1697 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1702 bit_buffer = av_malloc(bit_buffer_size);
1706 /* dump the file output parameters - cannot be done before in case
1708 for(i=0;i<nb_output_files;i++) {
1709 dump_format(output_files[i], i, output_files[i]->filename, 1);
1712 /* dump the stream mapping */
1714 fprintf(stderr, "Stream mapping:\n");
1715 for(i=0;i<nb_ostreams;i++) {
1717 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1718 ist_table[ost->source_index]->file_index,
1719 ist_table[ost->source_index]->index,
1722 if (ost->sync_ist != ist_table[ost->source_index])
1723 fprintf(stderr, " [sync #%d.%d]",
1724 ost->sync_ist->file_index,
1725 ost->sync_ist->index);
1726 fprintf(stderr, "\n");
1730 /* open each encoder */
1731 for(i=0;i<nb_ostreams;i++) {
1733 if (ost->encoding_needed) {
1735 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1737 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1738 ost->file_index, ost->index);
1741 if (avcodec_open(ost->st->codec, codec) < 0) {
1742 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1743 ost->file_index, ost->index);
1746 extra_size += ost->st->codec->extradata_size;
1750 /* open each decoder */
1751 for(i=0;i<nb_istreams;i++) {
1753 if (ist->decoding_needed) {
1755 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1757 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1758 ist->st->codec->codec_id, ist->file_index, ist->index);
1761 if (avcodec_open(ist->st->codec, codec) < 0) {
1762 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1763 ist->file_index, ist->index);
1766 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1767 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1772 for(i=0;i<nb_istreams;i++) {
1774 is = input_files[ist->file_index];
1776 ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1777 if(ist->st->start_time == AV_NOPTS_VALUE)
1779 if(input_files_ts_offset[ist->file_index])
1780 ist->next_pts= AV_NOPTS_VALUE;
1784 /* compute buffer size max (should use a complete heuristic) */
1785 for(i=0;i<nb_input_files;i++) {
1786 file_table[i].buffer_size_max = 2048;
1789 /* set meta data information from input file if required */
1790 for (i=0;i<nb_meta_data_maps;i++) {
1791 AVFormatContext *out_file;
1792 AVFormatContext *in_file;
1794 int out_file_index = meta_data_maps[i].out_file;
1795 int in_file_index = meta_data_maps[i].in_file;
1796 if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1797 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1801 if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1802 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1807 out_file = output_files[out_file_index];
1808 in_file = input_files[in_file_index];
1810 strcpy(out_file->title, in_file->title);
1811 strcpy(out_file->author, in_file->author);
1812 strcpy(out_file->copyright, in_file->copyright);
1813 strcpy(out_file->comment, in_file->comment);
1814 strcpy(out_file->album, in_file->album);
1815 out_file->year = in_file->year;
1816 out_file->track = in_file->track;
1817 strcpy(out_file->genre, in_file->genre);
1820 /* open files and write file headers */
1821 for(i=0;i<nb_output_files;i++) {
1822 os = output_files[i];
1823 if (av_write_header(os) < 0) {
1824 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1831 if ( !using_stdin && verbose >= 0) {
1832 fprintf(stderr, "Press [q] to stop encoding\n");
1833 url_set_interrupt_cb(decode_interrupt_cb);
1841 for(; received_sigterm == 0;) {
1842 int file_index, ist_index;
1850 /* if 'q' pressed, exits */
1854 /* read_key() returns 0 on EOF */
1860 /* select the stream that we must read now by looking at the
1861 smallest output pts */
1863 for(i=0;i<nb_ostreams;i++) {
1866 os = output_files[ost->file_index];
1867 ist = ist_table[ost->source_index];
1868 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1869 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1871 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1872 ipts = (double)ist->pts;
1873 if (!file_table[ist->file_index].eof_reached){
1874 if(ipts < ipts_min) {
1876 if(input_sync ) file_index = ist->file_index;
1878 if(opts < opts_min) {
1880 if(!input_sync) file_index = ist->file_index;
1883 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1888 /* if none, if is finished */
1889 if (file_index < 0) {
1893 /* finish if recording time exhausted */
1894 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1897 /* finish if limit size exhausted */
1898 if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1901 /* read a frame from it and output it in the fifo */
1902 is = input_files[file_index];
1903 if (av_read_frame(is, &pkt) < 0) {
1904 file_table[file_index].eof_reached = 1;
1905 if (opt_shortest) break; else continue; //
1909 stream_no_data = is;
1914 av_pkt_dump(stdout, &pkt, do_hex_dump);
1916 /* the following test is needed in case new streams appear
1917 dynamically in stream : we ignore them */
1918 if (pkt.stream_index >= file_table[file_index].nb_streams)
1919 goto discard_packet;
1920 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1921 ist = ist_table[ist_index];
1923 goto discard_packet;
1925 // 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);
1926 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1927 int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1928 if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1929 input_files_ts_offset[ist->file_index]-= delta;
1931 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1932 for(i=0; i<file_table[file_index].nb_streams; i++){
1933 int index= file_table[file_index].ist_index + i;
1934 ist_table[index]->next_pts += delta;
1935 ist_table[index]->is_start=1;
1940 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1941 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1944 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1945 ist->file_index, ist->index);
1947 av_free_packet(&pkt);
1952 av_free_packet(&pkt);
1954 /* dump report by using the output first video and audio streams */
1955 print_report(output_files, ost_table, nb_ostreams, 0);
1958 /* at the end of stream, we must flush the decoder buffers */
1959 for(i=0;i<nb_istreams;i++) {
1961 if (ist->decoding_needed) {
1962 output_packet(ist, i, ost_table, nb_ostreams, NULL);
1968 /* write the trailer if needed and close file */
1969 for(i=0;i<nb_output_files;i++) {
1970 os = output_files[i];
1971 av_write_trailer(os);
1974 /* dump report by using the first video and audio streams */
1975 print_report(output_files, ost_table, nb_ostreams, 1);
1977 /* close each encoder */
1978 for(i=0;i<nb_ostreams;i++) {
1980 if (ost->encoding_needed) {
1981 av_freep(&ost->st->codec->stats_in);
1982 avcodec_close(ost->st->codec);
1986 /* close each decoder */
1987 for(i=0;i<nb_istreams;i++) {
1989 if (ist->decoding_needed) {
1990 avcodec_close(ist->st->codec);
1998 av_freep(&bit_buffer);
1999 av_free(file_table);
2002 for(i=0;i<nb_istreams;i++) {
2009 for(i=0;i<nb_ostreams;i++) {
2013 fclose(ost->logfile);
2014 ost->logfile = NULL;
2016 av_fifo_free(&ost->fifo); /* works even if fifo is not
2017 initialized but set to zero */
2018 av_free(ost->pict_tmp.data[0]);
2019 if (ost->video_resample)
2020 sws_freeContext(ost->img_resample_ctx);
2021 if (ost->audio_resample)
2022 audio_resample_close(ost->resample);
2035 int file_read(const char *filename)
2038 unsigned char buffer[1024];
2041 if (url_open(&h, filename, O_RDONLY) < 0) {
2042 printf("could not open '%s'\n", filename);
2046 len = url_read(h, buffer, sizeof(buffer));
2049 for(i=0;i<len;i++) putchar(buffer[i]);
2056 static void opt_image_format(const char *arg)
2060 for(f = first_image_format; f != NULL; f = f->next) {
2061 if (!strcmp(arg, f->name))
2065 fprintf(stderr, "Unknown image format: '%s'\n", arg);
2071 static void opt_format(const char *arg)
2073 /* compatibility stuff for pgmyuv */
2074 if (!strcmp(arg, "pgmyuv")) {
2075 pgmyuv_compatibility_hack=1;
2076 // opt_image_format(arg);
2080 file_iformat = av_find_input_format(arg);
2081 file_oformat = guess_format(arg, NULL, NULL);
2082 if (!file_iformat && !file_oformat) {
2083 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2088 static void opt_video_rc_eq(char *arg)
2093 static void opt_video_rc_override_string(char *arg)
2095 video_rc_override_string = arg;
2098 static void opt_me_threshold(const char *arg)
2100 me_threshold = atoi(arg);
2103 static void opt_verbose(const char *arg)
2105 verbose = atoi(arg);
2106 av_log_set_level(atoi(arg));
2109 static void opt_frame_rate(const char *arg)
2111 if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2112 fprintf(stderr, "Incorrect frame rate\n");
2117 static void opt_frame_crop_top(const char *arg)
2119 frame_topBand = atoi(arg);
2120 if (frame_topBand < 0) {
2121 fprintf(stderr, "Incorrect top crop size\n");
2124 if ((frame_topBand % 2) != 0) {
2125 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2128 if ((frame_topBand) >= frame_height){
2129 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2132 frame_height -= frame_topBand;
2135 static void opt_frame_crop_bottom(const char *arg)
2137 frame_bottomBand = atoi(arg);
2138 if (frame_bottomBand < 0) {
2139 fprintf(stderr, "Incorrect bottom crop size\n");
2142 if ((frame_bottomBand % 2) != 0) {
2143 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2146 if ((frame_bottomBand) >= frame_height){
2147 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2150 frame_height -= frame_bottomBand;
2153 static void opt_frame_crop_left(const char *arg)
2155 frame_leftBand = atoi(arg);
2156 if (frame_leftBand < 0) {
2157 fprintf(stderr, "Incorrect left crop size\n");
2160 if ((frame_leftBand % 2) != 0) {
2161 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2164 if ((frame_leftBand) >= frame_width){
2165 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2168 frame_width -= frame_leftBand;
2171 static void opt_frame_crop_right(const char *arg)
2173 frame_rightBand = atoi(arg);
2174 if (frame_rightBand < 0) {
2175 fprintf(stderr, "Incorrect right crop size\n");
2178 if ((frame_rightBand % 2) != 0) {
2179 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2182 if ((frame_rightBand) >= frame_width){
2183 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2186 frame_width -= frame_rightBand;
2189 static void opt_frame_size(const char *arg)
2191 if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2192 fprintf(stderr, "Incorrect frame size\n");
2195 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2196 fprintf(stderr, "Frame size must be a multiple of 2\n");
2202 #define SCALEBITS 10
2203 #define ONE_HALF (1 << (SCALEBITS - 1))
2204 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2206 #define RGB_TO_Y(r, g, b) \
2207 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2208 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2210 #define RGB_TO_U(r1, g1, b1, shift)\
2211 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2212 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2214 #define RGB_TO_V(r1, g1, b1, shift)\
2215 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2216 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2218 static void opt_pad_color(const char *arg) {
2219 /* Input is expected to be six hex digits similar to
2220 how colors are expressed in html tags (but without the #) */
2221 int rgb = strtol(arg, NULL, 16);
2225 g = ((rgb >> 8) & 255);
2228 padcolor[0] = RGB_TO_Y(r,g,b);
2229 padcolor[1] = RGB_TO_U(r,g,b,0);
2230 padcolor[2] = RGB_TO_V(r,g,b,0);
2233 static void opt_frame_pad_top(const char *arg)
2235 frame_padtop = atoi(arg);
2236 if (frame_padtop < 0) {
2237 fprintf(stderr, "Incorrect top pad size\n");
2240 if ((frame_padtop % 2) != 0) {
2241 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2246 static void opt_frame_pad_bottom(const char *arg)
2248 frame_padbottom = atoi(arg);
2249 if (frame_padbottom < 0) {
2250 fprintf(stderr, "Incorrect bottom pad size\n");
2253 if ((frame_padbottom % 2) != 0) {
2254 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2260 static void opt_frame_pad_left(const char *arg)
2262 frame_padleft = atoi(arg);
2263 if (frame_padleft < 0) {
2264 fprintf(stderr, "Incorrect left pad size\n");
2267 if ((frame_padleft % 2) != 0) {
2268 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2274 static void opt_frame_pad_right(const char *arg)
2276 frame_padright = atoi(arg);
2277 if (frame_padright < 0) {
2278 fprintf(stderr, "Incorrect right pad size\n");
2281 if ((frame_padright % 2) != 0) {
2282 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2288 static void opt_frame_pix_fmt(const char *arg)
2290 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2293 static void opt_frame_aspect_ratio(const char *arg)
2299 p = strchr(arg, ':');
2301 x = strtol(arg, (char **)&arg, 10);
2303 y = strtol(arg+1, (char **)&arg, 10);
2305 ar = (double)x / (double)y;
2307 ar = strtod(arg, (char **)&arg);
2310 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2313 frame_aspect_ratio = ar;
2316 static void opt_qscale(const char *arg)
2318 video_qscale = atof(arg);
2319 if (video_qscale <= 0 ||
2320 video_qscale > 255) {
2321 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2326 static void opt_lmin(const char *arg)
2328 video_lmin = atof(arg)*FF_QP2LAMBDA;
2331 static void opt_mb_lmin(const char *arg)
2333 video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2334 if (video_mb_lmin < 1 ||
2335 video_mb_lmin > FF_LAMBDA_MAX) {
2336 fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2341 static void opt_mb_lmax(const char *arg)
2343 video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2344 if (video_mb_lmax < 1 ||
2345 video_mb_lmax > FF_LAMBDA_MAX) {
2346 fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2351 static void opt_qdiff(const char *arg)
2353 video_qdiff = atoi(arg);
2354 if (video_qdiff < 0 ||
2356 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2361 static void opt_packet_size(const char *arg)
2363 packet_size= atoi(arg);
2366 static void opt_strict(const char *arg)
2371 static void opt_top_field_first(const char *arg)
2373 top_field_first= atoi(arg);
2376 static void opt_thread_count(const char *arg)
2378 thread_count= atoi(arg);
2379 #if !defined(HAVE_THREADS)
2381 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2385 static void opt_audio_bitrate(const char *arg)
2387 audio_bit_rate = atoi(arg) * 1000;
2390 static void opt_audio_rate(const char *arg)
2392 audio_sample_rate = atoi(arg);
2395 static void opt_audio_channels(const char *arg)
2397 audio_channels = atoi(arg);
2400 static void opt_video_device(const char *arg)
2402 video_device = av_strdup(arg);
2405 static void opt_grab_device(const char *arg)
2407 grab_device = av_strdup(arg);
2410 static void opt_video_channel(const char *arg)
2412 video_channel = strtol(arg, NULL, 0);
2415 static void opt_video_standard(const char *arg)
2417 video_standard = av_strdup(arg);
2420 static void opt_audio_device(const char *arg)
2422 audio_device = av_strdup(arg);
2425 static void opt_codec(int *pstream_copy, int *pcodec_id,
2426 int codec_type, const char *arg)
2430 if (!strcmp(arg, "copy")) {
2435 if (!strcmp(p->name, arg) && p->type == codec_type)
2440 fprintf(stderr, "Unknown codec '%s'\n", arg);
2448 static void opt_audio_codec(const char *arg)
2450 opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2453 static void opt_audio_tag(const char *arg)
2456 audio_codec_tag= strtol(arg, &tail, 0);
2459 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2462 static void opt_video_tag(const char *arg)
2465 video_codec_tag= strtol(arg, &tail, 0);
2468 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2471 static void add_frame_hooker(const char *arg)
2476 char *args = av_strdup(arg);
2480 argv[0] = strtok(args, " ");
2481 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2484 i = frame_hook_add(argc, argv);
2487 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2492 const char *motion_str[] = {
2505 static void opt_motion_estimation(const char *arg)
2511 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2514 if (!strcmp(*p, arg))
2518 me_method = (p - motion_str) + 1;
2521 static void opt_video_codec(const char *arg)
2523 opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2526 static void opt_subtitle_codec(const char *arg)
2528 opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2531 static void opt_map(const char *arg)
2537 m = &stream_maps[nb_stream_maps++];
2539 m->file_index = strtol(arg, (char **)&p, 0);
2543 m->stream_index = strtol(p, (char **)&p, 0);
2546 m->sync_file_index = strtol(p, (char **)&p, 0);
2549 m->sync_stream_index = strtol(p, (char **)&p, 0);
2551 m->sync_file_index = m->file_index;
2552 m->sync_stream_index = m->stream_index;
2556 static void opt_map_meta_data(const char *arg)
2562 m = &meta_data_maps[nb_meta_data_maps++];
2564 m->out_file = strtol(arg, (char **)&p, 0);
2568 m->in_file = strtol(p, (char **)&p, 0);
2571 static void opt_recording_time(const char *arg)
2573 recording_time = parse_date(arg, 1);
2576 static void opt_start_time(const char *arg)
2578 start_time = parse_date(arg, 1);
2581 static void opt_rec_timestamp(const char *arg)
2583 rec_timestamp = parse_date(arg, 0) / 1000000;
2586 static void opt_input_ts_offset(const char *arg)
2588 input_ts_offset = parse_date(arg, 1);
2591 static void opt_input_file(const char *filename)
2593 AVFormatContext *ic;
2594 AVFormatParameters params, *ap = ¶ms;
2595 int err, i, ret, rfps, rfps_base;
2598 if (!strcmp(filename, "-"))
2601 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2602 !strcmp( filename, "/dev/stdin" );
2604 /* get default parameters from command line */
2605 ic = av_alloc_format_context();
2607 memset(ap, 0, sizeof(*ap));
2608 ap->prealloced_context = 1;
2609 ap->sample_rate = audio_sample_rate;
2610 ap->channels = audio_channels;
2611 ap->time_base.den = frame_rate;
2612 ap->time_base.num = frame_rate_base;
2613 ap->width = frame_width + frame_padleft + frame_padright;
2614 ap->height = frame_height + frame_padtop + frame_padbottom;
2615 ap->image_format = image_format;
2616 ap->pix_fmt = frame_pix_fmt;
2617 ap->device = grab_device;
2618 ap->channel = video_channel;
2619 ap->standard = video_standard;
2620 ap->video_codec_id = video_codec_id;
2621 ap->audio_codec_id = audio_codec_id;
2622 if(pgmyuv_compatibility_hack)
2623 ap->video_codec_id= CODEC_ID_PGMYUV;
2625 for(i=0; i<opt_name_count; i++){
2627 double d= av_get_double(avformat_opts, opt_names[i], &opt);
2628 if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2629 av_set_double(ic, opt_names[i], d);
2631 /* open the input file with generic libav function */
2632 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2634 print_error(filename, err);
2638 ic->loop_input = loop_input;
2640 /* If not enough info to get the stream parameters, we decode the
2641 first frames to get it. (used in mpeg case for example) */
2642 ret = av_find_stream_info(ic);
2643 if (ret < 0 && verbose >= 0) {
2644 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2648 timestamp = start_time;
2649 /* add the stream start time */
2650 if (ic->start_time != AV_NOPTS_VALUE)
2651 timestamp += ic->start_time;
2653 /* if seeking requested, we execute it */
2654 if (start_time != 0) {
2655 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2657 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2658 filename, (double)timestamp / AV_TIME_BASE);
2660 /* reset seek info */
2664 /* update the current parameters so that they match the one of the input stream */
2665 for(i=0;i<ic->nb_streams;i++) {
2667 AVCodecContext *enc = ic->streams[i]->codec;
2668 #if defined(HAVE_THREADS)
2670 avcodec_thread_init(enc, thread_count);
2672 enc->thread_count= thread_count;
2673 switch(enc->codec_type) {
2674 case CODEC_TYPE_AUDIO:
2675 for(j=0; j<opt_name_count; j++){
2677 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2678 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2679 av_set_double(enc, opt_names[j], d);
2681 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2682 audio_channels = enc->channels;
2683 audio_sample_rate = enc->sample_rate;
2685 ic->streams[i]->discard= AVDISCARD_ALL;
2687 case CODEC_TYPE_VIDEO:
2688 for(j=0; j<opt_name_count; j++){
2690 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2691 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2692 av_set_double(enc, opt_names[j], d);
2694 frame_height = enc->height;
2695 frame_width = enc->width;
2696 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2697 frame_pix_fmt = enc->pix_fmt;
2698 rfps = ic->streams[i]->r_frame_rate.num;
2699 rfps_base = ic->streams[i]->r_frame_rate.den;
2700 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2702 enc->debug |= FF_DEBUG_MV;
2704 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2707 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2708 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2710 (float)rfps / rfps_base, rfps, rfps_base);
2712 /* update the current frame rate to match the stream frame rate */
2714 frame_rate_base = rfps_base;
2716 enc->rate_emu = rate_emu;
2718 ic->streams[i]->discard= AVDISCARD_ALL;
2719 else if(video_discard)
2720 ic->streams[i]->discard= video_discard;
2722 case CODEC_TYPE_DATA:
2724 case CODEC_TYPE_SUBTITLE:
2726 case CODEC_TYPE_UNKNOWN:
2733 input_files[nb_input_files] = ic;
2734 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2735 /* dump the file content */
2737 dump_format(ic, nb_input_files, filename, 0);
2740 file_iformat = NULL;
2741 file_oformat = NULL;
2742 image_format = NULL;
2750 static void opt_grab(const char *arg)
2752 file_iformat = av_find_input_format(arg);
2756 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2758 int has_video, has_audio, i, j;
2759 AVFormatContext *ic;
2763 for(j=0;j<nb_input_files;j++) {
2764 ic = input_files[j];
2765 for(i=0;i<ic->nb_streams;i++) {
2766 AVCodecContext *enc = ic->streams[i]->codec;
2767 switch(enc->codec_type) {
2768 case CODEC_TYPE_AUDIO:
2771 case CODEC_TYPE_VIDEO:
2774 case CODEC_TYPE_DATA:
2775 case CODEC_TYPE_UNKNOWN:
2776 case CODEC_TYPE_SUBTITLE:
2783 *has_video_ptr = has_video;
2784 *has_audio_ptr = has_audio;
2787 static void new_video_stream(AVFormatContext *oc)
2790 AVCodecContext *video_enc;
2793 st = av_new_stream(oc, oc->nb_streams);
2795 fprintf(stderr, "Could not alloc stream\n");
2798 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2799 video_bitstream_filters= NULL;
2801 #if defined(HAVE_THREADS)
2803 avcodec_thread_init(st->codec, thread_count);
2806 video_enc = st->codec;
2809 video_enc->codec_tag= video_codec_tag;
2811 if( (video_global_header&1)
2812 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2813 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2814 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2816 if(video_global_header&2){
2817 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2818 avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2821 if (video_stream_copy) {
2822 st->stream_copy = 1;
2823 video_enc->codec_type = CODEC_TYPE_VIDEO;
2829 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2830 if (video_codec_id != CODEC_ID_NONE)
2831 codec_id = video_codec_id;
2833 video_enc->codec_id = codec_id;
2834 codec = avcodec_find_encoder(codec_id);
2836 for(i=0; i<opt_name_count; i++){
2838 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2839 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2840 av_set_double(video_enc, opt_names[i], d);
2843 video_enc->time_base.den = frame_rate;
2844 video_enc->time_base.num = frame_rate_base;
2845 if(codec && codec->supported_framerates){
2846 const AVRational *p= codec->supported_framerates;
2847 AVRational req= (AVRational){frame_rate, frame_rate_base};
2848 const AVRational *best=NULL;
2849 AVRational best_error= (AVRational){INT_MAX, 1};
2850 for(; p->den!=0; p++){
2851 AVRational error= av_sub_q(req, *p);
2852 if(error.num <0) error.num *= -1;
2853 if(av_cmp_q(error, best_error) < 0){
2858 video_enc->time_base.den= best->num;
2859 video_enc->time_base.num= best->den;
2862 video_enc->width = frame_width + frame_padright + frame_padleft;
2863 video_enc->height = frame_height + frame_padtop + frame_padbottom;
2864 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2865 video_enc->pix_fmt = frame_pix_fmt;
2867 if(codec && codec->pix_fmts){
2868 const enum PixelFormat *p= codec->pix_fmts;
2870 if(*p == video_enc->pix_fmt)
2874 video_enc->pix_fmt = codec->pix_fmts[0];
2878 video_enc->gop_size = 0;
2879 if (video_qscale || same_quality) {
2880 video_enc->flags |= CODEC_FLAG_QSCALE;
2881 video_enc->global_quality=
2882 st->quality = FF_QP2LAMBDA * video_qscale;
2886 video_enc->intra_matrix = intra_matrix;
2888 video_enc->inter_matrix = inter_matrix;
2890 video_enc->lmin = video_lmin;
2891 video_enc->mb_lmin = video_mb_lmin;
2892 video_enc->mb_lmax = video_mb_lmax;
2893 video_enc->max_qdiff = video_qdiff;
2894 video_enc->rc_eq = video_rc_eq;
2895 video_enc->thread_count = thread_count;
2896 p= video_rc_override_string;
2899 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2901 fprintf(stderr, "error parsing rc_override\n");
2904 video_enc->rc_override=
2905 av_realloc(video_enc->rc_override,
2906 sizeof(RcOverride)*(i+1));
2907 video_enc->rc_override[i].start_frame= start;
2908 video_enc->rc_override[i].end_frame = end;
2910 video_enc->rc_override[i].qscale= q;
2911 video_enc->rc_override[i].quality_factor= 1.0;
2914 video_enc->rc_override[i].qscale= 0;
2915 video_enc->rc_override[i].quality_factor= -q/100.0;
2920 video_enc->rc_override_count=i;
2921 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
2922 video_enc->me_threshold= me_threshold;
2923 video_enc->intra_dc_precision= intra_dc_precision - 8;
2924 video_enc->strict_std_compliance = strict;
2927 video_enc->rtp_mode= 1;
2928 video_enc->rtp_payload_size= packet_size;
2932 video_enc->flags|= CODEC_FLAG_PSNR;
2934 video_enc->me_method = me_method;
2939 video_enc->flags |= CODEC_FLAG_PASS1;
2941 video_enc->flags |= CODEC_FLAG_PASS2;
2946 /* reset some key parameters */
2948 video_codec_id = CODEC_ID_NONE;
2949 video_stream_copy = 0;
2952 static void new_audio_stream(AVFormatContext *oc)
2955 AVCodecContext *audio_enc;
2958 st = av_new_stream(oc, oc->nb_streams);
2960 fprintf(stderr, "Could not alloc stream\n");
2964 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
2965 audio_bitstream_filters= NULL;
2967 #if defined(HAVE_THREADS)
2969 avcodec_thread_init(st->codec, thread_count);
2972 audio_enc = st->codec;
2973 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2976 audio_enc->codec_tag= audio_codec_tag;
2978 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
2979 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2980 avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2982 if (audio_stream_copy) {
2983 st->stream_copy = 1;
2984 audio_enc->channels = audio_channels;
2986 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
2988 for(i=0; i<opt_name_count; i++){
2990 double d= av_get_double(avctx_opts, opt_names[i], &opt);
2991 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2992 av_set_double(audio_enc, opt_names[i], d);
2995 if (audio_codec_id != CODEC_ID_NONE)
2996 codec_id = audio_codec_id;
2997 audio_enc->codec_id = codec_id;
2999 audio_enc->bit_rate = audio_bit_rate;
3000 if (audio_qscale > QSCALE_NONE) {
3001 audio_enc->flags |= CODEC_FLAG_QSCALE;
3002 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3004 audio_enc->strict_std_compliance = strict;
3005 audio_enc->thread_count = thread_count;
3006 /* For audio codecs other than AC3 or DTS we limit */
3007 /* the number of coded channels to stereo */
3008 if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3009 && codec_id != CODEC_ID_DTS) {
3010 audio_enc->channels = 2;
3012 audio_enc->channels = audio_channels;
3014 audio_enc->sample_rate = audio_sample_rate;
3015 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3016 if (audio_language) {
3017 pstrcpy(st->language, sizeof(st->language), audio_language);
3018 av_free(audio_language);
3019 audio_language = NULL;
3022 /* reset some key parameters */
3024 audio_codec_id = CODEC_ID_NONE;
3025 audio_stream_copy = 0;
3028 static void opt_new_subtitle_stream(void)
3030 AVFormatContext *oc;
3032 AVCodecContext *subtitle_enc;
3035 if (nb_output_files <= 0) {
3036 fprintf(stderr, "At least one output file must be specified\n");
3039 oc = output_files[nb_output_files - 1];
3041 st = av_new_stream(oc, oc->nb_streams);
3043 fprintf(stderr, "Could not alloc stream\n");
3047 subtitle_enc = st->codec;
3048 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3049 if (subtitle_stream_copy) {
3050 st->stream_copy = 1;
3052 for(i=0; i<opt_name_count; i++){
3054 double d= av_get_double(avctx_opts, opt_names[i], &opt);
3055 if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3056 av_set_double(subtitle_enc, opt_names[i], d);
3058 subtitle_enc->codec_id = subtitle_codec_id;
3061 if (subtitle_language) {
3062 pstrcpy(st->language, sizeof(st->language), subtitle_language);
3063 av_free(subtitle_language);
3064 subtitle_language = NULL;
3067 subtitle_codec_id = CODEC_ID_NONE;
3068 subtitle_stream_copy = 0;
3071 static void opt_new_audio_stream(void)
3073 AVFormatContext *oc;
3074 if (nb_output_files <= 0) {
3075 fprintf(stderr, "At least one output file must be specified\n");
3078 oc = output_files[nb_output_files - 1];
3079 new_audio_stream(oc);
3082 static void opt_new_video_stream(void)
3084 AVFormatContext *oc;
3085 if (nb_output_files <= 0) {
3086 fprintf(stderr, "At least one output file must be specified\n");
3089 oc = output_files[nb_output_files - 1];
3090 new_video_stream(oc);
3093 static void opt_output_file(const char *filename)
3095 AVFormatContext *oc;
3096 int use_video, use_audio, input_has_video, input_has_audio, i;
3097 AVFormatParameters params, *ap = ¶ms;
3099 if (!strcmp(filename, "-"))
3102 oc = av_alloc_format_context();
3104 if (!file_oformat) {
3105 file_oformat = guess_format(NULL, filename, NULL);
3106 if (!file_oformat) {
3107 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3113 oc->oformat = file_oformat;
3114 pstrcpy(oc->filename, sizeof(oc->filename), filename);
3116 if (!strcmp(file_oformat->name, "ffm") &&
3117 strstart(filename, "http:", NULL)) {
3118 /* special case for files sent to ffserver: we get the stream
3119 parameters from ffserver */
3120 if (read_ffserver_streams(oc, filename) < 0) {
3121 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3125 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3126 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3128 /* disable if no corresponding type found and at least one
3130 if (nb_input_files > 0) {
3131 check_audio_video_inputs(&input_has_video, &input_has_audio);
3132 if (!input_has_video)
3134 if (!input_has_audio)
3138 /* manual disable */
3139 if (audio_disable) {
3142 if (video_disable) {
3147 new_video_stream(oc);
3151 new_audio_stream(oc);
3154 if (!oc->nb_streams) {
3155 fprintf(stderr, "No audio or video streams available\n");
3159 oc->timestamp = rec_timestamp;
3162 pstrcpy(oc->title, sizeof(oc->title), str_title);
3164 pstrcpy(oc->author, sizeof(oc->author), str_author);
3166 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3168 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3170 pstrcpy(oc->album, sizeof(oc->album), str_album);
3173 output_files[nb_output_files++] = oc;
3175 /* check filename in case of an image number is expected */
3176 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3177 if (!av_filename_number_test(oc->filename)) {
3178 print_error(oc->filename, AVERROR_NUMEXPECTED);
3183 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3184 /* test if it already exists to avoid loosing precious files */
3185 if (!file_overwrite &&
3186 (strchr(filename, ':') == NULL ||
3187 strstart(filename, "file:", NULL))) {
3188 if (url_exist(filename)) {
3191 if ( !using_stdin ) {
3192 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3195 if (toupper(c) != 'Y') {
3196 fprintf(stderr, "Not overwriting - exiting\n");
3201 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3208 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3209 fprintf(stderr, "Could not open '%s'\n", filename);
3214 memset(ap, 0, sizeof(*ap));
3215 ap->image_format = image_format;
3216 if (av_set_parameters(oc, ap) < 0) {
3217 fprintf(stderr, "%s: Invalid encoding parameters\n",
3222 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3223 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3224 oc->loop_output = loop_output;
3226 for(i=0; i<opt_name_count; i++){
3228 double d = av_get_double(avformat_opts, opt_names[i], &opt);
3229 if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3230 av_set_double(oc, opt_names[i], d);
3233 /* reset some options */
3234 file_oformat = NULL;
3235 file_iformat = NULL;
3236 image_format = NULL;
3239 /* prepare dummy protocols for grab */
3240 static void prepare_grab(void)
3242 int has_video, has_audio, i, j;
3243 AVFormatContext *oc;
3244 AVFormatContext *ic;
3245 AVFormatParameters vp1, *vp = &vp1;
3246 AVFormatParameters ap1, *ap = &ap1;
3248 /* see if audio/video inputs are needed */
3251 memset(ap, 0, sizeof(*ap));
3252 memset(vp, 0, sizeof(*vp));
3253 vp->time_base.num= 1;
3254 for(j=0;j<nb_output_files;j++) {
3255 oc = output_files[j];
3256 for(i=0;i<oc->nb_streams;i++) {
3257 AVCodecContext *enc = oc->streams[i]->codec;
3258 switch(enc->codec_type) {
3259 case CODEC_TYPE_AUDIO:
3260 if (enc->sample_rate > ap->sample_rate)
3261 ap->sample_rate = enc->sample_rate;
3262 if (enc->channels > ap->channels)
3263 ap->channels = enc->channels;
3266 case CODEC_TYPE_VIDEO:
3267 if (enc->width > vp->width)
3268 vp->width = enc->width;
3269 if (enc->height > vp->height)
3270 vp->height = enc->height;
3272 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3273 vp->time_base = enc->time_base;
3274 vp->width += frame_leftBand + frame_rightBand;
3275 vp->width -= (frame_padleft + frame_padright);
3276 vp->height += frame_topBand + frame_bottomBand;
3277 vp->height -= (frame_padtop + frame_padbottom);
3287 if (has_video == 0 && has_audio == 0) {
3288 fprintf(stderr, "Output file must have at least one audio or video stream\n");
3293 AVInputFormat *fmt1;
3294 fmt1 = av_find_input_format(video_grab_format);
3295 vp->device = video_device;
3296 vp->channel = video_channel;
3297 vp->standard = video_standard;
3298 vp->pix_fmt = frame_pix_fmt;
3299 if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3300 fprintf(stderr, "Could not find video grab device\n");
3303 /* If not enough info to get the stream parameters, we decode the
3304 first frames to get it. */
3305 if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3306 fprintf(stderr, "Could not find video grab parameters\n");
3309 /* by now video grab has one stream */
3310 ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3311 ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3312 input_files[nb_input_files] = ic;
3315 dump_format(ic, nb_input_files, "", 0);
3319 if (has_audio && audio_grab_format) {
3320 AVInputFormat *fmt1;
3321 fmt1 = av_find_input_format(audio_grab_format);
3322 ap->device = audio_device;
3323 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3324 fprintf(stderr, "Could not find audio grab device\n");
3327 input_files[nb_input_files] = ic;
3330 dump_format(ic, nb_input_files, "", 0);
3336 /* same option as mencoder */
3337 static void opt_pass(const char *pass_str)
3340 pass = atoi(pass_str);
3341 if (pass != 1 && pass != 2) {
3342 fprintf(stderr, "pass number can be only 1 or 2\n");
3348 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3349 static int64_t getutime(void)
3351 return av_gettime();
3354 static int64_t getutime(void)
3356 struct rusage rusage;
3358 getrusage(RUSAGE_SELF, &rusage);
3359 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3363 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3364 extern int ffm_nopts;
3367 static void show_formats(void)
3369 AVInputFormat *ifmt;
3370 AVOutputFormat *ofmt;
3371 AVImageFormat *image_fmt;
3374 const char **pp, *last_name;
3376 printf("File formats:\n");
3381 const char *name=NULL;
3382 const char *long_name=NULL;
3384 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3385 if((name == NULL || strcmp(ofmt->name, name)<0) &&
3386 strcmp(ofmt->name, last_name)>0){
3388 long_name= ofmt->long_name;
3392 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3393 if((name == NULL || strcmp(ifmt->name, name)<0) &&
3394 strcmp(ifmt->name, last_name)>0){
3396 long_name= ifmt->long_name;
3399 if(name && strcmp(ifmt->name, name)==0)
3411 long_name ? long_name:" ");
3415 printf("Image formats (filename extensions, if any, follow):\n");
3416 for(image_fmt = first_image_format; image_fmt != NULL;
3417 image_fmt = image_fmt->next) {
3420 image_fmt->img_read ? "D":" ",
3421 image_fmt->img_write ? "E":" ",
3423 image_fmt->extensions ? image_fmt->extensions:" ");
3427 printf("Codecs:\n");
3433 const char *type_str;
3436 for(p = first_avcodec; p != NULL; p = p->next) {
3437 if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3438 strcmp(p->name, last_name)>0){
3440 decode= encode= cap=0;
3442 if(p2 && strcmp(p->name, p2->name)==0){
3443 if(p->decode) decode=1;
3444 if(p->encode) encode=1;
3445 cap |= p->capabilities;
3450 last_name= p2->name;
3453 case CODEC_TYPE_VIDEO:
3456 case CODEC_TYPE_AUDIO:
3459 case CODEC_TYPE_SUBTITLE:
3468 decode ? "D": (/*p2->decoder ? "d":*/" "),
3471 cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3472 cap & CODEC_CAP_DR1 ? "D":" ",
3473 cap & CODEC_CAP_TRUNCATED ? "T":" ",
3475 /* if(p2->decoder && decode==0)
3476 printf(" use %s for decoding", p2->decoder->name);*/
3481 printf("Supported file protocols:\n");
3482 for(up = first_protocol; up != NULL; up = up->next)
3483 printf(" %s:", up->name);
3486 printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3487 printf("Motion estimation methods:\n");
3491 if ((pp - motion_str + 1) == ME_ZERO)
3492 printf("(fastest)");
3493 else if ((pp - motion_str + 1) == ME_FULL)
3494 printf("(slowest)");
3495 else if ((pp - motion_str + 1) == ME_EPZS)
3496 printf("(default)");
3501 "Note, the names of encoders and decoders dont always match, so there are\n"
3502 "several cases where the above table shows encoder only or decoder only entries\n"
3503 "even though both encoding and decoding are supported for example, the h263\n"
3504 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3509 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3512 const char *p = str;
3519 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3526 static void opt_inter_matrix(const char *arg)
3528 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3529 parse_matrix_coeffs(inter_matrix, arg);
3532 static void opt_intra_matrix(const char *arg)
3534 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3535 parse_matrix_coeffs(intra_matrix, arg);
3538 static void opt_target(const char *arg)
3541 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3543 if(!strncmp(arg, "pal-", 4)) {
3546 } else if(!strncmp(arg, "ntsc-", 5)) {
3549 } else if(!strncmp(arg, "film-", 5)) {
3554 /* Calculate FR via float to avoid int overflow */
3555 fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3558 } else if((fr == 29970) || (fr == 23976)) {
3561 /* Try to determine PAL/NTSC by peeking in the input files */
3562 if(nb_input_files) {
3564 for(j = 0; j < nb_input_files; j++) {
3565 for(i = 0; i < input_files[j]->nb_streams; i++) {
3566 AVCodecContext *c = input_files[j]->streams[i]->codec;
3567 if(c->codec_type != CODEC_TYPE_VIDEO)
3569 fr = c->time_base.den * 1000 / c->time_base.num;
3573 } else if((fr == 29970) || (fr == 23976)) {
3583 if(verbose && norm >= 0)
3584 fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3588 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3589 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3590 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3594 if(!strcmp(arg, "vcd")) {
3596 opt_video_codec("mpeg1video");
3597 opt_audio_codec("mp2");
3600 opt_frame_size(norm ? "352x240" : "352x288");
3601 opt_frame_rate(frame_rates[norm]);
3602 opt_default("gop", norm ? "18" : "15");
3604 opt_default("b", "1150000");
3605 opt_default("maxrate", "1150000");
3606 opt_default("minrate", "1150000");
3607 opt_default("bufsize", "327680"); // 40*1024*8;
3609 audio_bit_rate = 224000;
3610 audio_sample_rate = 44100;
3612 opt_default("packetsize", "2324");
3613 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3615 /* We have to offset the PTS, so that it is consistent with the SCR.
3616 SCR starts at 36000, but the first two packs contain only padding
3617 and the first pack from the other stream, respectively, may also have
3618 been written before.
3619 So the real data starts at SCR 36000+3*1200. */
3620 mux_preload= (36000+3*1200) / 90000.0; //0.44
3621 } else if(!strcmp(arg, "svcd")) {
3623 opt_video_codec("mpeg2video");
3624 opt_audio_codec("mp2");
3627 opt_frame_size(norm ? "480x480" : "480x576");
3628 opt_frame_rate(frame_rates[norm]);
3629 opt_default("gop", norm ? "18" : "15");
3631 opt_default("b", "2040000");
3632 opt_default("maxrate", "2516000");
3633 opt_default("minrate", "0"); //1145000;
3634 opt_default("bufsize", "1835008"); //224*1024*8;
3635 opt_default("flags", "+SCAN_OFFSET");
3638 audio_bit_rate = 224000;
3639 audio_sample_rate = 44100;
3641 opt_default("packetsize", "2324");
3643 } else if(!strcmp(arg, "dvd")) {
3645 opt_video_codec("mpeg2video");
3646 opt_audio_codec("ac3");
3649 opt_frame_size(norm ? "720x480" : "720x576");
3650 opt_frame_rate(frame_rates[norm]);
3651 opt_default("gop", norm ? "18" : "15");
3653 opt_default("b", "6000000");
3654 opt_default("maxrate", "9000000");
3655 opt_default("minrate", "0"); //1500000;
3656 opt_default("bufsize", "1835008"); //224*1024*8;
3658 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3659 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3661 audio_bit_rate = 448000;
3662 audio_sample_rate = 48000;
3664 } else if(!strncmp(arg, "dv", 2)) {
3668 opt_frame_size(norm ? "720x480" : "720x576");
3669 opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3670 (norm ? "yuv411p" : "yuv420p"));
3671 opt_frame_rate(frame_rates[norm]);
3673 audio_sample_rate = 48000;
3677 fprintf(stderr, "Unknown target: %s\n", arg);
3682 static void opt_video_bsf(const char *arg)
3684 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3685 AVBitStreamFilterContext **bsfp;
3688 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3692 bsfp= &video_bitstream_filters;
3694 bsfp= &(*bsfp)->next;
3699 //FIXME avoid audio - video code duplication
3700 static void opt_audio_bsf(const char *arg)
3702 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3703 AVBitStreamFilterContext **bsfp;
3706 fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3710 bsfp= &audio_bitstream_filters;
3712 bsfp= &(*bsfp)->next;
3717 static void show_version(void)
3719 /* TODO: add function interface to avutil and avformat */
3720 fprintf(stderr, "ffmpeg " FFMPEG_VERSION "\n"
3724 LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3728 static int opt_default(const char *opt, const char *arg){
3729 AVOption *o= av_set_string(avctx_opts, opt, arg);