3 * Copyright (c) 2000, 2001, 2002 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #define HAVE_AV_CONFIG_H
25 #include <sys/ioctl.h>
28 #include <sys/resource.h>
38 #define MAXINT64 INT64_C(0x7fffffffffffffff)
43 #define HAS_ARG 0x0001
44 #define OPT_BOOL 0x0002
45 #define OPT_EXPERT 0x0004
46 #define OPT_STRING 0x0008
56 /* select an input stream for an output stream */
57 typedef struct AVStreamMap {
62 extern const OptionDef options[];
68 static AVFormatContext *input_files[MAX_FILES];
69 static int nb_input_files = 0;
71 static AVFormatContext *output_files[MAX_FILES];
72 static int nb_output_files = 0;
74 static AVStreamMap stream_maps[MAX_FILES];
75 static int nb_stream_maps;
77 static AVInputFormat *file_iformat;
78 static AVOutputFormat *file_oformat;
79 static int frame_width = 160;
80 static int frame_height = 128;
81 static int frame_topBand = 0;
82 static int frame_bottomBand = 0;
83 static int frame_leftBand = 0;
84 static int frame_rightBand = 0;
85 static int frame_rate = 25 * FRAME_RATE_BASE;
86 static int video_bit_rate = 200*1000;
87 static int video_bit_rate_tolerance = 4000*1000;
88 static int video_qscale = 0;
89 static int video_qmin = 2;
90 static int video_qmax = 31;
91 static int video_qdiff = 3;
92 static float video_qblur = 0.5;
93 static float video_qcomp = 0.5;
94 #if 0 //experimental, (can be removed)
95 static float video_rc_qsquish=1.0;
96 static float video_rc_qmod_amp=0;
97 static int video_rc_qmod_freq=0;
99 static char *video_rc_override_string=NULL;
100 static char *video_rc_eq="tex^qComp";
101 static int video_rc_buffer_size=0;
102 static float video_rc_buffer_aggressivity=1.0;
103 static int video_rc_max_rate=0;
104 static int video_rc_min_rate=0;
105 static float video_rc_initial_cplx=0;
106 static float video_b_qfactor = 1.25;
107 static float video_b_qoffset = 1.25;
108 static float video_i_qfactor = -0.8;
109 static float video_i_qoffset = 0.0;
110 static int me_method = 0;
111 static int video_disable = 0;
112 static int video_codec_id = CODEC_ID_NONE;
113 static int same_quality = 0;
114 static int b_frames = 0;
115 static int use_hq = 0;
116 static int use_4mv = 0;
117 static int do_deinterlace = 0;
118 static int workaround_bugs = FF_BUG_AUTODETECT;
119 static int error_resilience = 2;
120 static int error_concealment = 3;
121 static int dct_algo = 0;
122 static int idct_algo = 0;
123 static int use_part = 0;
124 static int packet_size = 0;
126 static int gop_size = 12;
127 static int intra_only = 0;
128 static int audio_sample_rate = 44100;
129 static int audio_bit_rate = 64000;
130 static int audio_disable = 0;
131 static int audio_channels = 1;
132 static int audio_codec_id = CODEC_ID_NONE;
134 static INT64 recording_time = 0;
135 static int file_overwrite = 0;
136 static char *str_title = NULL;
137 static char *str_author = NULL;
138 static char *str_copyright = NULL;
139 static char *str_comment = NULL;
140 static int do_benchmark = 0;
141 static int do_hex_dump = 0;
142 static int do_play = 0;
143 static int do_psnr = 0;
144 static int do_vstats = 0;
145 static int do_pass = 0;
146 static char *pass_logfilename = NULL;
147 static int audio_stream_copy = 0;
148 static int video_stream_copy = 0;
150 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
152 #ifndef CONFIG_AUDIO_OSS
153 const char *audio_device = "none";
155 #ifndef CONFIG_VIDEO4LINUX
156 const char *v4l_device = "none";
159 typedef struct AVOutputStream {
160 int file_index; /* file index */
161 int index; /* stream index in the output file */
162 int source_index; /* AVInputStream index */
163 AVStream *st; /* stream in the output file */
164 int encoding_needed; /* true if encoding needed for this stream */
166 /* input pts and corresponding output pts
171 AVPicture pict_tmp; /* temporary image for resizing */
173 ImgReSampleContext *img_resample_ctx; /* for image resampling */
177 ReSampleContext *resample; /* for audio resampling */
178 FifoBuffer fifo; /* for compression: one audio fifo per codec */
182 typedef struct AVInputStream {
186 int discard; /* true if stream data should be discarded */
187 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
188 INT64 sample_index; /* current sample */
189 int frame_decoded; /* true if a video or audio frame has been decoded */
192 typedef struct AVInputFile {
193 int eof_reached; /* true if eof reached */
194 int ist_index; /* index of first stream in ist_table */
195 int buffer_size; /* current total buffer size */
196 int buffer_size_max; /* buffer size at which we consider we can stop
198 int nb_streams; /* nb streams we are aware of */
203 /* init terminal so that we can grab keys */
204 static struct termios oldtty;
206 static void term_exit(void)
208 tcsetattr (0, TCSANOW, &oldtty);
211 static void term_init(void)
218 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
219 |INLCR|IGNCR|ICRNL|IXON);
220 tty.c_oflag |= OPOST;
221 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
222 tty.c_cflag &= ~(CSIZE|PARENB);
227 tcsetattr (0, TCSANOW, &tty);
232 /* read a key without blocking */
233 static int read_key(void)
244 n = select(1, &rfds, NULL, NULL, &tv);
257 /* no interactive support */
258 static void term_exit(void)
262 static void term_init(void)
266 static int read_key(void)
273 int read_ffserver_streams(AVFormatContext *s, const char *filename)
278 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
281 /* copy stream format */
282 s->nb_streams = ic->nb_streams;
283 for(i=0;i<ic->nb_streams;i++) {
285 st = av_mallocz(sizeof(AVFormatContext));
286 memcpy(st, ic->streams[i], sizeof(AVStream));
290 av_close_input_file(ic);
294 #define MAX_AUDIO_PACKET_SIZE 16384
296 static void do_audio_out(AVFormatContext *s,
299 unsigned char *buf, int size)
302 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
303 UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
304 int size_out, frame_bytes, ret;
307 enc = &ost->st->codec;
309 if (ost->audio_resample) {
311 size_out = audio_resample(ost->resample,
312 (short *)buftmp, (short *)buf,
313 size / (ist->st->codec.channels * 2));
314 size_out = size_out * enc->channels * 2;
320 /* now encode as many frames as possible */
321 if (enc->frame_size > 1) {
322 /* output resampled raw samples */
323 fifo_write(&ost->fifo, buftmp, size_out,
326 frame_bytes = enc->frame_size * 2 * enc->channels;
328 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
329 &ost->fifo.rptr) == 0) {
330 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
332 av_write_frame(s, ost->index, audio_out, ret);
335 /* output a pcm frame */
336 /* XXX: change encoding codec API to avoid this ? */
337 switch(enc->codec->id) {
338 case CODEC_ID_PCM_S16LE:
339 case CODEC_ID_PCM_S16BE:
340 case CODEC_ID_PCM_U16LE:
341 case CODEC_ID_PCM_U16BE:
344 size_out = size_out >> 1;
347 ret = avcodec_encode_audio(enc, audio_out, size_out,
349 av_write_frame(s, ost->index, audio_out, ret);
353 /* write a picture to a raw mux */
354 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
355 int pix_fmt, int w, int h)
357 UINT8 *buf, *src, *dest;
360 /* XXX: not efficient, should add test if we can take
361 directly the AVPicture */
363 case PIX_FMT_YUV420P:
364 size = avpicture_get_size(pix_fmt, w, h);
365 buf = av_malloc(size);
374 src = picture->data[i];
376 memcpy(dest, src, w);
378 src += picture->linesize[i];
382 case PIX_FMT_YUV422P:
384 buf = av_malloc(size);
392 src = picture->data[i];
394 memcpy(dest, src, w);
396 src += picture->linesize[i];
400 case PIX_FMT_YUV444P:
402 buf = av_malloc(size);
407 src = picture->data[i];
409 memcpy(dest, src, w);
411 src += picture->linesize[i];
417 buf = av_malloc(size);
421 src = picture->data[0];
423 memcpy(dest, src, w * 2);
425 src += picture->linesize[0];
431 buf = av_malloc(size);
435 src = picture->data[0];
437 memcpy(dest, src, w * 3);
439 src += picture->linesize[0];
445 av_write_frame(s, index, buf, size);
449 /* we begin to correct av delay at this threshold */
450 #define AV_DELAY_MAX 0.100
452 static void do_video_out(AVFormatContext *s,
456 int *frame_size, AVOutputStream *audio_sync)
458 int nb_frames, i, ret;
459 AVPicture *picture, *picture2, *pict;
460 AVPicture picture_tmp1, picture_tmp2;
461 static UINT8 *video_buffer;
462 UINT8 *buf = NULL, *buf1 = NULL;
463 AVCodecContext *enc, *dec;
465 #define VIDEO_BUFFER_SIZE (1024*1024)
467 enc = &ost->st->codec;
468 dec = &ist->st->codec;
470 /* by default, we output a single frame */
473 /* NOTE: the A/V sync is always done by considering the audio is
474 the master clock. It is suffisant for transcoding or playing,
475 but not for the general case */
477 /* compute the A-V delay and duplicate/remove frames if needed */
478 double adelta, vdelta, apts, vpts, av_delay;
480 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
481 ost->sync_ipts != AV_NOPTS_VALUE) {
483 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
484 s->pts_num / s->pts_den;
485 apts = audio_sync->sync_ipts + adelta;
487 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
488 s->pts_num / s->pts_den;
489 vpts = ost->sync_ipts + vdelta;
491 av_delay = apts - vpts;
492 // printf("delay=%f\n", av_delay);
493 if (av_delay < -AV_DELAY_MAX)
495 else if (av_delay > AV_DELAY_MAX)
499 /* XXX: also handle frame rate conversion */
504 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
508 /* deinterlace : must be done before any resize */
509 if (do_deinterlace) {
512 /* create temporary picture */
513 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
514 buf1 = av_malloc(size);
518 picture2 = &picture_tmp2;
519 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
521 if (avpicture_deinterlace(picture2, picture1,
522 dec->pix_fmt, dec->width, dec->height) < 0) {
523 /* if error, do not deinterlace */
532 /* convert pixel format if needed */
533 if (enc->pix_fmt != dec->pix_fmt) {
536 /* create temporary picture */
537 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
538 buf = av_malloc(size);
541 pict = &picture_tmp1;
542 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
544 if (img_convert(pict, enc->pix_fmt,
545 picture2, dec->pix_fmt,
546 dec->width, dec->height) < 0) {
547 fprintf(stderr, "pixel format conversion not handled\n");
554 /* XXX: resampling could be done before raw format convertion in
555 some cases to go faster */
556 /* XXX: only works for YUV420P */
557 if (ost->video_resample) {
558 picture = &ost->pict_tmp;
559 img_resample(ost->img_resample_ctx, picture, pict);
563 /* duplicates frame if needed */
564 /* XXX: pb because no interleaving */
565 for(i=0;i<nb_frames;i++) {
566 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
567 /* handles sameq here. This is not correct because it may
568 not be a global option */
570 enc->quality = dec->quality;
573 ret = avcodec_encode_video(enc,
574 video_buffer, VIDEO_BUFFER_SIZE,
576 //enc->frame_number = enc->real_pict_num;
577 av_write_frame(s, ost->index, video_buffer, ret);
579 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
580 // enc->frame_number-1, enc->real_pict_num, ret,
582 /* if two pass, output log */
583 if (ost->logfile && enc->stats_out) {
584 fprintf(ost->logfile, "%s", enc->stats_out);
587 if (s->oformat->flags & AVFMT_RAWPICTURE) {
588 /* raw pictures are written as AVPicture structure to
589 avoid any copies. We support temorarily the older
591 av_write_frame(s, ost->index,
592 (UINT8 *)picture, sizeof(AVPicture));
594 write_picture(s, ost->index, picture, enc->pix_fmt,
595 enc->width, enc->height);
605 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
608 static FILE *fvstats=NULL;
609 static INT64 total_size = 0;
616 double ti1, bitrate, avg_bitrate;
620 today = localtime(&today2);
621 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
624 fvstats = fopen(filename,"w");
632 enc = &ost->st->codec;
633 total_size += frame_size;
634 if (enc->codec_type == CODEC_TYPE_VIDEO) {
635 frame_number = ost->frame_number;
636 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
638 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
640 fprintf(fvstats,"f_size= %6d ", frame_size);
641 /* compute pts value */
642 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
646 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
647 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
648 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
649 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
650 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
654 void print_report(AVFormatContext **output_files,
655 AVOutputStream **ost_table, int nb_ostreams,
660 AVFormatContext *oc, *os;
663 int frame_number, vid, i;
664 double bitrate, ti1, pts;
665 static INT64 last_time = -1;
667 if (!is_last_report) {
669 /* display the report every 0.5 seconds */
670 cur_time = av_gettime();
671 if (last_time == -1) {
672 last_time = cur_time;
675 if ((cur_time - last_time) < 500000)
677 last_time = cur_time;
681 oc = output_files[0];
683 total_size = url_ftell(&oc->pb);
688 for(i=0;i<nb_ostreams;i++) {
690 os = output_files[ost->file_index];
691 enc = &ost->st->codec;
692 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
693 frame_number = ost->frame_number;
694 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
695 frame_number, enc->quality);
697 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
700 /* compute min output value */
701 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
702 if ((pts < ti1) && (pts > 0))
707 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
709 sprintf(buf + strlen(buf),
710 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
711 (double)total_size / 1024, ti1, bitrate);
713 fprintf(stderr, "%s ", buf);
715 if (is_last_report) {
716 fprintf(stderr, "\n");
718 fprintf(stderr, "\r");
724 * The following code is the main loop of the file converter
726 static int av_encode(AVFormatContext **output_files,
728 AVFormatContext **input_files,
730 AVStreamMap *stream_maps, int nb_stream_maps)
732 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
733 AVFormatContext *is, *os;
734 AVCodecContext *codec, *icodec;
735 AVOutputStream *ost, **ost_table = NULL;
736 AVInputStream *ist, **ist_table = NULL;
737 AVInputFile *file_table;
738 AVFormatContext *stream_no_data;
741 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
745 /* input stream init */
747 for(i=0;i<nb_input_files;i++) {
749 file_table[i].ist_index = j;
750 file_table[i].nb_streams = is->nb_streams;
755 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
759 for(i=0;i<nb_istreams;i++) {
760 ist = av_mallocz(sizeof(AVInputStream));
766 for(i=0;i<nb_input_files;i++) {
768 for(k=0;k<is->nb_streams;k++) {
769 ist = ist_table[j++];
770 ist->st = is->streams[k];
773 ist->discard = 1; /* the stream is discarded by default
778 /* output stream init */
780 for(i=0;i<nb_output_files;i++) {
781 os = output_files[i];
782 nb_ostreams += os->nb_streams;
784 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
785 fprintf(stderr, "Number of stream maps must match number of output streams\n");
789 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
792 for(i=0;i<nb_ostreams;i++) {
793 ost = av_mallocz(sizeof(AVOutputStream));
800 for(k=0;k<nb_output_files;k++) {
801 os = output_files[k];
802 for(i=0;i<os->nb_streams;i++) {
804 ost = ost_table[n++];
807 ost->st = os->streams[i];
808 if (nb_stream_maps > 0) {
809 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
810 stream_maps[n-1].stream_index;
812 /* get corresponding input stream index : we select the first one with the right type */
814 for(j=0;j<nb_istreams;j++) {
817 ist->st->codec.codec_type == ost->st->codec.codec_type) {
818 ost->source_index = j;
824 /* try again and reuse existing stream */
825 for(j=0;j<nb_istreams;j++) {
827 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
828 ost->source_index = j;
833 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
834 ost->file_index, ost->index);
839 ist = ist_table[ost->source_index];
844 /* for each output stream, we compute the right encoding parameters */
845 for(i=0;i<nb_ostreams;i++) {
847 ist = ist_table[ost->source_index];
849 codec = &ost->st->codec;
850 icodec = &ist->st->codec;
852 if (ost->st->stream_copy) {
853 /* if stream_copy is selected, no need to decode or encode */
854 codec->codec_id = icodec->codec_id;
855 codec->codec_type = icodec->codec_type;
856 codec->codec_tag = icodec->codec_tag;
857 codec->bit_rate = icodec->bit_rate;
858 switch(codec->codec_type) {
859 case CODEC_TYPE_AUDIO:
860 codec->sample_rate = icodec->sample_rate;
861 codec->channels = icodec->channels;
863 case CODEC_TYPE_VIDEO:
864 codec->frame_rate = icodec->frame_rate;
865 codec->width = icodec->width;
866 codec->height = icodec->height;
872 switch(codec->codec_type) {
873 case CODEC_TYPE_AUDIO:
874 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
877 if (codec->channels == icodec->channels &&
878 codec->sample_rate == icodec->sample_rate) {
879 ost->audio_resample = 0;
881 if (codec->channels != icodec->channels &&
882 icodec->codec_id == CODEC_ID_AC3) {
883 /* Special case for 5:1 AC3 input */
884 /* and mono or stereo output */
885 /* Request specific number of channels */
886 icodec->channels = codec->channels;
887 if (codec->sample_rate == icodec->sample_rate)
888 ost->audio_resample = 0;
890 ost->audio_resample = 1;
891 ost->resample = audio_resample_init(codec->channels, icodec->channels,
893 icodec->sample_rate);
895 /* Request specific number of channels */
896 icodec->channels = codec->channels;
898 ost->audio_resample = 1;
899 ost->resample = audio_resample_init(codec->channels, icodec->channels,
901 icodec->sample_rate);
904 ist->decoding_needed = 1;
905 ost->encoding_needed = 1;
907 case CODEC_TYPE_VIDEO:
908 if (codec->width == icodec->width &&
909 codec->height == icodec->height) {
910 ost->video_resample = 0;
913 ost->video_resample = 1;
914 buf = av_malloc((codec->width * codec->height * 3) / 2);
917 ost->pict_tmp.data[0] = buf;
918 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
919 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
920 ost->pict_tmp.linesize[0] = codec->width;
921 ost->pict_tmp.linesize[1] = codec->width / 2;
922 ost->pict_tmp.linesize[2] = codec->width / 2;
924 ost->img_resample_ctx = img_resample_full_init(
925 ost->st->codec.width, ost->st->codec.height,
926 ist->st->codec.width, ist->st->codec.height,
927 frame_topBand, frame_bottomBand,
928 frame_leftBand, frame_rightBand);
930 ost->encoding_needed = 1;
931 ist->decoding_needed = 1;
937 if (ost->encoding_needed &&
938 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
939 char logfilename[1024];
944 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
946 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
947 if (codec->flags & CODEC_FLAG_PASS1) {
948 f = fopen(logfilename, "w");
955 /* read the log file */
956 f = fopen(logfilename, "r");
961 fseek(f, 0, SEEK_END);
963 fseek(f, 0, SEEK_SET);
964 logbuffer = av_malloc(size + 1);
966 fprintf(stderr, "Could not allocate log buffer\n");
969 fread(logbuffer, 1, size, f);
971 logbuffer[size] = '\0';
972 codec->stats_in = logbuffer;
978 /* dump the file output parameters - cannot be done before in case
980 for(i=0;i<nb_output_files;i++) {
981 dump_format(output_files[i], i, output_files[i]->filename, 1);
984 /* dump the stream mapping */
985 fprintf(stderr, "Stream mapping:\n");
986 for(i=0;i<nb_ostreams;i++) {
988 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
989 ist_table[ost->source_index]->file_index,
990 ist_table[ost->source_index]->index,
995 /* open each encoder */
996 for(i=0;i<nb_ostreams;i++) {
998 if (ost->encoding_needed) {
1000 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1002 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1003 ost->file_index, ost->index);
1006 if (avcodec_open(&ost->st->codec, codec) < 0) {
1007 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1008 ost->file_index, ost->index);
1014 /* open each decoder */
1015 for(i=0;i<nb_istreams;i++) {
1017 if (ist->decoding_needed) {
1019 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1021 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
1022 ist->file_index, ist->index);
1025 if (avcodec_open(&ist->st->codec, codec) < 0) {
1026 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1027 ist->file_index, ist->index);
1030 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1031 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1032 ist->frame_decoded = 1;
1037 for(i=0;i<nb_istreams;i++) {
1041 /* compute buffer size max (should use a complete heuristic) */
1042 for(i=0;i<nb_input_files;i++) {
1043 file_table[i].buffer_size_max = 2048;
1046 /* open files and write file headers */
1047 for(i=0;i<nb_output_files;i++) {
1048 os = output_files[i];
1049 if (av_write_header(os) < 0) {
1050 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1056 #ifndef CONFIG_WIN32
1058 fprintf(stderr, "Press [q] to stop encoding\n");
1060 fprintf(stderr, "Press [q] to stop playing\n");
1069 int file_index, ist_index;
1074 int data_size, got_picture;
1076 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1080 /* if 'q' pressed, exits */
1082 /* read_key() returns 0 on EOF */
1088 /* select the stream that we must read now by looking at the
1089 smallest output pts */
1092 for(i=0;i<nb_ostreams;i++) {
1095 os = output_files[ost->file_index];
1096 ist = ist_table[ost->source_index];
1097 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1098 if (!file_table[ist->file_index].eof_reached &&
1101 file_index = ist->file_index;
1104 /* if none, if is finished */
1105 if (file_index < 0) {
1109 /* finish if recording time exhausted */
1110 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1113 /* read a packet from it and output it in the fifo */
1114 is = input_files[file_index];
1115 if (av_read_packet(is, &pkt) < 0) {
1116 file_table[file_index].eof_reached = 1;
1120 stream_no_data = is;
1124 /* the following test is needed in case new streams appear
1125 dynamically in stream : we ignore them */
1126 if (pkt.stream_index >= file_table[file_index].nb_streams)
1127 goto discard_packet;
1128 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1129 ist = ist_table[ist_index];
1131 goto discard_packet;
1134 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1135 av_hex_dump(pkt.data, pkt.size);
1138 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1146 ipts = AV_NOPTS_VALUE;
1148 /* decode the packet if needed */
1149 data_buf = NULL; /* fail safe */
1151 if (ist->decoding_needed) {
1152 /* NOTE1: we only take into account the PTS if a new
1153 frame has begun (MPEG semantics) */
1154 /* NOTE2: even if the fraction is not initialized,
1155 av_frac_set can be used to set the integer part */
1156 if (ist->frame_decoded &&
1157 pkt.pts != AV_NOPTS_VALUE &&
1160 ist->frame_decoded = 0;
1164 switch(ist->st->codec.codec_type) {
1165 case CODEC_TYPE_AUDIO:
1166 /* XXX: could avoid copy if PCM 16 bits with same
1167 endianness as CPU */
1168 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1172 /* Some bug in mpeg audio decoder gives */
1173 /* data_size < 0, it seems they are overflows */
1174 if (data_size <= 0) {
1175 /* no audio frame */
1180 data_buf = (UINT8 *)samples;
1182 case CODEC_TYPE_VIDEO:
1183 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1186 size = (ist->st->codec.width * ist->st->codec.height);
1187 avpicture_fill(&picture, ptr,
1188 ist->st->codec.pix_fmt,
1189 ist->st->codec.width,
1190 ist->st->codec.height);
1193 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1194 ret = avcodec_decode_video(&ist->st->codec,
1195 &picture, &got_picture, ptr, len);
1198 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1199 ist->file_index, ist->index);
1200 av_free_packet(&pkt);
1204 /* no picture yet */
1223 ist->frame_decoded = 1;
1226 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1227 is the one of the next displayed one */
1228 /* XXX: add mpeg4 too ? */
1229 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1230 if (ist->st->codec.pict_type != B_TYPE) {
1232 tmp = ist->last_ip_pts;
1233 ist->last_ip_pts = ist->frac_pts.val;
1234 ist->frac_pts.val = tmp;
1238 /* transcode raw format, encode packets and output them */
1240 for(i=0;i<nb_ostreams;i++) {
1244 if (ost->source_index == ist_index) {
1245 os = output_files[ost->file_index];
1247 if (ipts != AV_NOPTS_VALUE) {
1249 printf("%d: got pts=%f %f\n",
1250 i, pkt.pts / 90000.0,
1251 (ipts - ost->st->pts.val) / 90000.0);
1253 /* set the input output pts pairs */
1254 ost->sync_ipts = (double)ipts * is->pts_num /
1256 /* XXX: take into account the various fifos,
1257 in particular for audio */
1258 ost->sync_opts = ost->st->pts.val;
1261 if (ost->encoding_needed) {
1262 switch(ost->st->codec.codec_type) {
1263 case CODEC_TYPE_AUDIO:
1264 do_audio_out(os, ost, ist, data_buf, data_size);
1266 case CODEC_TYPE_VIDEO:
1267 /* find an audio stream for synchro */
1270 AVOutputStream *audio_sync, *ost1;
1272 for(i=0;i<nb_ostreams;i++) {
1273 ost1 = ost_table[i];
1274 if (ost1->file_index == ost->file_index &&
1275 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1281 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1283 do_video_stats(os, ost, frame_size);
1290 /* no reencoding needed : output the packet directly */
1291 /* force the input stream PTS */
1292 av_write_frame(os, ost->index, data_buf, data_size);
1293 ost->st->codec.frame_number++;
1297 ipts = AV_NOPTS_VALUE;
1300 av_free_packet(&pkt);
1302 /* dump report by using the output first video and audio streams */
1303 print_report(output_files, ost_table, nb_ostreams, 0);
1307 /* dump report by using the first video and audio streams */
1308 print_report(output_files, ost_table, nb_ostreams, 1);
1310 /* close each encoder */
1311 for(i=0;i<nb_ostreams;i++) {
1313 if (ost->encoding_needed) {
1314 av_freep(&ost->st->codec.stats_in);
1315 avcodec_close(&ost->st->codec);
1319 /* close each decoder */
1320 for(i=0;i<nb_istreams;i++) {
1322 if (ist->decoding_needed) {
1323 avcodec_close(&ist->st->codec);
1328 /* write the trailer if needed and close file */
1329 for(i=0;i<nb_output_files;i++) {
1330 os = output_files[i];
1331 av_write_trailer(os);
1337 av_free(file_table);
1340 for(i=0;i<nb_istreams;i++) {
1347 for(i=0;i<nb_ostreams;i++) {
1351 fclose(ost->logfile);
1352 ost->logfile = NULL;
1354 fifo_free(&ost->fifo); /* works even if fifo is not
1355 initialized but set to zero */
1356 av_free(ost->pict_tmp.data[0]);
1357 if (ost->video_resample)
1358 img_resample_close(ost->img_resample_ctx);
1359 if (ost->audio_resample)
1360 audio_resample_close(ost->resample);
1373 int file_read(const char *filename)
1376 unsigned char buffer[1024];
1379 if (url_open(&h, filename, O_RDONLY) < 0) {
1380 printf("could not open '%s'\n", filename);
1384 len = url_read(h, buffer, sizeof(buffer));
1387 for(i=0;i<len;i++) putchar(buffer[i]);
1394 void show_licence(void)
1397 "ffmpeg version " FFMPEG_VERSION "\n"
1398 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1399 "This library is free software; you can redistribute it and/or\n"
1400 "modify it under the terms of the GNU Lesser General Public\n"
1401 "License as published by the Free Software Foundation; either\n"
1402 "version 2 of the License, or (at your option) any later version.\n"
1404 "This library is distributed in the hope that it will be useful,\n"
1405 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1406 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1407 "Lesser General Public License for more details.\n"
1409 "You should have received a copy of the GNU Lesser General Public\n"
1410 "License along with this library; if not, write to the Free Software\n"
1411 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1416 void opt_format(const char *arg)
1418 file_iformat = av_find_input_format(arg);
1419 file_oformat = guess_format(arg, NULL, NULL);
1420 if (!file_iformat && !file_oformat) {
1421 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1426 void opt_video_bitrate(const char *arg)
1428 video_bit_rate = atoi(arg) * 1000;
1431 void opt_video_bitrate_tolerance(const char *arg)
1433 video_bit_rate_tolerance = atoi(arg) * 1000;
1436 void opt_video_bitrate_max(const char *arg)
1438 video_rc_max_rate = atoi(arg) * 1000;
1441 void opt_video_bitrate_min(const char *arg)
1443 video_rc_min_rate = atoi(arg) * 1000;
1446 void opt_video_buffer_size(const char *arg)
1448 video_rc_buffer_size = atoi(arg) * 1000;
1451 void opt_video_rc_eq(char *arg)
1456 void opt_video_rc_override_string(char *arg)
1458 video_rc_override_string = arg;
1462 void opt_workaround_bugs(const char *arg)
1464 workaround_bugs = atoi(arg);
1467 void opt_dct_algo(const char *arg)
1469 dct_algo = atoi(arg);
1472 void opt_idct_algo(const char *arg)
1474 idct_algo = atoi(arg);
1478 void opt_error_resilience(const char *arg)
1480 error_resilience = atoi(arg);
1483 void opt_error_concealment(const char *arg)
1485 error_concealment = atoi(arg);
1489 void opt_frame_rate(const char *arg)
1491 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1495 void opt_frame_crop_top(const char *arg)
1497 frame_topBand = atoi(arg);
1498 if (frame_topBand < 0) {
1499 fprintf(stderr, "Incorrect top crop size\n");
1502 if ((frame_topBand % 2) != 0) {
1503 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1506 if ((frame_topBand) >= frame_height){
1507 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1510 frame_height -= frame_topBand;
1513 void opt_frame_crop_bottom(const char *arg)
1515 frame_bottomBand = atoi(arg);
1516 if (frame_bottomBand < 0) {
1517 fprintf(stderr, "Incorrect bottom crop size\n");
1520 if ((frame_bottomBand % 2) != 0) {
1521 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1524 if ((frame_bottomBand) >= frame_height){
1525 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1528 frame_height -= frame_bottomBand;
1531 void opt_frame_crop_left(const char *arg)
1533 frame_leftBand = atoi(arg);
1534 if (frame_leftBand < 0) {
1535 fprintf(stderr, "Incorrect left crop size\n");
1538 if ((frame_leftBand % 2) != 0) {
1539 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1542 if ((frame_leftBand) >= frame_width){
1543 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1546 frame_width -= frame_leftBand;
1549 void opt_frame_crop_right(const char *arg)
1551 frame_rightBand = atoi(arg);
1552 if (frame_rightBand < 0) {
1553 fprintf(stderr, "Incorrect right crop size\n");
1556 if ((frame_rightBand % 2) != 0) {
1557 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1560 if ((frame_rightBand) >= frame_width){
1561 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1564 frame_width -= frame_rightBand;
1567 void opt_frame_size(const char *arg)
1569 parse_image_size(&frame_width, &frame_height, arg);
1570 if (frame_width <= 0 || frame_height <= 0) {
1571 fprintf(stderr, "Incorrect frame size\n");
1574 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1575 fprintf(stderr, "Frame size must be a multiple of 2\n");
1580 void opt_gop_size(const char *arg)
1582 gop_size = atoi(arg);
1585 void opt_b_frames(const char *arg)
1587 b_frames = atoi(arg);
1588 if (b_frames > FF_MAX_B_FRAMES) {
1589 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1591 } else if (b_frames < 1) {
1592 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1597 void opt_qscale(const char *arg)
1599 video_qscale = atoi(arg);
1600 if (video_qscale < 0 ||
1601 video_qscale > 31) {
1602 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1607 void opt_qmin(const char *arg)
1609 video_qmin = atoi(arg);
1610 if (video_qmin < 0 ||
1612 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1617 void opt_qmax(const char *arg)
1619 video_qmax = atoi(arg);
1620 if (video_qmax < 0 ||
1622 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1627 void opt_qdiff(const char *arg)
1629 video_qdiff = atoi(arg);
1630 if (video_qdiff < 0 ||
1632 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1637 void opt_qblur(const char *arg)
1639 video_qblur = atof(arg);
1642 void opt_qcomp(const char *arg)
1644 video_qcomp = atof(arg);
1647 void opt_rc_initial_cplx(const char *arg)
1649 video_rc_initial_cplx = atof(arg);
1651 void opt_b_qfactor(const char *arg)
1653 video_b_qfactor = atof(arg);
1655 void opt_i_qfactor(const char *arg)
1657 video_i_qfactor = atof(arg);
1659 void opt_b_qoffset(const char *arg)
1661 video_b_qoffset = atof(arg);
1663 void opt_i_qoffset(const char *arg)
1665 video_i_qoffset = atof(arg);
1668 void opt_packet_size(const char *arg)
1670 packet_size= atoi(arg);
1673 void opt_audio_bitrate(const char *arg)
1675 audio_bit_rate = atoi(arg) * 1000;
1678 void opt_audio_rate(const char *arg)
1680 audio_sample_rate = atoi(arg);
1683 void opt_audio_channels(const char *arg)
1685 audio_channels = atoi(arg);
1688 void opt_video_device(const char *arg)
1690 v4l_device = strdup(arg);
1693 void opt_audio_device(const char *arg)
1695 audio_device = strdup(arg);
1698 void opt_audio_codec(const char *arg)
1702 if (!strcmp(arg, "copy")) {
1703 audio_stream_copy = 1;
1707 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1712 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1715 audio_codec_id = p->id;
1720 const char *motion_str[] = {
1730 void opt_motion_estimation(const char *arg)
1736 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1739 if (!strcmp(*p, arg))
1743 me_method = (p - motion_str) + 1;
1746 void opt_video_codec(const char *arg)
1750 if (!strcmp(arg, "copy")) {
1751 video_stream_copy = 1;
1755 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1760 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1763 video_codec_id = p->id;
1768 void opt_map(const char *arg)
1774 m = &stream_maps[nb_stream_maps++];
1776 m->file_index = strtol(arg, (char **)&p, 0);
1780 m->stream_index = strtol(p, (char **)&p, 0);
1783 void opt_recording_time(const char *arg)
1785 recording_time = parse_date(arg, 1);
1788 void print_error(const char *filename, int err)
1791 case AVERROR_NUMEXPECTED:
1792 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1793 "Use '%%d' to specify the image number:\n"
1794 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1795 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1798 case AVERROR_INVALIDDATA:
1799 fprintf(stderr, "%s: Error while parsing header\n", filename);
1802 fprintf(stderr, "%s: Unknown format\n", filename);
1805 fprintf(stderr, "%s: Error while opening file\n", filename);
1810 void opt_input_file(const char *filename)
1812 AVFormatContext *ic;
1813 AVFormatParameters params, *ap = ¶ms;
1814 int err, i, ret, rfps;
1816 /* get default parameters from command line */
1817 memset(ap, 0, sizeof(*ap));
1818 ap->sample_rate = audio_sample_rate;
1819 ap->channels = audio_channels;
1820 ap->frame_rate = frame_rate;
1821 ap->width = frame_width;
1822 ap->height = frame_height;
1824 /* open the input file with generic libav function */
1825 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1827 print_error(filename, err);
1831 /* If not enough info to get the stream parameters, we decode the
1832 first frames to get it. (used in mpeg case for example) */
1833 ret = av_find_stream_info(ic);
1835 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1839 /* update the current parameters so that they match the one of the input stream */
1840 for(i=0;i<ic->nb_streams;i++) {
1841 AVCodecContext *enc = &ic->streams[i]->codec;
1842 switch(enc->codec_type) {
1843 case CODEC_TYPE_AUDIO:
1844 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1845 audio_channels = enc->channels;
1846 audio_sample_rate = enc->sample_rate;
1848 case CODEC_TYPE_VIDEO:
1849 frame_height = enc->height;
1850 frame_width = enc->width;
1851 rfps = ic->streams[i]->r_frame_rate;
1852 enc->workaround_bugs = workaround_bugs;
1853 enc->error_resilience = error_resilience;
1854 enc->error_concealment = error_concealment;
1855 enc->idct_algo= idct_algo;
1856 if (enc->frame_rate != rfps) {
1857 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1858 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1859 (float)rfps / FRAME_RATE_BASE);
1861 /* update the current frame rate to match the stream frame rate */
1869 input_files[nb_input_files] = ic;
1870 /* dump the file content */
1871 dump_format(ic, nb_input_files, filename, 0);
1873 file_iformat = NULL;
1874 file_oformat = NULL;
1877 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1879 int has_video, has_audio, i, j;
1880 AVFormatContext *ic;
1884 for(j=0;j<nb_input_files;j++) {
1885 ic = input_files[j];
1886 for(i=0;i<ic->nb_streams;i++) {
1887 AVCodecContext *enc = &ic->streams[i]->codec;
1888 switch(enc->codec_type) {
1889 case CODEC_TYPE_AUDIO:
1892 case CODEC_TYPE_VIDEO:
1900 *has_video_ptr = has_video;
1901 *has_audio_ptr = has_audio;
1904 void opt_output_file(const char *filename)
1907 AVFormatContext *oc;
1908 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1911 if (!strcmp(filename, "-"))
1914 oc = av_mallocz(sizeof(AVFormatContext));
1916 if (!file_oformat) {
1917 file_oformat = guess_format(NULL, filename, NULL);
1918 if (!file_oformat) {
1919 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1925 oc->oformat = file_oformat;
1927 if (!strcmp(file_oformat->name, "ffm") &&
1928 strstart(filename, "http:", NULL)) {
1929 /* special case for files sent to ffserver: we get the stream
1930 parameters from ffserver */
1931 if (read_ffserver_streams(oc, filename) < 0) {
1932 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1936 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1937 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1939 /* disable if no corresponding type found and at least one
1941 if (nb_input_files > 0) {
1942 check_audio_video_inputs(&input_has_video, &input_has_audio);
1943 if (!input_has_video)
1945 if (!input_has_audio)
1949 /* manual disable */
1950 if (audio_disable) {
1953 if (video_disable) {
1959 AVCodecContext *video_enc;
1961 st = av_mallocz(sizeof(AVStream));
1963 fprintf(stderr, "Could not alloc stream\n");
1967 video_enc = &st->codec;
1968 if (video_stream_copy) {
1969 st->stream_copy = 1;
1970 video_enc->codec_type = CODEC_TYPE_VIDEO;
1975 codec_id = file_oformat->video_codec;
1976 if (video_codec_id != CODEC_ID_NONE)
1977 codec_id = video_codec_id;
1979 video_enc->codec_id = codec_id;
1981 video_enc->bit_rate = video_bit_rate;
1982 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1983 video_enc->frame_rate = frame_rate;
1985 video_enc->width = frame_width;
1986 video_enc->height = frame_height;
1989 video_enc->gop_size = gop_size;
1991 video_enc->gop_size = 0;
1992 if (video_qscale || same_quality) {
1993 video_enc->flags |= CODEC_FLAG_QSCALE;
1994 video_enc->quality = video_qscale;
1998 video_enc->flags |= CODEC_FLAG_HQ;
2002 video_enc->flags |= CODEC_FLAG_HQ;
2003 video_enc->flags |= CODEC_FLAG_4MV;
2007 video_enc->flags |= CODEC_FLAG_PART;
2011 if (codec_id != CODEC_ID_MPEG4) {
2012 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2015 video_enc->max_b_frames = b_frames;
2016 video_enc->b_frame_strategy = 0;
2017 video_enc->b_quant_factor = 2.0;
2020 video_enc->qmin = video_qmin;
2021 video_enc->qmax = video_qmax;
2022 video_enc->max_qdiff = video_qdiff;
2023 video_enc->qblur = video_qblur;
2024 video_enc->qcompress = video_qcomp;
2025 video_enc->rc_eq = video_rc_eq;
2027 p= video_rc_override_string;
2030 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2032 fprintf(stderr, "error parsing rc_override\n");
2035 video_enc->rc_override=
2036 realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2037 video_enc->rc_override[i].start_frame= start;
2038 video_enc->rc_override[i].end_frame = end;
2040 video_enc->rc_override[i].qscale= q;
2041 video_enc->rc_override[i].quality_factor= 1.0;
2044 video_enc->rc_override[i].qscale= 0;
2045 video_enc->rc_override[i].quality_factor= -q/100.0;
2050 video_enc->rc_override_count=i;
2052 video_enc->rc_max_rate = video_rc_max_rate;
2053 video_enc->rc_min_rate = video_rc_min_rate;
2054 video_enc->rc_buffer_size = video_rc_buffer_size;
2055 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2056 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2057 video_enc->i_quant_factor = video_i_qfactor;
2058 video_enc->b_quant_factor = video_b_qfactor;
2059 video_enc->i_quant_offset = video_i_qoffset;
2060 video_enc->b_quant_offset = video_b_qoffset;
2061 video_enc->dct_algo = dct_algo;
2062 video_enc->idct_algo = idct_algo;
2064 video_enc->rtp_mode= 1;
2065 video_enc->rtp_payload_size= packet_size;
2069 video_enc->get_psnr = 1;
2071 video_enc->get_psnr = 0;
2073 video_enc->me_method = me_method;
2078 video_enc->flags |= CODEC_FLAG_PASS1;
2080 video_enc->flags |= CODEC_FLAG_PASS2;
2084 /* XXX: need to find a way to set codec parameters */
2085 if (oc->oformat->flags & AVFMT_RGB24) {
2086 video_enc->pix_fmt = PIX_FMT_RGB24;
2089 oc->streams[nb_streams] = st;
2094 AVCodecContext *audio_enc;
2096 st = av_mallocz(sizeof(AVStream));
2098 fprintf(stderr, "Could not alloc stream\n");
2102 audio_enc = &st->codec;
2103 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2104 if (audio_stream_copy) {
2105 st->stream_copy = 1;
2107 codec_id = file_oformat->audio_codec;
2108 if (audio_codec_id != CODEC_ID_NONE)
2109 codec_id = audio_codec_id;
2110 audio_enc->codec_id = codec_id;
2112 audio_enc->bit_rate = audio_bit_rate;
2113 audio_enc->sample_rate = audio_sample_rate;
2114 /* For audio codecs other than AC3 we limit */
2115 /* the number of coded channels to stereo */
2116 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2117 audio_enc->channels = 2;
2119 audio_enc->channels = audio_channels;
2121 oc->streams[nb_streams] = st;
2125 oc->nb_streams = nb_streams;
2128 fprintf(stderr, "No audio or video streams available\n");
2133 pstrcpy(oc->title, sizeof(oc->title), str_title);
2135 pstrcpy(oc->author, sizeof(oc->author), str_author);
2137 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2139 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2142 output_files[nb_output_files++] = oc;
2144 strcpy(oc->filename, filename);
2146 /* check filename in case of an image number is expected */
2147 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2148 if (filename_number_test(oc->filename) < 0) {
2149 print_error(oc->filename, AVERROR_NUMEXPECTED);
2154 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2155 /* test if it already exists to avoid loosing precious files */
2156 if (!file_overwrite &&
2157 (strchr(filename, ':') == NULL ||
2158 strstart(filename, "file:", NULL))) {
2159 if (url_exist(filename)) {
2162 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2165 if (toupper(c) != 'Y') {
2166 fprintf(stderr, "Not overwriting - exiting\n");
2173 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2174 fprintf(stderr, "Could not open '%s'\n", filename);
2179 /* reset some options */
2180 file_oformat = NULL;
2181 file_iformat = NULL;
2184 audio_codec_id = CODEC_ID_NONE;
2185 video_codec_id = CODEC_ID_NONE;
2186 audio_stream_copy = 0;
2187 video_stream_copy = 0;
2190 /* prepare dummy protocols for grab */
2191 void prepare_grab(void)
2193 int has_video, has_audio, i, j;
2194 AVFormatContext *oc;
2195 AVFormatContext *ic;
2196 AVFormatParameters ap1, *ap = &ap1;
2198 /* see if audio/video inputs are needed */
2201 memset(ap, 0, sizeof(*ap));
2202 for(j=0;j<nb_output_files;j++) {
2203 oc = output_files[j];
2204 for(i=0;i<oc->nb_streams;i++) {
2205 AVCodecContext *enc = &oc->streams[i]->codec;
2206 switch(enc->codec_type) {
2207 case CODEC_TYPE_AUDIO:
2208 if (enc->sample_rate > ap->sample_rate)
2209 ap->sample_rate = enc->sample_rate;
2210 if (enc->channels > ap->channels)
2211 ap->channels = enc->channels;
2214 case CODEC_TYPE_VIDEO:
2215 if (enc->width > ap->width)
2216 ap->width = enc->width;
2217 if (enc->height > ap->height)
2218 ap->height = enc->height;
2219 if (enc->frame_rate > ap->frame_rate)
2220 ap->frame_rate = enc->frame_rate;
2229 if (has_video == 0 && has_audio == 0) {
2230 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2235 AVInputFormat *fmt1;
2236 fmt1 = av_find_input_format("video_grab_device");
2237 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2238 fprintf(stderr, "Could not find video grab device\n");
2241 /* by now video grab has one stream */
2242 ic->streams[0]->r_frame_rate = ap->frame_rate;
2243 input_files[nb_input_files] = ic;
2244 dump_format(ic, nb_input_files, v4l_device, 0);
2248 AVInputFormat *fmt1;
2249 fmt1 = av_find_input_format("audio_device");
2250 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2251 fprintf(stderr, "Could not find audio grab device\n");
2254 input_files[nb_input_files] = ic;
2255 dump_format(ic, nb_input_files, audio_device, 0);
2260 /* open the necessary output devices for playing */
2261 void prepare_play(void)
2263 file_iformat = NULL;
2264 file_oformat = guess_format("audio_device", NULL, NULL);
2265 if (!file_oformat) {
2266 fprintf(stderr, "Could not find audio device\n");
2270 opt_output_file(audio_device);
2273 /* same option as mencoder */
2274 void opt_pass(const char *pass_str)
2277 pass = atoi(pass_str);
2278 if (pass != 1 && pass != 2) {
2279 fprintf(stderr, "pass number can be only 1 or 2\n");
2285 #ifndef CONFIG_WIN32
2286 INT64 getutime(void)
2288 struct rusage rusage;
2290 getrusage(RUSAGE_SELF, &rusage);
2291 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2294 INT64 getutime(void)
2296 return av_gettime();
2300 extern int ffm_nopts;
2302 void opt_bitexact(void)
2304 avcodec_set_bit_exact();
2305 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2309 void show_formats(void)
2311 AVInputFormat *ifmt;
2312 AVOutputFormat *ofmt;
2317 printf("File formats:\n");
2318 printf(" Encoding:");
2319 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2320 printf(" %s", ofmt->name);
2323 printf(" Decoding:");
2324 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2325 printf(" %s", ifmt->name);
2329 printf("Codecs:\n");
2330 printf(" Encoders:");
2331 for(p = first_avcodec; p != NULL; p = p->next) {
2333 printf(" %s", p->name);
2337 printf(" Decoders:");
2338 for(p = first_avcodec; p != NULL; p = p->next) {
2340 printf(" %s", p->name);
2344 printf("Supported file protocols:");
2345 for(up = first_protocol; up != NULL; up = up->next)
2346 printf(" %s:", up->name);
2349 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2350 printf("Motion estimation methods:");
2354 if ((pp - motion_str + 1) == ME_ZERO)
2355 printf("(fastest)");
2356 else if ((pp - motion_str + 1) == ME_FULL)
2357 printf("(slowest)");
2358 else if ((pp - motion_str + 1) == ME_EPZS)
2359 printf("(default)");
2366 void show_help(void)
2369 const OptionDef *po;
2372 prog = do_play ? "ffplay" : "ffmpeg";
2374 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2378 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2379 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2381 printf("usage: ffplay [options] input_file...\n"
2382 "Simple audio player\n");
2386 "Main options are:\n");
2389 printf("\nAdvanced options are:\n");
2390 for(po = options; po->name != NULL; po++) {
2392 expert = (po->flags & OPT_EXPERT) != 0;
2394 strcpy(buf, po->name);
2395 if (po->flags & HAS_ARG) {
2397 strcat(buf, po->argname);
2399 printf("-%-17s %s\n", buf, po->help);
2407 const OptionDef options[] = {
2408 { "L", 0, {(void*)show_licence}, "show license" },
2409 { "h", 0, {(void*)show_help}, "show help" },
2410 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2411 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2412 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2413 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2414 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2415 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2416 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2417 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2418 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2419 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2420 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2421 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2423 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2424 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2425 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2426 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2427 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2428 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2429 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2430 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2431 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2432 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2433 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2434 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2435 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2436 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2437 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2438 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2439 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2440 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2441 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2442 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2443 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2444 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2445 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2446 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2447 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2448 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2449 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2450 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2451 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2452 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2454 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2455 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2456 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2457 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
2458 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2459 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2460 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2461 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2462 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2463 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2464 { "sameq", OPT_BOOL, {(void*)&same_quality},
2465 "use same video quality as source (implies VBR)" },
2467 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2468 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2469 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2470 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2471 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2472 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2473 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2474 "deinterlace pictures" },
2475 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2476 "add timings for benchmarking" },
2477 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2478 "dump each input packet" },
2479 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2480 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2481 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2485 int main(int argc, char **argv)
2488 const char *opt, *arg;
2489 const OptionDef *po;
2494 /* detect if invoked as player */
2495 i = strlen(argv[0]);
2496 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2504 while (optindex < argc) {
2505 opt = argv[optindex++];
2507 if (opt[0] == '-' && opt[1] != '\0') {
2509 while (po->name != NULL) {
2510 if (!strcmp(opt + 1, po->name))
2515 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2519 if (po->flags & HAS_ARG)
2520 arg = argv[optindex++];
2521 if (po->flags & OPT_STRING) {
2524 *po->u.str_arg = str;
2525 } else if (po->flags & OPT_BOOL) {
2528 po->u.func_arg(arg);
2532 opt_output_file(opt);
2534 opt_input_file(opt);
2541 /* file converter / grab */
2542 if (nb_output_files <= 0) {
2543 fprintf(stderr, "Must supply at least one output file\n");
2547 if (nb_input_files == 0) {
2552 if (nb_input_files <= 0) {
2553 fprintf(stderr, "Must supply at least one input file\n");
2560 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2561 stream_maps, nb_stream_maps);
2562 ti = getutime() - ti;
2564 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2568 for(i=0;i<nb_output_files;i++) {
2569 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
2570 url_fclose(&output_files[i]->pb);
2572 for(i=0;i<nb_input_files;i++)
2573 av_close_input_file(input_files[i]);