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>
34 #define MAXINT64 INT64_C(0x7fffffffffffffff)
39 #define HAS_ARG 0x0001
40 #define OPT_BOOL 0x0002
41 #define OPT_EXPERT 0x0004
42 #define OPT_STRING 0x0008
52 /* select an input stream for an output stream */
53 typedef struct AVStreamMap {
58 extern const OptionDef options[];
64 static AVFormatContext *input_files[MAX_FILES];
65 static int nb_input_files = 0;
67 static AVFormatContext *output_files[MAX_FILES];
68 static int nb_output_files = 0;
70 static AVStreamMap stream_maps[MAX_FILES];
71 static int nb_stream_maps;
73 static AVInputFormat *file_iformat;
74 static AVOutputFormat *file_oformat;
75 static int frame_width = 160;
76 static int frame_height = 128;
77 static int frame_topBand = 0;
78 static int frame_bottomBand = 0;
79 static int frame_leftBand = 0;
80 static int frame_rightBand = 0;
81 static int frame_rate = 25 * FRAME_RATE_BASE;
82 static int video_bit_rate = 200*1000;
83 static int video_bit_rate_tolerance = 4000*1000;
84 static int video_qscale = 0;
85 static int video_qmin = 2;
86 static int video_qmax = 31;
87 static int video_qdiff = 3;
88 static float video_qblur = 0.5;
89 static float video_qcomp = 0.5;
90 #if 0 //experimental, (can be removed)
91 static float video_rc_qsquish=1.0;
92 static float video_rc_qmod_amp=0;
93 static int video_rc_qmod_freq=0;
95 static char *video_rc_override_string=NULL;
96 static char *video_rc_eq="tex^qComp";
97 static int video_rc_buffer_size=0;
98 static float video_rc_buffer_aggressivity=1.0;
99 static int video_rc_max_rate=0;
100 static int video_rc_min_rate=0;
101 static float video_rc_initial_cplx=0;
102 static float video_b_qfactor = 1.25;
103 static float video_b_qoffset = 1.25;
104 static float video_i_qfactor = -0.8;
105 static float video_i_qoffset = 0.0;
106 static int me_method = 0;
107 static int video_disable = 0;
108 static int video_codec_id = CODEC_ID_NONE;
109 static int same_quality = 0;
110 static int b_frames = 0;
111 static int use_hq = 0;
112 static int use_4mv = 0;
113 static int do_deinterlace = 0;
114 static int workaround_bugs = FF_BUG_AUTODETECT;
115 static int error_resilience = 2;
116 static int error_concealment = 3;
117 static int dct_algo = 0;
118 static int idct_algo = 0;
119 static int use_part = 0;
120 static int packet_size = 0;
122 static int gop_size = 12;
123 static int intra_only = 0;
124 static int audio_sample_rate = 44100;
125 static int audio_bit_rate = 64000;
126 static int audio_disable = 0;
127 static int audio_channels = 1;
128 static int audio_codec_id = CODEC_ID_NONE;
130 static INT64 recording_time = 0;
131 static int file_overwrite = 0;
132 static char *str_title = NULL;
133 static char *str_author = NULL;
134 static char *str_copyright = NULL;
135 static char *str_comment = NULL;
136 static int do_benchmark = 0;
137 static int do_hex_dump = 0;
138 static int do_play = 0;
139 static int do_psnr = 0;
140 static int do_vstats = 0;
141 static int do_pass = 0;
142 static char *pass_logfilename = NULL;
143 static int audio_stream_copy = 0;
144 static int video_stream_copy = 0;
146 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
148 #if !defined(CONFIG_AUDIO_OSS) && !defined(CONFIG_AUDIO_BEOS)
149 const char *audio_device = "none";
151 #ifndef CONFIG_VIDEO4LINUX
152 const char *v4l_device = "none";
155 typedef struct AVOutputStream {
156 int file_index; /* file index */
157 int index; /* stream index in the output file */
158 int source_index; /* AVInputStream index */
159 AVStream *st; /* stream in the output file */
160 int encoding_needed; /* true if encoding needed for this stream */
162 /* input pts and corresponding output pts
167 AVPicture pict_tmp; /* temporary image for resizing */
169 ImgReSampleContext *img_resample_ctx; /* for image resampling */
173 ReSampleContext *resample; /* for audio resampling */
174 FifoBuffer fifo; /* for compression: one audio fifo per codec */
178 typedef struct AVInputStream {
182 int discard; /* true if stream data should be discarded */
183 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
184 INT64 sample_index; /* current sample */
185 int frame_decoded; /* true if a video or audio frame has been decoded */
188 typedef struct AVInputFile {
189 int eof_reached; /* true if eof reached */
190 int ist_index; /* index of first stream in ist_table */
191 int buffer_size; /* current total buffer size */
192 int buffer_size_max; /* buffer size at which we consider we can stop
194 int nb_streams; /* nb streams we are aware of */
199 /* init terminal so that we can grab keys */
200 static struct termios oldtty;
202 static void term_exit(void)
204 tcsetattr (0, TCSANOW, &oldtty);
207 static void term_init(void)
214 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
215 |INLCR|IGNCR|ICRNL|IXON);
216 tty.c_oflag |= OPOST;
217 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
218 tty.c_cflag &= ~(CSIZE|PARENB);
223 tcsetattr (0, TCSANOW, &tty);
226 #ifdef CONFIG_BEOS_NETSERVER
227 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
231 /* read a key without blocking */
232 static int read_key(void)
236 #ifndef CONFIG_BEOS_NETSERVER
244 n = select(1, &rfds, NULL, NULL, &tv);
258 /* no interactive support */
259 static void term_exit(void)
263 static void term_init(void)
267 static int read_key(void)
274 int read_ffserver_streams(AVFormatContext *s, const char *filename)
279 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
282 /* copy stream format */
283 s->nb_streams = ic->nb_streams;
284 for(i=0;i<ic->nb_streams;i++) {
286 st = av_mallocz(sizeof(AVFormatContext));
287 memcpy(st, ic->streams[i], sizeof(AVStream));
291 av_close_input_file(ic);
295 #define MAX_AUDIO_PACKET_SIZE 16384
297 static void do_audio_out(AVFormatContext *s,
300 unsigned char *buf, int size)
303 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
304 UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
305 int size_out, frame_bytes, ret;
308 enc = &ost->st->codec;
310 if (ost->audio_resample) {
312 size_out = audio_resample(ost->resample,
313 (short *)buftmp, (short *)buf,
314 size / (ist->st->codec.channels * 2));
315 size_out = size_out * enc->channels * 2;
321 /* now encode as many frames as possible */
322 if (enc->frame_size > 1) {
323 /* output resampled raw samples */
324 fifo_write(&ost->fifo, buftmp, size_out,
327 frame_bytes = enc->frame_size * 2 * enc->channels;
329 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
330 &ost->fifo.rptr) == 0) {
331 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
333 av_write_frame(s, ost->index, audio_out, ret);
336 /* output a pcm frame */
337 /* XXX: change encoding codec API to avoid this ? */
338 switch(enc->codec->id) {
339 case CODEC_ID_PCM_S16LE:
340 case CODEC_ID_PCM_S16BE:
341 case CODEC_ID_PCM_U16LE:
342 case CODEC_ID_PCM_U16BE:
345 size_out = size_out >> 1;
348 ret = avcodec_encode_audio(enc, audio_out, size_out,
350 av_write_frame(s, ost->index, audio_out, ret);
354 /* write a picture to a raw mux */
355 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
356 int pix_fmt, int w, int h)
358 UINT8 *buf, *src, *dest;
361 /* XXX: not efficient, should add test if we can take
362 directly the AVPicture */
364 case PIX_FMT_YUV420P:
365 size = avpicture_get_size(pix_fmt, w, h);
366 buf = av_malloc(size);
375 src = picture->data[i];
377 memcpy(dest, src, w);
379 src += picture->linesize[i];
383 case PIX_FMT_YUV422P:
385 buf = av_malloc(size);
393 src = picture->data[i];
395 memcpy(dest, src, w);
397 src += picture->linesize[i];
401 case PIX_FMT_YUV444P:
403 buf = av_malloc(size);
408 src = picture->data[i];
410 memcpy(dest, src, w);
412 src += picture->linesize[i];
418 buf = av_malloc(size);
422 src = picture->data[0];
424 memcpy(dest, src, w * 2);
426 src += picture->linesize[0];
432 buf = av_malloc(size);
436 src = picture->data[0];
438 memcpy(dest, src, w * 3);
440 src += picture->linesize[0];
446 av_write_frame(s, index, buf, size);
450 /* we begin to correct av delay at this threshold */
451 #define AV_DELAY_MAX 0.100
453 static void do_video_out(AVFormatContext *s,
457 int *frame_size, AVOutputStream *audio_sync)
459 int nb_frames, i, ret;
460 AVPicture *picture, *picture2, *pict;
461 AVPicture picture_tmp1, picture_tmp2;
462 static UINT8 *video_buffer;
463 UINT8 *buf = NULL, *buf1 = NULL;
464 AVCodecContext *enc, *dec;
466 #define VIDEO_BUFFER_SIZE (1024*1024)
468 enc = &ost->st->codec;
469 dec = &ist->st->codec;
471 /* by default, we output a single frame */
474 /* NOTE: the A/V sync is always done by considering the audio is
475 the master clock. It is suffisant for transcoding or playing,
476 but not for the general case */
478 /* compute the A-V delay and duplicate/remove frames if needed */
479 double adelta, vdelta, apts, vpts, av_delay;
481 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
482 ost->sync_ipts != AV_NOPTS_VALUE) {
484 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
485 s->pts_num / s->pts_den;
486 apts = audio_sync->sync_ipts + adelta;
488 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
489 s->pts_num / s->pts_den;
490 vpts = ost->sync_ipts + vdelta;
492 av_delay = apts - vpts;
493 // printf("delay=%f\n", av_delay);
494 if (av_delay < -AV_DELAY_MAX)
496 else if (av_delay > AV_DELAY_MAX)
500 /* XXX: also handle frame rate conversion */
505 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
509 /* deinterlace : must be done before any resize */
510 if (do_deinterlace) {
513 /* create temporary picture */
514 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
515 buf1 = av_malloc(size);
519 picture2 = &picture_tmp2;
520 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
522 if (avpicture_deinterlace(picture2, picture1,
523 dec->pix_fmt, dec->width, dec->height) < 0) {
524 /* if error, do not deinterlace */
533 /* convert pixel format if needed */
534 if (enc->pix_fmt != dec->pix_fmt) {
537 /* create temporary picture */
538 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
539 buf = av_malloc(size);
542 pict = &picture_tmp1;
543 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
545 if (img_convert(pict, enc->pix_fmt,
546 picture2, dec->pix_fmt,
547 dec->width, dec->height) < 0) {
548 fprintf(stderr, "pixel format conversion not handled\n");
555 /* XXX: resampling could be done before raw format convertion in
556 some cases to go faster */
557 /* XXX: only works for YUV420P */
558 if (ost->video_resample) {
559 picture = &ost->pict_tmp;
560 img_resample(ost->img_resample_ctx, picture, pict);
564 /* duplicates frame if needed */
565 /* XXX: pb because no interleaving */
566 for(i=0;i<nb_frames;i++) {
567 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
568 /* handles sameq here. This is not correct because it may
569 not be a global option */
571 enc->quality = dec->quality;
574 ret = avcodec_encode_video(enc,
575 video_buffer, VIDEO_BUFFER_SIZE,
577 //enc->frame_number = enc->real_pict_num;
578 av_write_frame(s, ost->index, video_buffer, ret);
580 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
581 // enc->frame_number-1, enc->real_pict_num, ret,
583 /* if two pass, output log */
584 if (ost->logfile && enc->stats_out) {
585 fprintf(ost->logfile, "%s", enc->stats_out);
588 if (s->oformat->flags & AVFMT_RAWPICTURE) {
589 /* raw pictures are written as AVPicture structure to
590 avoid any copies. We support temorarily the older
592 av_write_frame(s, ost->index,
593 (UINT8 *)picture, sizeof(AVPicture));
595 write_picture(s, ost->index, picture, enc->pix_fmt,
596 enc->width, enc->height);
606 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
609 static FILE *fvstats=NULL;
610 static INT64 total_size = 0;
617 double ti1, bitrate, avg_bitrate;
621 today = localtime(&today2);
622 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
625 fvstats = fopen(filename,"w");
633 enc = &ost->st->codec;
634 total_size += frame_size;
635 if (enc->codec_type == CODEC_TYPE_VIDEO) {
636 frame_number = ost->frame_number;
637 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
639 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
641 fprintf(fvstats,"f_size= %6d ", frame_size);
642 /* compute pts value */
643 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
647 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
648 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
649 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
650 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
651 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
655 void print_report(AVFormatContext **output_files,
656 AVOutputStream **ost_table, int nb_ostreams,
661 AVFormatContext *oc, *os;
664 int frame_number, vid, i;
665 double bitrate, ti1, pts;
666 static INT64 last_time = -1;
668 if (!is_last_report) {
670 /* display the report every 0.5 seconds */
671 cur_time = av_gettime();
672 if (last_time == -1) {
673 last_time = cur_time;
676 if ((cur_time - last_time) < 500000)
678 last_time = cur_time;
682 oc = output_files[0];
684 total_size = url_ftell(&oc->pb);
689 for(i=0;i<nb_ostreams;i++) {
691 os = output_files[ost->file_index];
692 enc = &ost->st->codec;
693 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
694 frame_number = ost->frame_number;
695 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
696 frame_number, enc->quality);
698 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
701 /* compute min output value */
702 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
703 if ((pts < ti1) && (pts > 0))
708 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
710 sprintf(buf + strlen(buf),
711 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
712 (double)total_size / 1024, ti1, bitrate);
714 fprintf(stderr, "%s ", buf);
716 if (is_last_report) {
717 fprintf(stderr, "\n");
719 fprintf(stderr, "\r");
725 * The following code is the main loop of the file converter
727 static int av_encode(AVFormatContext **output_files,
729 AVFormatContext **input_files,
731 AVStreamMap *stream_maps, int nb_stream_maps)
733 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
734 AVFormatContext *is, *os;
735 AVCodecContext *codec, *icodec;
736 AVOutputStream *ost, **ost_table = NULL;
737 AVInputStream *ist, **ist_table = NULL;
738 AVInputFile *file_table;
739 AVFormatContext *stream_no_data;
742 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
746 /* input stream init */
748 for(i=0;i<nb_input_files;i++) {
750 file_table[i].ist_index = j;
751 file_table[i].nb_streams = is->nb_streams;
756 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
760 for(i=0;i<nb_istreams;i++) {
761 ist = av_mallocz(sizeof(AVInputStream));
767 for(i=0;i<nb_input_files;i++) {
769 for(k=0;k<is->nb_streams;k++) {
770 ist = ist_table[j++];
771 ist->st = is->streams[k];
774 ist->discard = 1; /* the stream is discarded by default
779 /* output stream init */
781 for(i=0;i<nb_output_files;i++) {
782 os = output_files[i];
783 nb_ostreams += os->nb_streams;
785 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
786 fprintf(stderr, "Number of stream maps must match number of output streams\n");
790 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
793 for(i=0;i<nb_ostreams;i++) {
794 ost = av_mallocz(sizeof(AVOutputStream));
801 for(k=0;k<nb_output_files;k++) {
802 os = output_files[k];
803 for(i=0;i<os->nb_streams;i++) {
805 ost = ost_table[n++];
808 ost->st = os->streams[i];
809 if (nb_stream_maps > 0) {
810 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
811 stream_maps[n-1].stream_index;
813 /* get corresponding input stream index : we select the first one with the right type */
815 for(j=0;j<nb_istreams;j++) {
818 ist->st->codec.codec_type == ost->st->codec.codec_type) {
819 ost->source_index = j;
825 /* try again and reuse existing stream */
826 for(j=0;j<nb_istreams;j++) {
828 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
829 ost->source_index = j;
834 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
835 ost->file_index, ost->index);
840 ist = ist_table[ost->source_index];
845 /* for each output stream, we compute the right encoding parameters */
846 for(i=0;i<nb_ostreams;i++) {
848 ist = ist_table[ost->source_index];
850 codec = &ost->st->codec;
851 icodec = &ist->st->codec;
853 if (ost->st->stream_copy) {
854 /* if stream_copy is selected, no need to decode or encode */
855 codec->codec_id = icodec->codec_id;
856 codec->codec_type = icodec->codec_type;
857 codec->codec_tag = icodec->codec_tag;
858 codec->bit_rate = icodec->bit_rate;
859 switch(codec->codec_type) {
860 case CODEC_TYPE_AUDIO:
861 codec->sample_rate = icodec->sample_rate;
862 codec->channels = icodec->channels;
864 case CODEC_TYPE_VIDEO:
865 codec->frame_rate = icodec->frame_rate;
866 codec->width = icodec->width;
867 codec->height = icodec->height;
873 switch(codec->codec_type) {
874 case CODEC_TYPE_AUDIO:
875 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
878 if (codec->channels == icodec->channels &&
879 codec->sample_rate == icodec->sample_rate) {
880 ost->audio_resample = 0;
882 if (codec->channels != icodec->channels &&
883 icodec->codec_id == CODEC_ID_AC3) {
884 /* Special case for 5:1 AC3 input */
885 /* and mono or stereo output */
886 /* Request specific number of channels */
887 icodec->channels = codec->channels;
888 if (codec->sample_rate == icodec->sample_rate)
889 ost->audio_resample = 0;
891 ost->audio_resample = 1;
892 ost->resample = audio_resample_init(codec->channels, icodec->channels,
894 icodec->sample_rate);
896 /* Request specific number of channels */
897 icodec->channels = codec->channels;
899 ost->audio_resample = 1;
900 ost->resample = audio_resample_init(codec->channels, icodec->channels,
902 icodec->sample_rate);
905 ist->decoding_needed = 1;
906 ost->encoding_needed = 1;
908 case CODEC_TYPE_VIDEO:
909 if (codec->width == icodec->width &&
910 codec->height == icodec->height) {
911 ost->video_resample = 0;
914 ost->video_resample = 1;
915 buf = av_malloc((codec->width * codec->height * 3) / 2);
918 ost->pict_tmp.data[0] = buf;
919 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
920 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
921 ost->pict_tmp.linesize[0] = codec->width;
922 ost->pict_tmp.linesize[1] = codec->width / 2;
923 ost->pict_tmp.linesize[2] = codec->width / 2;
925 ost->img_resample_ctx = img_resample_full_init(
926 ost->st->codec.width, ost->st->codec.height,
927 ist->st->codec.width, ist->st->codec.height,
928 frame_topBand, frame_bottomBand,
929 frame_leftBand, frame_rightBand);
931 ost->encoding_needed = 1;
932 ist->decoding_needed = 1;
938 if (ost->encoding_needed &&
939 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
940 char logfilename[1024];
945 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
947 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
948 if (codec->flags & CODEC_FLAG_PASS1) {
949 f = fopen(logfilename, "w");
956 /* read the log file */
957 f = fopen(logfilename, "r");
962 fseek(f, 0, SEEK_END);
964 fseek(f, 0, SEEK_SET);
965 logbuffer = av_malloc(size + 1);
967 fprintf(stderr, "Could not allocate log buffer\n");
970 fread(logbuffer, 1, size, f);
972 logbuffer[size] = '\0';
973 codec->stats_in = logbuffer;
979 /* dump the file output parameters - cannot be done before in case
981 for(i=0;i<nb_output_files;i++) {
982 dump_format(output_files[i], i, output_files[i]->filename, 1);
985 /* dump the stream mapping */
986 fprintf(stderr, "Stream mapping:\n");
987 for(i=0;i<nb_ostreams;i++) {
989 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
990 ist_table[ost->source_index]->file_index,
991 ist_table[ost->source_index]->index,
996 /* open each encoder */
997 for(i=0;i<nb_ostreams;i++) {
999 if (ost->encoding_needed) {
1001 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1003 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1004 ost->file_index, ost->index);
1007 if (avcodec_open(&ost->st->codec, codec) < 0) {
1008 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1009 ost->file_index, ost->index);
1015 /* open each decoder */
1016 for(i=0;i<nb_istreams;i++) {
1018 if (ist->decoding_needed) {
1020 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1022 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
1023 ist->file_index, ist->index);
1026 if (avcodec_open(&ist->st->codec, codec) < 0) {
1027 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1028 ist->file_index, ist->index);
1031 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1032 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1033 ist->frame_decoded = 1;
1038 for(i=0;i<nb_istreams;i++) {
1042 /* compute buffer size max (should use a complete heuristic) */
1043 for(i=0;i<nb_input_files;i++) {
1044 file_table[i].buffer_size_max = 2048;
1047 /* open files and write file headers */
1048 for(i=0;i<nb_output_files;i++) {
1049 os = output_files[i];
1050 if (av_write_header(os) < 0) {
1051 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1057 #ifndef CONFIG_WIN32
1059 fprintf(stderr, "Press [q] to stop encoding\n");
1061 fprintf(stderr, "Press [q] to stop playing\n");
1070 int file_index, ist_index;
1075 int data_size, got_picture;
1077 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1081 /* if 'q' pressed, exits */
1083 /* read_key() returns 0 on EOF */
1089 /* select the stream that we must read now by looking at the
1090 smallest output pts */
1093 for(i=0;i<nb_ostreams;i++) {
1096 os = output_files[ost->file_index];
1097 ist = ist_table[ost->source_index];
1098 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1099 if (!file_table[ist->file_index].eof_reached &&
1102 file_index = ist->file_index;
1105 /* if none, if is finished */
1106 if (file_index < 0) {
1110 /* finish if recording time exhausted */
1111 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1114 /* read a packet from it and output it in the fifo */
1115 is = input_files[file_index];
1116 if (av_read_packet(is, &pkt) < 0) {
1117 file_table[file_index].eof_reached = 1;
1121 stream_no_data = is;
1125 /* the following test is needed in case new streams appear
1126 dynamically in stream : we ignore them */
1127 if (pkt.stream_index >= file_table[file_index].nb_streams)
1128 goto discard_packet;
1129 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1130 ist = ist_table[ist_index];
1132 goto discard_packet;
1135 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1136 av_hex_dump(pkt.data, pkt.size);
1139 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1147 ipts = AV_NOPTS_VALUE;
1149 /* decode the packet if needed */
1150 data_buf = NULL; /* fail safe */
1152 if (ist->decoding_needed) {
1153 /* NOTE1: we only take into account the PTS if a new
1154 frame has begun (MPEG semantics) */
1155 /* NOTE2: even if the fraction is not initialized,
1156 av_frac_set can be used to set the integer part */
1157 if (ist->frame_decoded &&
1158 pkt.pts != AV_NOPTS_VALUE &&
1161 ist->frame_decoded = 0;
1165 switch(ist->st->codec.codec_type) {
1166 case CODEC_TYPE_AUDIO:
1167 /* XXX: could avoid copy if PCM 16 bits with same
1168 endianness as CPU */
1169 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1173 /* Some bug in mpeg audio decoder gives */
1174 /* data_size < 0, it seems they are overflows */
1175 if (data_size <= 0) {
1176 /* no audio frame */
1181 data_buf = (UINT8 *)samples;
1183 case CODEC_TYPE_VIDEO:
1184 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1187 size = (ist->st->codec.width * ist->st->codec.height);
1188 avpicture_fill(&picture, ptr,
1189 ist->st->codec.pix_fmt,
1190 ist->st->codec.width,
1191 ist->st->codec.height);
1194 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1195 ret = avcodec_decode_video(&ist->st->codec,
1196 &picture, &got_picture, ptr, len);
1199 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1200 ist->file_index, ist->index);
1201 av_free_packet(&pkt);
1205 /* no picture yet */
1224 ist->frame_decoded = 1;
1227 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1228 is the one of the next displayed one */
1229 /* XXX: add mpeg4 too ? */
1230 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1231 if (ist->st->codec.pict_type != B_TYPE) {
1233 tmp = ist->last_ip_pts;
1234 ist->last_ip_pts = ist->frac_pts.val;
1235 ist->frac_pts.val = tmp;
1239 /* transcode raw format, encode packets and output them */
1241 for(i=0;i<nb_ostreams;i++) {
1245 if (ost->source_index == ist_index) {
1246 os = output_files[ost->file_index];
1248 if (ipts != AV_NOPTS_VALUE) {
1250 printf("%d: got pts=%f %f\n",
1251 i, pkt.pts / 90000.0,
1252 (ipts - ost->st->pts.val) / 90000.0);
1254 /* set the input output pts pairs */
1255 ost->sync_ipts = (double)ipts * is->pts_num /
1257 /* XXX: take into account the various fifos,
1258 in particular for audio */
1259 ost->sync_opts = ost->st->pts.val;
1262 if (ost->encoding_needed) {
1263 switch(ost->st->codec.codec_type) {
1264 case CODEC_TYPE_AUDIO:
1265 do_audio_out(os, ost, ist, data_buf, data_size);
1267 case CODEC_TYPE_VIDEO:
1268 /* find an audio stream for synchro */
1271 AVOutputStream *audio_sync, *ost1;
1273 for(i=0;i<nb_ostreams;i++) {
1274 ost1 = ost_table[i];
1275 if (ost1->file_index == ost->file_index &&
1276 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1282 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1284 do_video_stats(os, ost, frame_size);
1291 /* no reencoding needed : output the packet directly */
1292 /* force the input stream PTS */
1293 av_write_frame(os, ost->index, data_buf, data_size);
1294 ost->st->codec.frame_number++;
1295 ost->frame_number++;
1299 ipts = AV_NOPTS_VALUE;
1302 av_free_packet(&pkt);
1304 /* dump report by using the output first video and audio streams */
1305 print_report(output_files, ost_table, nb_ostreams, 0);
1309 /* dump report by using the first video and audio streams */
1310 print_report(output_files, ost_table, nb_ostreams, 1);
1312 /* close each encoder */
1313 for(i=0;i<nb_ostreams;i++) {
1315 if (ost->encoding_needed) {
1316 av_freep(&ost->st->codec.stats_in);
1317 avcodec_close(&ost->st->codec);
1321 /* close each decoder */
1322 for(i=0;i<nb_istreams;i++) {
1324 if (ist->decoding_needed) {
1325 avcodec_close(&ist->st->codec);
1330 /* write the trailer if needed and close file */
1331 for(i=0;i<nb_output_files;i++) {
1332 os = output_files[i];
1333 av_write_trailer(os);
1339 av_free(file_table);
1342 for(i=0;i<nb_istreams;i++) {
1349 for(i=0;i<nb_ostreams;i++) {
1353 fclose(ost->logfile);
1354 ost->logfile = NULL;
1356 fifo_free(&ost->fifo); /* works even if fifo is not
1357 initialized but set to zero */
1358 av_free(ost->pict_tmp.data[0]);
1359 if (ost->video_resample)
1360 img_resample_close(ost->img_resample_ctx);
1361 if (ost->audio_resample)
1362 audio_resample_close(ost->resample);
1375 int file_read(const char *filename)
1378 unsigned char buffer[1024];
1381 if (url_open(&h, filename, O_RDONLY) < 0) {
1382 printf("could not open '%s'\n", filename);
1386 len = url_read(h, buffer, sizeof(buffer));
1389 for(i=0;i<len;i++) putchar(buffer[i]);
1396 void show_licence(void)
1399 "ffmpeg version " FFMPEG_VERSION "\n"
1400 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1401 "This library is free software; you can redistribute it and/or\n"
1402 "modify it under the terms of the GNU Lesser General Public\n"
1403 "License as published by the Free Software Foundation; either\n"
1404 "version 2 of the License, or (at your option) any later version.\n"
1406 "This library is distributed in the hope that it will be useful,\n"
1407 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1408 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1409 "Lesser General Public License for more details.\n"
1411 "You should have received a copy of the GNU Lesser General Public\n"
1412 "License along with this library; if not, write to the Free Software\n"
1413 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1418 void opt_format(const char *arg)
1420 file_iformat = av_find_input_format(arg);
1421 file_oformat = guess_format(arg, NULL, NULL);
1422 if (!file_iformat && !file_oformat) {
1423 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1428 void opt_video_bitrate(const char *arg)
1430 video_bit_rate = atoi(arg) * 1000;
1433 void opt_video_bitrate_tolerance(const char *arg)
1435 video_bit_rate_tolerance = atoi(arg) * 1000;
1438 void opt_video_bitrate_max(const char *arg)
1440 video_rc_max_rate = atoi(arg) * 1000;
1443 void opt_video_bitrate_min(const char *arg)
1445 video_rc_min_rate = atoi(arg) * 1000;
1448 void opt_video_buffer_size(const char *arg)
1450 video_rc_buffer_size = atoi(arg) * 1000;
1453 void opt_video_rc_eq(char *arg)
1458 void opt_video_rc_override_string(char *arg)
1460 video_rc_override_string = arg;
1464 void opt_workaround_bugs(const char *arg)
1466 workaround_bugs = atoi(arg);
1469 void opt_dct_algo(const char *arg)
1471 dct_algo = atoi(arg);
1474 void opt_idct_algo(const char *arg)
1476 idct_algo = atoi(arg);
1480 void opt_error_resilience(const char *arg)
1482 error_resilience = atoi(arg);
1485 void opt_error_concealment(const char *arg)
1487 error_concealment = atoi(arg);
1491 void opt_frame_rate(const char *arg)
1493 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1497 void opt_frame_crop_top(const char *arg)
1499 frame_topBand = atoi(arg);
1500 if (frame_topBand < 0) {
1501 fprintf(stderr, "Incorrect top crop size\n");
1504 if ((frame_topBand % 2) != 0) {
1505 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1508 if ((frame_topBand) >= frame_height){
1509 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1512 frame_height -= frame_topBand;
1515 void opt_frame_crop_bottom(const char *arg)
1517 frame_bottomBand = atoi(arg);
1518 if (frame_bottomBand < 0) {
1519 fprintf(stderr, "Incorrect bottom crop size\n");
1522 if ((frame_bottomBand % 2) != 0) {
1523 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1526 if ((frame_bottomBand) >= frame_height){
1527 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1530 frame_height -= frame_bottomBand;
1533 void opt_frame_crop_left(const char *arg)
1535 frame_leftBand = atoi(arg);
1536 if (frame_leftBand < 0) {
1537 fprintf(stderr, "Incorrect left crop size\n");
1540 if ((frame_leftBand % 2) != 0) {
1541 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1544 if ((frame_leftBand) >= frame_width){
1545 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1548 frame_width -= frame_leftBand;
1551 void opt_frame_crop_right(const char *arg)
1553 frame_rightBand = atoi(arg);
1554 if (frame_rightBand < 0) {
1555 fprintf(stderr, "Incorrect right crop size\n");
1558 if ((frame_rightBand % 2) != 0) {
1559 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1562 if ((frame_rightBand) >= frame_width){
1563 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1566 frame_width -= frame_rightBand;
1569 void opt_frame_size(const char *arg)
1571 parse_image_size(&frame_width, &frame_height, arg);
1572 if (frame_width <= 0 || frame_height <= 0) {
1573 fprintf(stderr, "Incorrect frame size\n");
1576 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1577 fprintf(stderr, "Frame size must be a multiple of 2\n");
1582 void opt_gop_size(const char *arg)
1584 gop_size = atoi(arg);
1587 void opt_b_frames(const char *arg)
1589 b_frames = atoi(arg);
1590 if (b_frames > FF_MAX_B_FRAMES) {
1591 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1593 } else if (b_frames < 1) {
1594 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1599 void opt_qscale(const char *arg)
1601 video_qscale = atoi(arg);
1602 if (video_qscale < 0 ||
1603 video_qscale > 31) {
1604 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1609 void opt_qmin(const char *arg)
1611 video_qmin = atoi(arg);
1612 if (video_qmin < 0 ||
1614 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1619 void opt_qmax(const char *arg)
1621 video_qmax = atoi(arg);
1622 if (video_qmax < 0 ||
1624 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1629 void opt_qdiff(const char *arg)
1631 video_qdiff = atoi(arg);
1632 if (video_qdiff < 0 ||
1634 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1639 void opt_qblur(const char *arg)
1641 video_qblur = atof(arg);
1644 void opt_qcomp(const char *arg)
1646 video_qcomp = atof(arg);
1649 void opt_rc_initial_cplx(const char *arg)
1651 video_rc_initial_cplx = atof(arg);
1653 void opt_b_qfactor(const char *arg)
1655 video_b_qfactor = atof(arg);
1657 void opt_i_qfactor(const char *arg)
1659 video_i_qfactor = atof(arg);
1661 void opt_b_qoffset(const char *arg)
1663 video_b_qoffset = atof(arg);
1665 void opt_i_qoffset(const char *arg)
1667 video_i_qoffset = atof(arg);
1670 void opt_packet_size(const char *arg)
1672 packet_size= atoi(arg);
1675 void opt_audio_bitrate(const char *arg)
1677 audio_bit_rate = atoi(arg) * 1000;
1680 void opt_audio_rate(const char *arg)
1682 audio_sample_rate = atoi(arg);
1685 void opt_audio_channels(const char *arg)
1687 audio_channels = atoi(arg);
1690 void opt_video_device(const char *arg)
1692 v4l_device = strdup(arg);
1695 void opt_audio_device(const char *arg)
1697 audio_device = strdup(arg);
1700 void opt_audio_codec(const char *arg)
1704 if (!strcmp(arg, "copy")) {
1705 audio_stream_copy = 1;
1709 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1714 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1717 audio_codec_id = p->id;
1722 const char *motion_str[] = {
1732 void opt_motion_estimation(const char *arg)
1738 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1741 if (!strcmp(*p, arg))
1745 me_method = (p - motion_str) + 1;
1748 void opt_video_codec(const char *arg)
1752 if (!strcmp(arg, "copy")) {
1753 video_stream_copy = 1;
1757 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1762 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1765 video_codec_id = p->id;
1770 void opt_map(const char *arg)
1776 m = &stream_maps[nb_stream_maps++];
1778 m->file_index = strtol(arg, (char **)&p, 0);
1782 m->stream_index = strtol(p, (char **)&p, 0);
1785 void opt_recording_time(const char *arg)
1787 recording_time = parse_date(arg, 1);
1790 void print_error(const char *filename, int err)
1793 case AVERROR_NUMEXPECTED:
1794 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1795 "Use '%%d' to specify the image number:\n"
1796 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1797 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1800 case AVERROR_INVALIDDATA:
1801 fprintf(stderr, "%s: Error while parsing header\n", filename);
1804 fprintf(stderr, "%s: Unknown format\n", filename);
1807 fprintf(stderr, "%s: Error while opening file\n", filename);
1812 void opt_input_file(const char *filename)
1814 AVFormatContext *ic;
1815 AVFormatParameters params, *ap = ¶ms;
1816 int err, i, ret, rfps;
1818 /* get default parameters from command line */
1819 memset(ap, 0, sizeof(*ap));
1820 ap->sample_rate = audio_sample_rate;
1821 ap->channels = audio_channels;
1822 ap->frame_rate = frame_rate;
1823 ap->width = frame_width;
1824 ap->height = frame_height;
1826 /* open the input file with generic libav function */
1827 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1829 print_error(filename, err);
1833 /* If not enough info to get the stream parameters, we decode the
1834 first frames to get it. (used in mpeg case for example) */
1835 ret = av_find_stream_info(ic);
1837 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1841 /* update the current parameters so that they match the one of the input stream */
1842 for(i=0;i<ic->nb_streams;i++) {
1843 AVCodecContext *enc = &ic->streams[i]->codec;
1844 switch(enc->codec_type) {
1845 case CODEC_TYPE_AUDIO:
1846 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1847 audio_channels = enc->channels;
1848 audio_sample_rate = enc->sample_rate;
1850 case CODEC_TYPE_VIDEO:
1851 frame_height = enc->height;
1852 frame_width = enc->width;
1853 rfps = ic->streams[i]->r_frame_rate;
1854 enc->workaround_bugs = workaround_bugs;
1855 enc->error_resilience = error_resilience;
1856 enc->error_concealment = error_concealment;
1857 enc->idct_algo= idct_algo;
1858 /* if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1859 enc->flags|= CODEC_FLAG_TRUNCATED; */
1860 if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
1861 enc->flags|= CODEC_FLAG_TRUNCATED;
1863 if (enc->frame_rate != rfps) {
1864 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1865 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1866 (float)rfps / FRAME_RATE_BASE);
1868 /* update the current frame rate to match the stream frame rate */
1876 input_files[nb_input_files] = ic;
1877 /* dump the file content */
1878 dump_format(ic, nb_input_files, filename, 0);
1880 file_iformat = NULL;
1881 file_oformat = NULL;
1884 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1886 int has_video, has_audio, i, j;
1887 AVFormatContext *ic;
1891 for(j=0;j<nb_input_files;j++) {
1892 ic = input_files[j];
1893 for(i=0;i<ic->nb_streams;i++) {
1894 AVCodecContext *enc = &ic->streams[i]->codec;
1895 switch(enc->codec_type) {
1896 case CODEC_TYPE_AUDIO:
1899 case CODEC_TYPE_VIDEO:
1907 *has_video_ptr = has_video;
1908 *has_audio_ptr = has_audio;
1911 void opt_output_file(const char *filename)
1914 AVFormatContext *oc;
1915 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1918 if (!strcmp(filename, "-"))
1921 oc = av_mallocz(sizeof(AVFormatContext));
1923 if (!file_oformat) {
1924 file_oformat = guess_format(NULL, filename, NULL);
1925 if (!file_oformat) {
1926 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1932 oc->oformat = file_oformat;
1934 if (!strcmp(file_oformat->name, "ffm") &&
1935 strstart(filename, "http:", NULL)) {
1936 /* special case for files sent to ffserver: we get the stream
1937 parameters from ffserver */
1938 if (read_ffserver_streams(oc, filename) < 0) {
1939 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1943 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1944 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1946 /* disable if no corresponding type found and at least one
1948 if (nb_input_files > 0) {
1949 check_audio_video_inputs(&input_has_video, &input_has_audio);
1950 if (!input_has_video)
1952 if (!input_has_audio)
1956 /* manual disable */
1957 if (audio_disable) {
1960 if (video_disable) {
1966 AVCodecContext *video_enc;
1968 st = av_mallocz(sizeof(AVStream));
1970 fprintf(stderr, "Could not alloc stream\n");
1974 video_enc = &st->codec;
1975 if (video_stream_copy) {
1976 st->stream_copy = 1;
1977 video_enc->codec_type = CODEC_TYPE_VIDEO;
1982 codec_id = file_oformat->video_codec;
1983 if (video_codec_id != CODEC_ID_NONE)
1984 codec_id = video_codec_id;
1986 video_enc->codec_id = codec_id;
1988 video_enc->bit_rate = video_bit_rate;
1989 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1990 video_enc->frame_rate = frame_rate;
1992 video_enc->width = frame_width;
1993 video_enc->height = frame_height;
1996 video_enc->gop_size = gop_size;
1998 video_enc->gop_size = 0;
1999 if (video_qscale || same_quality) {
2000 video_enc->flags |= CODEC_FLAG_QSCALE;
2001 video_enc->quality = video_qscale;
2005 video_enc->flags |= CODEC_FLAG_HQ;
2009 video_enc->flags |= CODEC_FLAG_HQ;
2010 video_enc->flags |= CODEC_FLAG_4MV;
2014 video_enc->flags |= CODEC_FLAG_PART;
2018 if (codec_id != CODEC_ID_MPEG4) {
2019 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2022 video_enc->max_b_frames = b_frames;
2023 video_enc->b_frame_strategy = 0;
2024 video_enc->b_quant_factor = 2.0;
2027 video_enc->qmin = video_qmin;
2028 video_enc->qmax = video_qmax;
2029 video_enc->max_qdiff = video_qdiff;
2030 video_enc->qblur = video_qblur;
2031 video_enc->qcompress = video_qcomp;
2032 video_enc->rc_eq = video_rc_eq;
2034 p= video_rc_override_string;
2037 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2039 fprintf(stderr, "error parsing rc_override\n");
2042 video_enc->rc_override=
2043 realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2044 video_enc->rc_override[i].start_frame= start;
2045 video_enc->rc_override[i].end_frame = end;
2047 video_enc->rc_override[i].qscale= q;
2048 video_enc->rc_override[i].quality_factor= 1.0;
2051 video_enc->rc_override[i].qscale= 0;
2052 video_enc->rc_override[i].quality_factor= -q/100.0;
2057 video_enc->rc_override_count=i;
2059 video_enc->rc_max_rate = video_rc_max_rate;
2060 video_enc->rc_min_rate = video_rc_min_rate;
2061 video_enc->rc_buffer_size = video_rc_buffer_size;
2062 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2063 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2064 video_enc->i_quant_factor = video_i_qfactor;
2065 video_enc->b_quant_factor = video_b_qfactor;
2066 video_enc->i_quant_offset = video_i_qoffset;
2067 video_enc->b_quant_offset = video_b_qoffset;
2068 video_enc->dct_algo = dct_algo;
2069 video_enc->idct_algo = idct_algo;
2071 video_enc->rtp_mode= 1;
2072 video_enc->rtp_payload_size= packet_size;
2076 video_enc->get_psnr = 1;
2078 video_enc->get_psnr = 0;
2080 video_enc->me_method = me_method;
2085 video_enc->flags |= CODEC_FLAG_PASS1;
2087 video_enc->flags |= CODEC_FLAG_PASS2;
2091 /* XXX: need to find a way to set codec parameters */
2092 if (oc->oformat->flags & AVFMT_RGB24) {
2093 video_enc->pix_fmt = PIX_FMT_RGB24;
2096 oc->streams[nb_streams] = st;
2101 AVCodecContext *audio_enc;
2103 st = av_mallocz(sizeof(AVStream));
2105 fprintf(stderr, "Could not alloc stream\n");
2109 audio_enc = &st->codec;
2110 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2111 if (audio_stream_copy) {
2112 st->stream_copy = 1;
2114 codec_id = file_oformat->audio_codec;
2115 if (audio_codec_id != CODEC_ID_NONE)
2116 codec_id = audio_codec_id;
2117 audio_enc->codec_id = codec_id;
2119 audio_enc->bit_rate = audio_bit_rate;
2120 audio_enc->sample_rate = audio_sample_rate;
2121 /* For audio codecs other than AC3 we limit */
2122 /* the number of coded channels to stereo */
2123 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2124 audio_enc->channels = 2;
2126 audio_enc->channels = audio_channels;
2128 oc->streams[nb_streams] = st;
2132 oc->nb_streams = nb_streams;
2135 fprintf(stderr, "No audio or video streams available\n");
2140 pstrcpy(oc->title, sizeof(oc->title), str_title);
2142 pstrcpy(oc->author, sizeof(oc->author), str_author);
2144 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2146 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2149 output_files[nb_output_files++] = oc;
2151 strcpy(oc->filename, filename);
2153 /* check filename in case of an image number is expected */
2154 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2155 if (filename_number_test(oc->filename) < 0) {
2156 print_error(oc->filename, AVERROR_NUMEXPECTED);
2161 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2162 /* test if it already exists to avoid loosing precious files */
2163 if (!file_overwrite &&
2164 (strchr(filename, ':') == NULL ||
2165 strstart(filename, "file:", NULL))) {
2166 if (url_exist(filename)) {
2169 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2172 if (toupper(c) != 'Y') {
2173 fprintf(stderr, "Not overwriting - exiting\n");
2180 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2181 fprintf(stderr, "Could not open '%s'\n", filename);
2186 /* reset some options */
2187 file_oformat = NULL;
2188 file_iformat = NULL;
2191 audio_codec_id = CODEC_ID_NONE;
2192 video_codec_id = CODEC_ID_NONE;
2193 audio_stream_copy = 0;
2194 video_stream_copy = 0;
2197 /* prepare dummy protocols for grab */
2198 void prepare_grab(void)
2200 int has_video, has_audio, i, j;
2201 AVFormatContext *oc;
2202 AVFormatContext *ic;
2203 AVFormatParameters ap1, *ap = &ap1;
2205 /* see if audio/video inputs are needed */
2208 memset(ap, 0, sizeof(*ap));
2209 for(j=0;j<nb_output_files;j++) {
2210 oc = output_files[j];
2211 for(i=0;i<oc->nb_streams;i++) {
2212 AVCodecContext *enc = &oc->streams[i]->codec;
2213 switch(enc->codec_type) {
2214 case CODEC_TYPE_AUDIO:
2215 if (enc->sample_rate > ap->sample_rate)
2216 ap->sample_rate = enc->sample_rate;
2217 if (enc->channels > ap->channels)
2218 ap->channels = enc->channels;
2221 case CODEC_TYPE_VIDEO:
2222 if (enc->width > ap->width)
2223 ap->width = enc->width;
2224 if (enc->height > ap->height)
2225 ap->height = enc->height;
2226 if (enc->frame_rate > ap->frame_rate)
2227 ap->frame_rate = enc->frame_rate;
2236 if (has_video == 0 && has_audio == 0) {
2237 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2242 AVInputFormat *fmt1;
2243 fmt1 = av_find_input_format("video_grab_device");
2244 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2245 fprintf(stderr, "Could not find video grab device\n");
2248 /* by now video grab has one stream */
2249 ic->streams[0]->r_frame_rate = ap->frame_rate;
2250 input_files[nb_input_files] = ic;
2251 dump_format(ic, nb_input_files, v4l_device, 0);
2255 AVInputFormat *fmt1;
2256 fmt1 = av_find_input_format("audio_device");
2257 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2258 fprintf(stderr, "Could not find audio grab device\n");
2261 input_files[nb_input_files] = ic;
2262 dump_format(ic, nb_input_files, audio_device, 0);
2267 /* open the necessary output devices for playing */
2268 void prepare_play(void)
2270 file_iformat = NULL;
2271 file_oformat = guess_format("audio_device", NULL, NULL);
2272 if (!file_oformat) {
2273 fprintf(stderr, "Could not find audio device\n");
2277 opt_output_file(audio_device);
2280 /* same option as mencoder */
2281 void opt_pass(const char *pass_str)
2284 pass = atoi(pass_str);
2285 if (pass != 1 && pass != 2) {
2286 fprintf(stderr, "pass number can be only 1 or 2\n");
2292 #ifndef CONFIG_WIN32
2293 INT64 getutime(void)
2295 struct rusage rusage;
2297 getrusage(RUSAGE_SELF, &rusage);
2298 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2301 INT64 getutime(void)
2303 return av_gettime();
2307 extern int ffm_nopts;
2309 void opt_bitexact(void)
2311 avcodec_set_bit_exact();
2312 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2316 void show_formats(void)
2318 AVInputFormat *ifmt;
2319 AVOutputFormat *ofmt;
2324 printf("File formats:\n");
2325 printf(" Encoding:");
2326 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2327 printf(" %s", ofmt->name);
2330 printf(" Decoding:");
2331 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2332 printf(" %s", ifmt->name);
2336 printf("Codecs:\n");
2337 printf(" Encoders:");
2338 for(p = first_avcodec; p != NULL; p = p->next) {
2340 printf(" %s", p->name);
2344 printf(" Decoders:");
2345 for(p = first_avcodec; p != NULL; p = p->next) {
2347 printf(" %s", p->name);
2351 printf("Supported file protocols:");
2352 for(up = first_protocol; up != NULL; up = up->next)
2353 printf(" %s:", up->name);
2356 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2357 printf("Motion estimation methods:");
2361 if ((pp - motion_str + 1) == ME_ZERO)
2362 printf("(fastest)");
2363 else if ((pp - motion_str + 1) == ME_FULL)
2364 printf("(slowest)");
2365 else if ((pp - motion_str + 1) == ME_EPZS)
2366 printf("(default)");
2373 void show_help(void)
2376 const OptionDef *po;
2379 prog = do_play ? "ffplay" : "ffmpeg";
2381 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2385 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2386 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2388 printf("usage: ffplay [options] input_file...\n"
2389 "Simple audio player\n");
2393 "Main options are:\n");
2396 printf("\nAdvanced options are:\n");
2397 for(po = options; po->name != NULL; po++) {
2399 expert = (po->flags & OPT_EXPERT) != 0;
2401 strcpy(buf, po->name);
2402 if (po->flags & HAS_ARG) {
2404 strcat(buf, po->argname);
2406 printf("-%-17s %s\n", buf, po->help);
2414 const OptionDef options[] = {
2415 { "L", 0, {(void*)show_licence}, "show license" },
2416 { "h", 0, {(void*)show_help}, "show help" },
2417 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2418 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2419 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2420 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2421 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2422 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2423 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2424 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2425 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2426 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2427 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2428 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2430 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2431 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2432 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2433 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2434 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2435 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2436 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2437 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2438 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2439 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2440 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2441 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2442 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2443 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2444 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2445 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2446 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2447 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2448 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2449 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2450 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2451 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2452 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2453 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2454 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2455 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2456 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2457 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2458 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2459 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2461 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2462 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2463 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2464 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
2465 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2466 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2467 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2468 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2469 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2470 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2471 { "sameq", OPT_BOOL, {(void*)&same_quality},
2472 "use same video quality as source (implies VBR)" },
2474 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2475 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2476 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2477 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2478 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2479 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2480 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2481 "deinterlace pictures" },
2482 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2483 "add timings for benchmarking" },
2484 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2485 "dump each input packet" },
2486 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2487 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2488 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2492 int main(int argc, char **argv)
2495 const char *opt, *arg;
2496 const OptionDef *po;
2501 /* detect if invoked as player */
2502 i = strlen(argv[0]);
2503 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2511 while (optindex < argc) {
2512 opt = argv[optindex++];
2514 if (opt[0] == '-' && opt[1] != '\0') {
2516 while (po->name != NULL) {
2517 if (!strcmp(opt + 1, po->name))
2522 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2526 if (po->flags & HAS_ARG)
2527 arg = argv[optindex++];
2528 if (po->flags & OPT_STRING) {
2531 *po->u.str_arg = str;
2532 } else if (po->flags & OPT_BOOL) {
2535 po->u.func_arg(arg);
2539 opt_output_file(opt);
2541 opt_input_file(opt);
2548 /* file converter / grab */
2549 if (nb_output_files <= 0) {
2550 fprintf(stderr, "Must supply at least one output file\n");
2554 if (nb_input_files == 0) {
2559 if (nb_input_files <= 0) {
2560 fprintf(stderr, "Must supply at least one input file\n");
2567 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2568 stream_maps, nb_stream_maps);
2569 ti = getutime() - ti;
2571 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2575 for(i=0;i<nb_output_files;i++) {
2576 /* maybe av_close_output_file ??? */
2577 AVFormatContext *s = output_files[i];
2579 if (!(s->oformat->flags & AVFMT_NOFILE))
2581 for(j=0;j<s->nb_streams;j++)
2582 av_free(s->streams[j]);
2585 for(i=0;i<nb_input_files;i++)
2586 av_close_input_file(input_files[i]);