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;
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);
1296 ipts = AV_NOPTS_VALUE;
1299 av_free_packet(&pkt);
1301 /* dump report by using the output first video and audio streams */
1302 print_report(output_files, ost_table, nb_ostreams, 0);
1306 /* dump report by using the first video and audio streams */
1307 print_report(output_files, ost_table, nb_ostreams, 1);
1309 /* close each encoder */
1310 for(i=0;i<nb_ostreams;i++) {
1312 if (ost->encoding_needed) {
1313 av_freep(&ost->st->codec.stats_in);
1314 avcodec_close(&ost->st->codec);
1318 /* close each decoder */
1319 for(i=0;i<nb_istreams;i++) {
1321 if (ist->decoding_needed) {
1322 avcodec_close(&ist->st->codec);
1327 /* write the trailer if needed and close file */
1328 for(i=0;i<nb_output_files;i++) {
1329 os = output_files[i];
1330 av_write_trailer(os);
1336 av_free(file_table);
1339 for(i=0;i<nb_istreams;i++) {
1346 for(i=0;i<nb_ostreams;i++) {
1350 fclose(ost->logfile);
1351 ost->logfile = NULL;
1353 fifo_free(&ost->fifo); /* works even if fifo is not
1354 initialized but set to zero */
1355 av_free(ost->pict_tmp.data[0]);
1356 if (ost->video_resample)
1357 img_resample_close(ost->img_resample_ctx);
1358 if (ost->audio_resample)
1359 audio_resample_close(ost->resample);
1372 int file_read(const char *filename)
1375 unsigned char buffer[1024];
1378 if (url_open(&h, filename, O_RDONLY) < 0) {
1379 printf("could not open '%s'\n", filename);
1383 len = url_read(h, buffer, sizeof(buffer));
1386 for(i=0;i<len;i++) putchar(buffer[i]);
1393 void show_licence(void)
1396 "ffmpeg version " FFMPEG_VERSION "\n"
1397 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1398 "This library is free software; you can redistribute it and/or\n"
1399 "modify it under the terms of the GNU Lesser General Public\n"
1400 "License as published by the Free Software Foundation; either\n"
1401 "version 2 of the License, or (at your option) any later version.\n"
1403 "This library is distributed in the hope that it will be useful,\n"
1404 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1405 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1406 "Lesser General Public License for more details.\n"
1408 "You should have received a copy of the GNU Lesser General Public\n"
1409 "License along with this library; if not, write to the Free Software\n"
1410 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1415 void opt_format(const char *arg)
1417 file_iformat = av_find_input_format(arg);
1418 file_oformat = guess_format(arg, NULL, NULL);
1419 if (!file_iformat && !file_oformat) {
1420 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1425 void opt_video_bitrate(const char *arg)
1427 video_bit_rate = atoi(arg) * 1000;
1430 void opt_video_bitrate_tolerance(const char *arg)
1432 video_bit_rate_tolerance = atoi(arg) * 1000;
1435 void opt_video_bitrate_max(const char *arg)
1437 video_rc_max_rate = atoi(arg) * 1000;
1440 void opt_video_bitrate_min(const char *arg)
1442 video_rc_min_rate = atoi(arg) * 1000;
1445 void opt_video_buffer_size(const char *arg)
1447 video_rc_buffer_size = atoi(arg) * 1000;
1450 void opt_video_rc_eq(char *arg)
1455 void opt_video_rc_override_string(char *arg)
1457 video_rc_override_string = arg;
1461 void opt_workaround_bugs(const char *arg)
1463 workaround_bugs = atoi(arg);
1466 void opt_dct_algo(const char *arg)
1468 dct_algo = atoi(arg);
1471 void opt_idct_algo(const char *arg)
1473 idct_algo = atoi(arg);
1477 void opt_error_resilience(const char *arg)
1479 error_resilience = atoi(arg);
1482 void opt_error_concealment(const char *arg)
1484 error_concealment = atoi(arg);
1488 void opt_frame_rate(const char *arg)
1490 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1494 void opt_frame_crop_top(const char *arg)
1496 frame_topBand = atoi(arg);
1497 if (frame_topBand < 0) {
1498 fprintf(stderr, "Incorrect top crop size\n");
1501 if ((frame_topBand % 2) != 0) {
1502 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1505 if ((frame_topBand) >= frame_height){
1506 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1509 frame_height -= frame_topBand;
1512 void opt_frame_crop_bottom(const char *arg)
1514 frame_bottomBand = atoi(arg);
1515 if (frame_bottomBand < 0) {
1516 fprintf(stderr, "Incorrect bottom crop size\n");
1519 if ((frame_bottomBand % 2) != 0) {
1520 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1523 if ((frame_bottomBand) >= frame_height){
1524 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1527 frame_height -= frame_bottomBand;
1530 void opt_frame_crop_left(const char *arg)
1532 frame_leftBand = atoi(arg);
1533 if (frame_leftBand < 0) {
1534 fprintf(stderr, "Incorrect left crop size\n");
1537 if ((frame_leftBand % 2) != 0) {
1538 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1541 if ((frame_leftBand) >= frame_width){
1542 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1545 frame_width -= frame_leftBand;
1548 void opt_frame_crop_right(const char *arg)
1550 frame_rightBand = atoi(arg);
1551 if (frame_rightBand < 0) {
1552 fprintf(stderr, "Incorrect right crop size\n");
1555 if ((frame_rightBand % 2) != 0) {
1556 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1559 if ((frame_rightBand) >= frame_width){
1560 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1563 frame_width -= frame_rightBand;
1566 void opt_frame_size(const char *arg)
1568 parse_image_size(&frame_width, &frame_height, arg);
1569 if (frame_width <= 0 || frame_height <= 0) {
1570 fprintf(stderr, "Incorrect frame size\n");
1573 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1574 fprintf(stderr, "Frame size must be a multiple of 2\n");
1579 void opt_gop_size(const char *arg)
1581 gop_size = atoi(arg);
1584 void opt_b_frames(const char *arg)
1586 b_frames = atoi(arg);
1587 if (b_frames > FF_MAX_B_FRAMES) {
1588 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1590 } else if (b_frames < 1) {
1591 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1596 void opt_qscale(const char *arg)
1598 video_qscale = atoi(arg);
1599 if (video_qscale < 0 ||
1600 video_qscale > 31) {
1601 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1606 void opt_qmin(const char *arg)
1608 video_qmin = atoi(arg);
1609 if (video_qmin < 0 ||
1611 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1616 void opt_qmax(const char *arg)
1618 video_qmax = atoi(arg);
1619 if (video_qmax < 0 ||
1621 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1626 void opt_qdiff(const char *arg)
1628 video_qdiff = atoi(arg);
1629 if (video_qdiff < 0 ||
1631 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1636 void opt_qblur(const char *arg)
1638 video_qblur = atof(arg);
1641 void opt_qcomp(const char *arg)
1643 video_qcomp = atof(arg);
1646 void opt_rc_initial_cplx(const char *arg)
1648 video_rc_initial_cplx = atof(arg);
1650 void opt_b_qfactor(const char *arg)
1652 video_b_qfactor = atof(arg);
1654 void opt_i_qfactor(const char *arg)
1656 video_i_qfactor = atof(arg);
1658 void opt_b_qoffset(const char *arg)
1660 video_b_qoffset = atof(arg);
1662 void opt_i_qoffset(const char *arg)
1664 video_i_qoffset = atof(arg);
1667 void opt_packet_size(const char *arg)
1669 packet_size= atoi(arg);
1672 void opt_audio_bitrate(const char *arg)
1674 audio_bit_rate = atoi(arg) * 1000;
1677 void opt_audio_rate(const char *arg)
1679 audio_sample_rate = atoi(arg);
1682 void opt_audio_channels(const char *arg)
1684 audio_channels = atoi(arg);
1687 void opt_video_device(const char *arg)
1689 v4l_device = strdup(arg);
1692 void opt_audio_device(const char *arg)
1694 audio_device = strdup(arg);
1697 void opt_audio_codec(const char *arg)
1701 if (!strcmp(arg, "copy")) {
1702 audio_stream_copy = 1;
1706 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1711 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1714 audio_codec_id = p->id;
1719 const char *motion_str[] = {
1729 void opt_motion_estimation(const char *arg)
1735 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1738 if (!strcmp(*p, arg))
1742 me_method = (p - motion_str) + 1;
1745 void opt_video_codec(const char *arg)
1749 if (!strcmp(arg, "copy")) {
1750 video_stream_copy = 1;
1754 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1759 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1762 video_codec_id = p->id;
1767 void opt_map(const char *arg)
1773 m = &stream_maps[nb_stream_maps++];
1775 m->file_index = strtol(arg, (char **)&p, 0);
1779 m->stream_index = strtol(p, (char **)&p, 0);
1782 void opt_recording_time(const char *arg)
1784 recording_time = parse_date(arg, 1);
1787 void print_error(const char *filename, int err)
1790 case AVERROR_NUMEXPECTED:
1791 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1792 "Use '%%d' to specify the image number:\n"
1793 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1794 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1797 case AVERROR_INVALIDDATA:
1798 fprintf(stderr, "%s: Error while parsing header\n", filename);
1801 fprintf(stderr, "%s: Unknown format\n", filename);
1804 fprintf(stderr, "%s: Error while opening file\n", filename);
1809 void opt_input_file(const char *filename)
1811 AVFormatContext *ic;
1812 AVFormatParameters params, *ap = ¶ms;
1813 int err, i, ret, rfps;
1815 /* get default parameters from command line */
1816 memset(ap, 0, sizeof(*ap));
1817 ap->sample_rate = audio_sample_rate;
1818 ap->channels = audio_channels;
1819 ap->frame_rate = frame_rate;
1820 ap->width = frame_width;
1821 ap->height = frame_height;
1823 /* open the input file with generic libav function */
1824 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1826 print_error(filename, err);
1830 /* If not enough info to get the stream parameters, we decode the
1831 first frames to get it. (used in mpeg case for example) */
1832 ret = av_find_stream_info(ic);
1834 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1838 /* update the current parameters so that they match the one of the input stream */
1839 for(i=0;i<ic->nb_streams;i++) {
1840 AVCodecContext *enc = &ic->streams[i]->codec;
1841 switch(enc->codec_type) {
1842 case CODEC_TYPE_AUDIO:
1843 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1844 audio_channels = enc->channels;
1845 audio_sample_rate = enc->sample_rate;
1847 case CODEC_TYPE_VIDEO:
1848 frame_height = enc->height;
1849 frame_width = enc->width;
1850 rfps = ic->streams[i]->r_frame_rate;
1851 enc->workaround_bugs = workaround_bugs;
1852 enc->error_resilience = error_resilience;
1853 enc->error_concealment = error_concealment;
1854 enc->idct_algo= idct_algo;
1855 if (enc->frame_rate != rfps) {
1856 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1857 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1858 (float)rfps / FRAME_RATE_BASE);
1860 /* update the current frame rate to match the stream frame rate */
1868 input_files[nb_input_files] = ic;
1869 /* dump the file content */
1870 dump_format(ic, nb_input_files, filename, 0);
1872 file_iformat = NULL;
1873 file_oformat = NULL;
1876 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1878 int has_video, has_audio, i, j;
1879 AVFormatContext *ic;
1883 for(j=0;j<nb_input_files;j++) {
1884 ic = input_files[j];
1885 for(i=0;i<ic->nb_streams;i++) {
1886 AVCodecContext *enc = &ic->streams[i]->codec;
1887 switch(enc->codec_type) {
1888 case CODEC_TYPE_AUDIO:
1891 case CODEC_TYPE_VIDEO:
1899 *has_video_ptr = has_video;
1900 *has_audio_ptr = has_audio;
1903 void opt_output_file(const char *filename)
1906 AVFormatContext *oc;
1907 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1910 if (!strcmp(filename, "-"))
1913 oc = av_mallocz(sizeof(AVFormatContext));
1915 if (!file_oformat) {
1916 file_oformat = guess_format(NULL, filename, NULL);
1917 if (!file_oformat) {
1918 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1924 oc->oformat = file_oformat;
1926 if (!strcmp(file_oformat->name, "ffm") &&
1927 strstart(filename, "http:", NULL)) {
1928 /* special case for files sent to ffserver: we get the stream
1929 parameters from ffserver */
1930 if (read_ffserver_streams(oc, filename) < 0) {
1931 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1935 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1936 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1938 /* disable if no corresponding type found and at least one
1940 if (nb_input_files > 0) {
1941 check_audio_video_inputs(&input_has_video, &input_has_audio);
1942 if (!input_has_video)
1944 if (!input_has_audio)
1948 /* manual disable */
1949 if (audio_disable) {
1952 if (video_disable) {
1958 AVCodecContext *video_enc;
1960 st = av_mallocz(sizeof(AVStream));
1962 fprintf(stderr, "Could not alloc stream\n");
1966 video_enc = &st->codec;
1967 if (video_stream_copy) {
1968 st->stream_copy = 1;
1969 video_enc->codec_type = CODEC_TYPE_VIDEO;
1974 codec_id = file_oformat->video_codec;
1975 if (video_codec_id != CODEC_ID_NONE)
1976 codec_id = video_codec_id;
1978 video_enc->codec_id = codec_id;
1980 video_enc->bit_rate = video_bit_rate;
1981 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1982 video_enc->frame_rate = frame_rate;
1984 video_enc->width = frame_width;
1985 video_enc->height = frame_height;
1988 video_enc->gop_size = gop_size;
1990 video_enc->gop_size = 0;
1991 if (video_qscale || same_quality) {
1992 video_enc->flags |= CODEC_FLAG_QSCALE;
1993 video_enc->quality = video_qscale;
1997 video_enc->flags |= CODEC_FLAG_HQ;
2001 video_enc->flags |= CODEC_FLAG_HQ;
2002 video_enc->flags |= CODEC_FLAG_4MV;
2006 video_enc->flags |= CODEC_FLAG_PART;
2010 if (codec_id != CODEC_ID_MPEG4) {
2011 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2014 video_enc->max_b_frames = b_frames;
2015 video_enc->b_frame_strategy = 0;
2016 video_enc->b_quant_factor = 2.0;
2019 video_enc->qmin = video_qmin;
2020 video_enc->qmax = video_qmax;
2021 video_enc->max_qdiff = video_qdiff;
2022 video_enc->qblur = video_qblur;
2023 video_enc->qcompress = video_qcomp;
2024 video_enc->rc_eq = video_rc_eq;
2026 p= video_rc_override_string;
2029 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2031 fprintf(stderr, "error parsing rc_override\n");
2034 video_enc->rc_override=
2035 realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2036 video_enc->rc_override[i].start_frame= start;
2037 video_enc->rc_override[i].end_frame = end;
2039 video_enc->rc_override[i].qscale= q;
2040 video_enc->rc_override[i].quality_factor= 1.0;
2043 video_enc->rc_override[i].qscale= 0;
2044 video_enc->rc_override[i].quality_factor= -q/100.0;
2049 video_enc->rc_override_count=i;
2051 video_enc->rc_max_rate = video_rc_max_rate;
2052 video_enc->rc_min_rate = video_rc_min_rate;
2053 video_enc->rc_buffer_size = video_rc_buffer_size;
2054 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2055 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2056 video_enc->i_quant_factor = video_i_qfactor;
2057 video_enc->b_quant_factor = video_b_qfactor;
2058 video_enc->i_quant_offset = video_i_qoffset;
2059 video_enc->b_quant_offset = video_b_qoffset;
2060 video_enc->dct_algo = dct_algo;
2061 video_enc->idct_algo = idct_algo;
2063 video_enc->rtp_mode= 1;
2064 video_enc->rtp_payload_size= packet_size;
2068 video_enc->get_psnr = 1;
2070 video_enc->get_psnr = 0;
2072 video_enc->me_method = me_method;
2077 video_enc->flags |= CODEC_FLAG_PASS1;
2079 video_enc->flags |= CODEC_FLAG_PASS2;
2083 /* XXX: need to find a way to set codec parameters */
2084 if (oc->oformat->flags & AVFMT_RGB24) {
2085 video_enc->pix_fmt = PIX_FMT_RGB24;
2088 oc->streams[nb_streams] = st;
2093 AVCodecContext *audio_enc;
2095 st = av_mallocz(sizeof(AVStream));
2097 fprintf(stderr, "Could not alloc stream\n");
2101 audio_enc = &st->codec;
2102 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2103 if (audio_stream_copy) {
2104 st->stream_copy = 1;
2106 codec_id = file_oformat->audio_codec;
2107 if (audio_codec_id != CODEC_ID_NONE)
2108 codec_id = audio_codec_id;
2109 audio_enc->codec_id = codec_id;
2111 audio_enc->bit_rate = audio_bit_rate;
2112 audio_enc->sample_rate = audio_sample_rate;
2113 /* For audio codecs other than AC3 we limit */
2114 /* the number of coded channels to stereo */
2115 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2116 audio_enc->channels = 2;
2118 audio_enc->channels = audio_channels;
2120 oc->streams[nb_streams] = st;
2124 oc->nb_streams = nb_streams;
2127 fprintf(stderr, "No audio or video streams available\n");
2132 pstrcpy(oc->title, sizeof(oc->title), str_title);
2134 pstrcpy(oc->author, sizeof(oc->author), str_author);
2136 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2138 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2141 output_files[nb_output_files++] = oc;
2143 strcpy(oc->filename, filename);
2145 /* check filename in case of an image number is expected */
2146 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2147 if (filename_number_test(oc->filename) < 0) {
2148 print_error(oc->filename, AVERROR_NUMEXPECTED);
2153 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2154 /* test if it already exists to avoid loosing precious files */
2155 if (!file_overwrite &&
2156 (strchr(filename, ':') == NULL ||
2157 strstart(filename, "file:", NULL))) {
2158 if (url_exist(filename)) {
2161 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2164 if (toupper(c) != 'Y') {
2165 fprintf(stderr, "Not overwriting - exiting\n");
2172 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2173 fprintf(stderr, "Could not open '%s'\n", filename);
2178 /* reset some options */
2179 file_oformat = NULL;
2180 file_iformat = NULL;
2183 audio_codec_id = CODEC_ID_NONE;
2184 video_codec_id = CODEC_ID_NONE;
2185 audio_stream_copy = 0;
2186 video_stream_copy = 0;
2189 /* prepare dummy protocols for grab */
2190 void prepare_grab(void)
2192 int has_video, has_audio, i, j;
2193 AVFormatContext *oc;
2194 AVFormatContext *ic;
2195 AVFormatParameters ap1, *ap = &ap1;
2197 /* see if audio/video inputs are needed */
2200 memset(ap, 0, sizeof(*ap));
2201 for(j=0;j<nb_output_files;j++) {
2202 oc = output_files[j];
2203 for(i=0;i<oc->nb_streams;i++) {
2204 AVCodecContext *enc = &oc->streams[i]->codec;
2205 switch(enc->codec_type) {
2206 case CODEC_TYPE_AUDIO:
2207 if (enc->sample_rate > ap->sample_rate)
2208 ap->sample_rate = enc->sample_rate;
2209 if (enc->channels > ap->channels)
2210 ap->channels = enc->channels;
2213 case CODEC_TYPE_VIDEO:
2214 if (enc->width > ap->width)
2215 ap->width = enc->width;
2216 if (enc->height > ap->height)
2217 ap->height = enc->height;
2218 if (enc->frame_rate > ap->frame_rate)
2219 ap->frame_rate = enc->frame_rate;
2228 if (has_video == 0 && has_audio == 0) {
2229 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2234 AVInputFormat *fmt1;
2235 fmt1 = av_find_input_format("video_grab_device");
2236 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2237 fprintf(stderr, "Could not find video grab device\n");
2240 /* by now video grab has one stream */
2241 ic->streams[0]->r_frame_rate = ap->frame_rate;
2242 input_files[nb_input_files] = ic;
2243 dump_format(ic, nb_input_files, v4l_device, 0);
2247 AVInputFormat *fmt1;
2248 fmt1 = av_find_input_format("audio_device");
2249 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2250 fprintf(stderr, "Could not find audio grab device\n");
2253 input_files[nb_input_files] = ic;
2254 dump_format(ic, nb_input_files, audio_device, 0);
2259 /* open the necessary output devices for playing */
2260 void prepare_play(void)
2262 file_iformat = NULL;
2263 file_oformat = guess_format("audio_device", NULL, NULL);
2264 if (!file_oformat) {
2265 fprintf(stderr, "Could not find audio device\n");
2269 opt_output_file(audio_device);
2272 /* same option as mencoder */
2273 void opt_pass(const char *pass_str)
2276 pass = atoi(pass_str);
2277 if (pass != 1 && pass != 2) {
2278 fprintf(stderr, "pass number can be only 1 or 2\n");
2284 #ifndef CONFIG_WIN32
2285 INT64 getutime(void)
2287 struct rusage rusage;
2289 getrusage(RUSAGE_SELF, &rusage);
2290 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2293 INT64 getutime(void)
2295 return av_gettime();
2299 extern int ffm_nopts;
2301 void opt_bitexact(void)
2303 avcodec_set_bit_exact();
2304 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2308 void show_formats(void)
2310 AVInputFormat *ifmt;
2311 AVOutputFormat *ofmt;
2316 printf("File formats:\n");
2317 printf(" Encoding:");
2318 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2319 printf(" %s", ofmt->name);
2322 printf(" Decoding:");
2323 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2324 printf(" %s", ifmt->name);
2328 printf("Codecs:\n");
2329 printf(" Encoders:");
2330 for(p = first_avcodec; p != NULL; p = p->next) {
2332 printf(" %s", p->name);
2336 printf(" Decoders:");
2337 for(p = first_avcodec; p != NULL; p = p->next) {
2339 printf(" %s", p->name);
2343 printf("Supported file protocols:");
2344 for(up = first_protocol; up != NULL; up = up->next)
2345 printf(" %s:", up->name);
2348 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2349 printf("Motion estimation methods:");
2353 if ((pp - motion_str + 1) == ME_ZERO)
2354 printf("(fastest)");
2355 else if ((pp - motion_str + 1) == ME_FULL)
2356 printf("(slowest)");
2357 else if ((pp - motion_str + 1) == ME_EPZS)
2358 printf("(default)");
2365 void show_help(void)
2368 const OptionDef *po;
2371 prog = do_play ? "ffplay" : "ffmpeg";
2373 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2377 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2378 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2380 printf("usage: ffplay [options] input_file...\n"
2381 "Simple audio player\n");
2385 "Main options are:\n");
2388 printf("\nAdvanced options are:\n");
2389 for(po = options; po->name != NULL; po++) {
2391 expert = (po->flags & OPT_EXPERT) != 0;
2393 strcpy(buf, po->name);
2394 if (po->flags & HAS_ARG) {
2396 strcat(buf, po->argname);
2398 printf("-%-17s %s\n", buf, po->help);
2406 const OptionDef options[] = {
2407 { "L", 0, {(void*)show_licence}, "show license" },
2408 { "h", 0, {(void*)show_help}, "show help" },
2409 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2410 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2411 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2412 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2413 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2414 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2415 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2416 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2417 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2418 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2419 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2420 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2422 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2423 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2424 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2425 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2426 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2427 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2428 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2429 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2430 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2431 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2432 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2433 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2434 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2435 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2436 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2437 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2438 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2439 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2440 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2441 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2442 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2443 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2444 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2445 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2446 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2447 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2448 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2449 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2450 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2451 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2453 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2454 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2455 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2456 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
2457 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2458 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2459 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2460 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2461 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2462 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2463 { "sameq", OPT_BOOL, {(void*)&same_quality},
2464 "use same video quality as source (implies VBR)" },
2466 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2467 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2468 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2469 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2470 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2471 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2472 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2473 "deinterlace pictures" },
2474 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2475 "add timings for benchmarking" },
2476 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2477 "dump each input packet" },
2478 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2479 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2480 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2484 int main(int argc, char **argv)
2487 const char *opt, *arg;
2488 const OptionDef *po;
2493 /* detect if invoked as player */
2494 i = strlen(argv[0]);
2495 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2503 while (optindex < argc) {
2504 opt = argv[optindex++];
2506 if (opt[0] == '-' && opt[1] != '\0') {
2508 while (po->name != NULL) {
2509 if (!strcmp(opt + 1, po->name))
2514 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2518 if (po->flags & HAS_ARG)
2519 arg = argv[optindex++];
2520 if (po->flags & OPT_STRING) {
2523 *po->u.str_arg = str;
2524 } else if (po->flags & OPT_BOOL) {
2527 po->u.func_arg(arg);
2531 opt_output_file(opt);
2533 opt_input_file(opt);
2540 /* file converter / grab */
2541 if (nb_output_files <= 0) {
2542 fprintf(stderr, "Must supply at least one output file\n");
2546 if (nb_input_files == 0) {
2551 if (nb_input_files <= 0) {
2552 fprintf(stderr, "Must supply at least one input file\n");
2559 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2560 stream_maps, nb_stream_maps);
2561 ti = getutime() - ti;
2563 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2567 for(i=0;i<nb_output_files;i++) {
2568 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
2569 url_fclose(&output_files[i]->pb);
2571 for(i=0;i<nb_input_files;i++)
2572 av_close_input_file(input_files[i]);