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
21 #include "framehook.h"
26 #include <sys/ioctl.h>
29 #include <sys/resource.h>
35 #define MAXINT64 INT64_C(0x7fffffffffffffff)
40 #define HAS_ARG 0x0001
41 #define OPT_BOOL 0x0002
42 #define OPT_EXPERT 0x0004
43 #define OPT_STRING 0x0008
53 /* select an input stream for an output stream */
54 typedef struct AVStreamMap {
59 extern const OptionDef options[];
65 static AVFormatContext *input_files[MAX_FILES];
66 static int nb_input_files = 0;
68 static AVFormatContext *output_files[MAX_FILES];
69 static int nb_output_files = 0;
71 static AVStreamMap stream_maps[MAX_FILES];
72 static int nb_stream_maps;
74 static AVInputFormat *file_iformat;
75 static AVOutputFormat *file_oformat;
76 static int frame_width = 160;
77 static int frame_height = 128;
78 static int frame_topBand = 0;
79 static int frame_bottomBand = 0;
80 static int frame_leftBand = 0;
81 static int frame_rightBand = 0;
82 static int frame_rate = 25 * FRAME_RATE_BASE;
83 static int video_bit_rate = 200*1000;
84 static int video_bit_rate_tolerance = 4000*1000;
85 static int video_qscale = 0;
86 static int video_qmin = 2;
87 static int video_qmax = 31;
88 static int video_qdiff = 3;
89 static float video_qblur = 0.5;
90 static float video_qcomp = 0.5;
91 #if 0 //experimental, (can be removed)
92 static float video_rc_qsquish=1.0;
93 static float video_rc_qmod_amp=0;
94 static int video_rc_qmod_freq=0;
96 static char *video_rc_override_string=NULL;
97 static char *video_rc_eq="tex^qComp";
98 static int video_rc_buffer_size=0;
99 static float video_rc_buffer_aggressivity=1.0;
100 static int video_rc_max_rate=0;
101 static int video_rc_min_rate=0;
102 static float video_rc_initial_cplx=0;
103 static float video_b_qfactor = 1.25;
104 static float video_b_qoffset = 1.25;
105 static float video_i_qfactor = -0.8;
106 static float video_i_qoffset = 0.0;
107 static int me_method = 0;
108 static int video_disable = 0;
109 static int video_codec_id = CODEC_ID_NONE;
110 static int same_quality = 0;
111 static int b_frames = 0;
112 static int use_hq = 0;
113 static int use_4mv = 0;
114 static int do_deinterlace = 0;
115 static int workaround_bugs = FF_BUG_AUTODETECT;
116 static int error_resilience = 2;
117 static int error_concealment = 3;
118 static int dct_algo = 0;
119 static int idct_algo = 0;
120 static int use_part = 0;
121 static int packet_size = 0;
123 static int gop_size = 12;
124 static int intra_only = 0;
125 static int audio_sample_rate = 44100;
126 static int audio_bit_rate = 64000;
127 static int audio_disable = 0;
128 static int audio_channels = 1;
129 static int audio_codec_id = CODEC_ID_NONE;
131 static INT64 recording_time = 0;
132 static int file_overwrite = 0;
133 static char *str_title = NULL;
134 static char *str_author = NULL;
135 static char *str_copyright = NULL;
136 static char *str_comment = NULL;
137 static int do_benchmark = 0;
138 static int do_hex_dump = 0;
139 static int do_play = 0;
140 static int do_psnr = 0;
141 static int do_vstats = 0;
142 static int do_pass = 0;
143 static char *pass_logfilename = NULL;
144 static int audio_stream_copy = 0;
145 static int video_stream_copy = 0;
147 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
149 #if !defined(CONFIG_AUDIO_OSS) && !defined(CONFIG_AUDIO_BEOS)
150 const char *audio_device = "none";
152 #ifndef CONFIG_VIDEO4LINUX
153 const char *v4l_device = "none";
156 typedef struct AVOutputStream {
157 int file_index; /* file index */
158 int index; /* stream index in the output file */
159 int source_index; /* AVInputStream index */
160 AVStream *st; /* stream in the output file */
161 int encoding_needed; /* true if encoding needed for this stream */
163 /* input pts and corresponding output pts
168 AVPicture pict_tmp; /* temporary image for resizing */
170 ImgReSampleContext *img_resample_ctx; /* for image resampling */
174 ReSampleContext *resample; /* for audio resampling */
175 FifoBuffer fifo; /* for compression: one audio fifo per codec */
179 typedef struct AVInputStream {
183 int discard; /* true if stream data should be discarded */
184 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
185 INT64 sample_index; /* current sample */
186 int frame_decoded; /* true if a video or audio frame has been decoded */
189 typedef struct AVInputFile {
190 int eof_reached; /* true if eof reached */
191 int ist_index; /* index of first stream in ist_table */
192 int buffer_size; /* current total buffer size */
193 int buffer_size_max; /* buffer size at which we consider we can stop
195 int nb_streams; /* nb streams we are aware of */
200 /* init terminal so that we can grab keys */
201 static struct termios oldtty;
203 static void term_exit(void)
205 tcsetattr (0, TCSANOW, &oldtty);
208 static void term_init(void)
215 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
216 |INLCR|IGNCR|ICRNL|IXON);
217 tty.c_oflag |= OPOST;
218 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
219 tty.c_cflag &= ~(CSIZE|PARENB);
224 tcsetattr (0, TCSANOW, &tty);
227 #ifdef CONFIG_BEOS_NETSERVER
228 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
232 /* read a key without blocking */
233 static int read_key(void)
237 #ifndef CONFIG_BEOS_NETSERVER
245 n = select(1, &rfds, NULL, NULL, &tv);
259 /* no interactive support */
260 static void term_exit(void)
264 static void term_init(void)
268 static int read_key(void)
275 int read_ffserver_streams(AVFormatContext *s, const char *filename)
280 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
283 /* copy stream format */
284 s->nb_streams = ic->nb_streams;
285 for(i=0;i<ic->nb_streams;i++) {
287 st = av_mallocz(sizeof(AVFormatContext));
288 memcpy(st, ic->streams[i], sizeof(AVStream));
292 av_close_input_file(ic);
296 #define MAX_AUDIO_PACKET_SIZE 16384
298 static void do_audio_out(AVFormatContext *s,
301 unsigned char *buf, int size)
304 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
305 UINT8 audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */
306 int size_out, frame_bytes, ret;
309 enc = &ost->st->codec;
311 if (ost->audio_resample) {
313 size_out = audio_resample(ost->resample,
314 (short *)buftmp, (short *)buf,
315 size / (ist->st->codec.channels * 2));
316 size_out = size_out * enc->channels * 2;
322 /* now encode as many frames as possible */
323 if (enc->frame_size > 1) {
324 /* output resampled raw samples */
325 fifo_write(&ost->fifo, buftmp, size_out,
328 frame_bytes = enc->frame_size * 2 * enc->channels;
330 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
331 &ost->fifo.rptr) == 0) {
332 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
334 av_write_frame(s, ost->index, audio_out, ret);
337 /* output a pcm frame */
338 /* XXX: change encoding codec API to avoid this ? */
339 switch(enc->codec->id) {
340 case CODEC_ID_PCM_S16LE:
341 case CODEC_ID_PCM_S16BE:
342 case CODEC_ID_PCM_U16LE:
343 case CODEC_ID_PCM_U16BE:
346 size_out = size_out >> 1;
349 ret = avcodec_encode_audio(enc, audio_out, size_out,
351 av_write_frame(s, ost->index, audio_out, ret);
355 /* write a picture to a raw mux */
356 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
357 int pix_fmt, int w, int h)
359 UINT8 *buf, *src, *dest;
362 /* XXX: not efficient, should add test if we can take
363 directly the AVPicture */
365 case PIX_FMT_YUV420P:
366 size = avpicture_get_size(pix_fmt, w, h);
367 buf = av_malloc(size);
376 src = picture->data[i];
378 memcpy(dest, src, w);
380 src += picture->linesize[i];
384 case PIX_FMT_YUV422P:
386 buf = av_malloc(size);
394 src = picture->data[i];
396 memcpy(dest, src, w);
398 src += picture->linesize[i];
402 case PIX_FMT_YUV444P:
404 buf = av_malloc(size);
409 src = picture->data[i];
411 memcpy(dest, src, w);
413 src += picture->linesize[i];
419 buf = av_malloc(size);
423 src = picture->data[0];
425 memcpy(dest, src, w * 2);
427 src += picture->linesize[0];
433 buf = av_malloc(size);
437 src = picture->data[0];
439 memcpy(dest, src, w * 3);
441 src += picture->linesize[0];
447 av_write_frame(s, index, buf, size);
451 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
455 AVPicture picture_tmp;
458 dec = &ist->st->codec;
460 /* deinterlace : must be done before any resize */
461 if (do_deinterlace) {
464 /* create temporary picture */
465 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
466 buf = av_malloc(size);
470 picture2 = &picture_tmp;
471 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
473 if (avpicture_deinterlace(picture2, picture,
474 dec->pix_fmt, dec->width, dec->height) < 0) {
475 /* if error, do not deinterlace */
484 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
486 if (picture != picture2)
487 *picture = *picture2;
491 /* we begin to correct av delay at this threshold */
492 #define AV_DELAY_MAX 0.100
494 static void do_video_out(AVFormatContext *s,
498 int *frame_size, AVOutputStream *audio_sync)
500 int nb_frames, i, ret;
501 AVPicture *picture, *pict;
502 AVPicture picture_tmp1;
503 static UINT8 *video_buffer;
504 UINT8 *buf = NULL, *buf1 = NULL;
505 AVCodecContext *enc, *dec;
507 #define VIDEO_BUFFER_SIZE (1024*1024)
509 enc = &ost->st->codec;
510 dec = &ist->st->codec;
512 /* by default, we output a single frame */
515 /* NOTE: the A/V sync is always done by considering the audio is
516 the master clock. It is suffisant for transcoding or playing,
517 but not for the general case */
519 /* compute the A-V delay and duplicate/remove frames if needed */
520 double adelta, vdelta, apts, vpts, av_delay;
522 if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
523 ost->sync_ipts != AV_NOPTS_VALUE) {
525 adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
526 s->pts_num / s->pts_den;
527 apts = audio_sync->sync_ipts + adelta;
529 vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
530 s->pts_num / s->pts_den;
531 vpts = ost->sync_ipts + vdelta;
533 av_delay = apts - vpts;
534 // printf("delay=%f\n", av_delay);
535 if (av_delay < -AV_DELAY_MAX)
537 else if (av_delay > AV_DELAY_MAX)
543 if (ost->sync_ipts != AV_NOPTS_VALUE) {
544 vdelta = (double)(ost->st->pts.val) * s->pts_num / s->pts_den - ost->sync_ipts;
545 if (vdelta < -AV_DELAY_MAX)
547 else if (vdelta > AV_DELAY_MAX)
549 //printf("vdelta=%f\n", vdelta);
556 video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
560 /* convert pixel format if needed */
561 if (enc->pix_fmt != dec->pix_fmt) {
564 /* create temporary picture */
565 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
566 buf = av_malloc(size);
569 pict = &picture_tmp1;
570 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
572 if (img_convert(pict, enc->pix_fmt,
573 picture1, dec->pix_fmt,
574 dec->width, dec->height) < 0) {
575 fprintf(stderr, "pixel format conversion not handled\n");
582 /* XXX: resampling could be done before raw format convertion in
583 some cases to go faster */
584 /* XXX: only works for YUV420P */
585 if (ost->video_resample) {
586 picture = &ost->pict_tmp;
587 img_resample(ost->img_resample_ctx, picture, pict);
591 /* duplicates frame if needed */
592 /* XXX: pb because no interleaving */
593 for(i=0;i<nb_frames;i++) {
594 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
595 /* handles sameq here. This is not correct because it may
596 not be a global option */
598 enc->quality = dec->quality;
601 ret = avcodec_encode_video(enc,
602 video_buffer, VIDEO_BUFFER_SIZE,
604 //enc->frame_number = enc->real_pict_num;
605 av_write_frame(s, ost->index, video_buffer, ret);
607 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
608 // enc->frame_number-1, enc->real_pict_num, ret,
610 /* if two pass, output log */
611 if (ost->logfile && enc->stats_out) {
612 fprintf(ost->logfile, "%s", enc->stats_out);
615 if (s->oformat->flags & AVFMT_RAWPICTURE) {
616 /* raw pictures are written as AVPicture structure to
617 avoid any copies. We support temorarily the older
619 av_write_frame(s, ost->index,
620 (UINT8 *)picture, sizeof(AVPicture));
622 write_picture(s, ost->index, picture, enc->pix_fmt,
623 enc->width, enc->height);
633 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
636 static FILE *fvstats=NULL;
637 static INT64 total_size = 0;
644 double ti1, bitrate, avg_bitrate;
648 today = localtime(&today2);
649 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
652 fvstats = fopen(filename,"w");
660 enc = &ost->st->codec;
661 total_size += frame_size;
662 if (enc->codec_type == CODEC_TYPE_VIDEO) {
663 frame_number = ost->frame_number;
664 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
666 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
668 fprintf(fvstats,"f_size= %6d ", frame_size);
669 /* compute pts value */
670 ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
674 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
675 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
676 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
677 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
678 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
682 void print_report(AVFormatContext **output_files,
683 AVOutputStream **ost_table, int nb_ostreams,
688 AVFormatContext *oc, *os;
691 int frame_number, vid, i;
692 double bitrate, ti1, pts;
693 static INT64 last_time = -1;
695 if (!is_last_report) {
697 /* display the report every 0.5 seconds */
698 cur_time = av_gettime();
699 if (last_time == -1) {
700 last_time = cur_time;
703 if ((cur_time - last_time) < 500000)
705 last_time = cur_time;
709 oc = output_files[0];
711 total_size = url_ftell(&oc->pb);
716 for(i=0;i<nb_ostreams;i++) {
718 os = output_files[ost->file_index];
719 enc = &ost->st->codec;
720 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
721 sprintf(buf + strlen(buf), "q=%2d ",
724 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
725 frame_number = ost->frame_number;
726 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
727 frame_number, enc->quality);
729 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
732 /* compute min output value */
733 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
734 if ((pts < ti1) && (pts > 0))
739 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
741 sprintf(buf + strlen(buf),
742 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
743 (double)total_size / 1024, ti1, bitrate);
745 fprintf(stderr, "%s ", buf);
747 if (is_last_report) {
748 fprintf(stderr, "\n");
750 fprintf(stderr, "\r");
756 * The following code is the main loop of the file converter
758 static int av_encode(AVFormatContext **output_files,
760 AVFormatContext **input_files,
762 AVStreamMap *stream_maps, int nb_stream_maps)
764 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
765 AVFormatContext *is, *os;
766 AVCodecContext *codec, *icodec;
767 AVOutputStream *ost, **ost_table = NULL;
768 AVInputStream *ist, **ist_table = NULL;
769 AVInputFile *file_table;
770 AVFormatContext *stream_no_data;
773 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
777 /* input stream init */
779 for(i=0;i<nb_input_files;i++) {
781 file_table[i].ist_index = j;
782 file_table[i].nb_streams = is->nb_streams;
787 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
791 for(i=0;i<nb_istreams;i++) {
792 ist = av_mallocz(sizeof(AVInputStream));
798 for(i=0;i<nb_input_files;i++) {
800 for(k=0;k<is->nb_streams;k++) {
801 ist = ist_table[j++];
802 ist->st = is->streams[k];
805 ist->discard = 1; /* the stream is discarded by default
810 /* output stream init */
812 for(i=0;i<nb_output_files;i++) {
813 os = output_files[i];
814 nb_ostreams += os->nb_streams;
816 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
817 fprintf(stderr, "Number of stream maps must match number of output streams\n");
821 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
824 for(i=0;i<nb_ostreams;i++) {
825 ost = av_mallocz(sizeof(AVOutputStream));
832 for(k=0;k<nb_output_files;k++) {
833 os = output_files[k];
834 for(i=0;i<os->nb_streams;i++) {
836 ost = ost_table[n++];
839 ost->st = os->streams[i];
840 if (nb_stream_maps > 0) {
841 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
842 stream_maps[n-1].stream_index;
844 /* get corresponding input stream index : we select the first one with the right type */
846 for(j=0;j<nb_istreams;j++) {
849 ist->st->codec.codec_type == ost->st->codec.codec_type) {
850 ost->source_index = j;
856 /* try again and reuse existing stream */
857 for(j=0;j<nb_istreams;j++) {
859 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
860 ost->source_index = j;
865 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
866 ost->file_index, ost->index);
871 ist = ist_table[ost->source_index];
876 /* for each output stream, we compute the right encoding parameters */
877 for(i=0;i<nb_ostreams;i++) {
879 ist = ist_table[ost->source_index];
881 codec = &ost->st->codec;
882 icodec = &ist->st->codec;
884 if (ost->st->stream_copy) {
885 /* if stream_copy is selected, no need to decode or encode */
886 codec->codec_id = icodec->codec_id;
887 codec->codec_type = icodec->codec_type;
888 codec->codec_tag = icodec->codec_tag;
889 codec->bit_rate = icodec->bit_rate;
890 switch(codec->codec_type) {
891 case CODEC_TYPE_AUDIO:
892 codec->sample_rate = icodec->sample_rate;
893 codec->channels = icodec->channels;
895 case CODEC_TYPE_VIDEO:
896 codec->frame_rate = icodec->frame_rate;
897 codec->width = icodec->width;
898 codec->height = icodec->height;
904 switch(codec->codec_type) {
905 case CODEC_TYPE_AUDIO:
906 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
909 if (codec->channels == icodec->channels &&
910 codec->sample_rate == icodec->sample_rate) {
911 ost->audio_resample = 0;
913 if (codec->channels != icodec->channels &&
914 icodec->codec_id == CODEC_ID_AC3) {
915 /* Special case for 5:1 AC3 input */
916 /* and mono or stereo output */
917 /* Request specific number of channels */
918 icodec->channels = codec->channels;
919 if (codec->sample_rate == icodec->sample_rate)
920 ost->audio_resample = 0;
922 ost->audio_resample = 1;
923 ost->resample = audio_resample_init(codec->channels, icodec->channels,
925 icodec->sample_rate);
927 /* Request specific number of channels */
928 icodec->channels = codec->channels;
930 ost->audio_resample = 1;
931 ost->resample = audio_resample_init(codec->channels, icodec->channels,
933 icodec->sample_rate);
936 ist->decoding_needed = 1;
937 ost->encoding_needed = 1;
939 case CODEC_TYPE_VIDEO:
940 if (codec->width == icodec->width &&
941 codec->height == icodec->height) {
942 ost->video_resample = 0;
945 ost->video_resample = 1;
946 buf = av_malloc((codec->width * codec->height * 3) / 2);
949 ost->pict_tmp.data[0] = buf;
950 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
951 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
952 ost->pict_tmp.linesize[0] = codec->width;
953 ost->pict_tmp.linesize[1] = codec->width / 2;
954 ost->pict_tmp.linesize[2] = codec->width / 2;
956 ost->img_resample_ctx = img_resample_full_init(
957 ost->st->codec.width, ost->st->codec.height,
958 ist->st->codec.width, ist->st->codec.height,
959 frame_topBand, frame_bottomBand,
960 frame_leftBand, frame_rightBand);
962 ost->encoding_needed = 1;
963 ist->decoding_needed = 1;
969 if (ost->encoding_needed &&
970 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
971 char logfilename[1024];
976 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
978 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
979 if (codec->flags & CODEC_FLAG_PASS1) {
980 f = fopen(logfilename, "w");
987 /* read the log file */
988 f = fopen(logfilename, "r");
993 fseek(f, 0, SEEK_END);
995 fseek(f, 0, SEEK_SET);
996 logbuffer = av_malloc(size + 1);
998 fprintf(stderr, "Could not allocate log buffer\n");
1001 fread(logbuffer, 1, size, f);
1003 logbuffer[size] = '\0';
1004 codec->stats_in = logbuffer;
1010 /* dump the file output parameters - cannot be done before in case
1012 for(i=0;i<nb_output_files;i++) {
1013 dump_format(output_files[i], i, output_files[i]->filename, 1);
1016 /* dump the stream mapping */
1017 fprintf(stderr, "Stream mapping:\n");
1018 for(i=0;i<nb_ostreams;i++) {
1020 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
1021 ist_table[ost->source_index]->file_index,
1022 ist_table[ost->source_index]->index,
1027 /* open each encoder */
1028 for(i=0;i<nb_ostreams;i++) {
1030 if (ost->encoding_needed) {
1032 codec = avcodec_find_encoder(ost->st->codec.codec_id);
1034 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1035 ost->file_index, ost->index);
1038 if (avcodec_open(&ost->st->codec, codec) < 0) {
1039 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1040 ost->file_index, ost->index);
1046 /* open each decoder */
1047 for(i=0;i<nb_istreams;i++) {
1049 if (ist->decoding_needed) {
1051 codec = avcodec_find_decoder(ist->st->codec.codec_id);
1053 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1054 ist->st->codec.codec_id, ist->file_index, ist->index);
1057 if (avcodec_open(&ist->st->codec, codec) < 0) {
1058 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1059 ist->file_index, ist->index);
1062 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1063 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1064 ist->frame_decoded = 1;
1069 for(i=0;i<nb_istreams;i++) {
1073 /* compute buffer size max (should use a complete heuristic) */
1074 for(i=0;i<nb_input_files;i++) {
1075 file_table[i].buffer_size_max = 2048;
1078 /* open files and write file headers */
1079 for(i=0;i<nb_output_files;i++) {
1080 os = output_files[i];
1081 if (av_write_header(os) < 0) {
1082 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
1088 #ifndef CONFIG_WIN32
1090 fprintf(stderr, "Press [q] to stop encoding\n");
1092 fprintf(stderr, "Press [q] to stop playing\n");
1101 int file_index, ist_index;
1106 int data_size, got_picture;
1108 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1109 void *buffer_to_free;
1113 /* if 'q' pressed, exits */
1115 /* read_key() returns 0 on EOF */
1121 /* select the stream that we must read now by looking at the
1122 smallest output pts */
1125 for(i=0;i<nb_ostreams;i++) {
1128 os = output_files[ost->file_index];
1129 ist = ist_table[ost->source_index];
1130 pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
1131 if (!file_table[ist->file_index].eof_reached &&
1134 file_index = ist->file_index;
1137 /* if none, if is finished */
1138 if (file_index < 0) {
1142 /* finish if recording time exhausted */
1143 if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
1146 /* read a packet from it and output it in the fifo */
1147 is = input_files[file_index];
1148 if (av_read_packet(is, &pkt) < 0) {
1149 file_table[file_index].eof_reached = 1;
1153 stream_no_data = is;
1157 /* the following test is needed in case new streams appear
1158 dynamically in stream : we ignore them */
1159 if (pkt.stream_index >= file_table[file_index].nb_streams)
1160 goto discard_packet;
1161 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1162 ist = ist_table[ist_index];
1164 goto discard_packet;
1167 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1168 av_hex_dump(pkt.data, pkt.size);
1171 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1179 ipts = AV_NOPTS_VALUE;
1181 /* decode the packet if needed */
1182 data_buf = NULL; /* fail safe */
1184 if (ist->decoding_needed) {
1185 /* NOTE1: we only take into account the PTS if a new
1186 frame has begun (MPEG semantics) */
1187 /* NOTE2: even if the fraction is not initialized,
1188 av_frac_set can be used to set the integer part */
1189 if (ist->frame_decoded &&
1190 pkt.pts != AV_NOPTS_VALUE &&
1193 ist->frame_decoded = 0;
1197 switch(ist->st->codec.codec_type) {
1198 case CODEC_TYPE_AUDIO:
1199 /* XXX: could avoid copy if PCM 16 bits with same
1200 endianness as CPU */
1201 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1205 /* Some bug in mpeg audio decoder gives */
1206 /* data_size < 0, it seems they are overflows */
1207 if (data_size <= 0) {
1208 /* no audio frame */
1213 data_buf = (UINT8 *)samples;
1215 case CODEC_TYPE_VIDEO:
1216 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1219 size = (ist->st->codec.width * ist->st->codec.height);
1220 avpicture_fill(&picture, ptr,
1221 ist->st->codec.pix_fmt,
1222 ist->st->codec.width,
1223 ist->st->codec.height);
1226 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1227 ret = avcodec_decode_video(&ist->st->codec,
1228 &picture, &got_picture, ptr, len);
1231 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1232 ist->file_index, ist->index);
1233 av_free_packet(&pkt);
1237 /* no picture yet */
1257 if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {
1258 pre_process_video_frame(ist, &picture, &buffer_to_free);
1261 ist->frame_decoded = 1;
1264 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1265 is the one of the next displayed one */
1266 /* XXX: add mpeg4 too ? */
1267 if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
1268 if (ist->st->codec.pict_type != B_TYPE) {
1270 tmp = ist->last_ip_pts;
1271 ist->last_ip_pts = ist->frac_pts.val;
1272 ist->frac_pts.val = tmp;
1276 /* transcode raw format, encode packets and output them */
1278 for(i=0;i<nb_ostreams;i++) {
1282 if (ost->source_index == ist_index) {
1283 os = output_files[ost->file_index];
1285 if (ipts != AV_NOPTS_VALUE) {
1287 printf("%d: got pts=%f %f\n",
1288 i, pkt.pts / 90000.0,
1289 (ipts - ost->st->pts.val) / 90000.0);
1291 /* set the input output pts pairs */
1292 ost->sync_ipts = (double)ipts * is->pts_num /
1294 /* XXX: take into account the various fifos,
1295 in particular for audio */
1296 ost->sync_opts = ost->st->pts.val;
1297 //printf("ipts=%lld sync_ipts=%f sync_opts=%lld pts.val=%lld pkt.pts=%lld\n", ipts, ost->sync_ipts, ost->sync_opts, ost->st->pts.val, pkt.pts);
1299 //printf("pts.val=%lld\n", ost->st->pts.val);
1302 if (ost->encoding_needed) {
1303 switch(ost->st->codec.codec_type) {
1304 case CODEC_TYPE_AUDIO:
1305 do_audio_out(os, ost, ist, data_buf, data_size);
1307 case CODEC_TYPE_VIDEO:
1308 /* find an audio stream for synchro */
1311 AVOutputStream *audio_sync, *ost1;
1313 for(i=0;i<nb_ostreams;i++) {
1314 ost1 = ost_table[i];
1315 if (ost1->file_index == ost->file_index &&
1316 ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
1322 do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
1324 do_video_stats(os, ost, frame_size);
1331 /* no reencoding needed : output the packet directly */
1332 /* force the input stream PTS */
1333 av_write_frame(os, ost->index, data_buf, data_size);
1334 ost->st->codec.frame_number++;
1335 ost->frame_number++;
1339 av_free(buffer_to_free);
1340 ipts = AV_NOPTS_VALUE;
1343 av_free_packet(&pkt);
1345 /* dump report by using the output first video and audio streams */
1346 print_report(output_files, ost_table, nb_ostreams, 0);
1350 /* dump report by using the first video and audio streams */
1351 print_report(output_files, ost_table, nb_ostreams, 1);
1353 /* close each encoder */
1354 for(i=0;i<nb_ostreams;i++) {
1356 if (ost->encoding_needed) {
1357 av_freep(&ost->st->codec.stats_in);
1358 avcodec_close(&ost->st->codec);
1362 /* close each decoder */
1363 for(i=0;i<nb_istreams;i++) {
1365 if (ist->decoding_needed) {
1366 avcodec_close(&ist->st->codec);
1371 /* write the trailer if needed and close file */
1372 for(i=0;i<nb_output_files;i++) {
1373 os = output_files[i];
1374 av_write_trailer(os);
1380 av_free(file_table);
1383 for(i=0;i<nb_istreams;i++) {
1390 for(i=0;i<nb_ostreams;i++) {
1394 fclose(ost->logfile);
1395 ost->logfile = NULL;
1397 fifo_free(&ost->fifo); /* works even if fifo is not
1398 initialized but set to zero */
1399 av_free(ost->pict_tmp.data[0]);
1400 if (ost->video_resample)
1401 img_resample_close(ost->img_resample_ctx);
1402 if (ost->audio_resample)
1403 audio_resample_close(ost->resample);
1416 int file_read(const char *filename)
1419 unsigned char buffer[1024];
1422 if (url_open(&h, filename, O_RDONLY) < 0) {
1423 printf("could not open '%s'\n", filename);
1427 len = url_read(h, buffer, sizeof(buffer));
1430 for(i=0;i<len;i++) putchar(buffer[i]);
1437 void show_licence(void)
1440 "ffmpeg version " FFMPEG_VERSION "\n"
1441 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1442 "This library is free software; you can redistribute it and/or\n"
1443 "modify it under the terms of the GNU Lesser General Public\n"
1444 "License as published by the Free Software Foundation; either\n"
1445 "version 2 of the License, or (at your option) any later version.\n"
1447 "This library is distributed in the hope that it will be useful,\n"
1448 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1449 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1450 "Lesser General Public License for more details.\n"
1452 "You should have received a copy of the GNU Lesser General Public\n"
1453 "License along with this library; if not, write to the Free Software\n"
1454 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1459 void opt_format(const char *arg)
1461 file_iformat = av_find_input_format(arg);
1462 file_oformat = guess_format(arg, NULL, NULL);
1463 if (!file_iformat && !file_oformat) {
1464 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1469 void opt_video_bitrate(const char *arg)
1471 video_bit_rate = atoi(arg) * 1000;
1474 void opt_video_bitrate_tolerance(const char *arg)
1476 video_bit_rate_tolerance = atoi(arg) * 1000;
1479 void opt_video_bitrate_max(const char *arg)
1481 video_rc_max_rate = atoi(arg) * 1000;
1484 void opt_video_bitrate_min(const char *arg)
1486 video_rc_min_rate = atoi(arg) * 1000;
1489 void opt_video_buffer_size(const char *arg)
1491 video_rc_buffer_size = atoi(arg) * 1000;
1494 void opt_video_rc_eq(char *arg)
1499 void opt_video_rc_override_string(char *arg)
1501 video_rc_override_string = arg;
1505 void opt_workaround_bugs(const char *arg)
1507 workaround_bugs = atoi(arg);
1510 void opt_dct_algo(const char *arg)
1512 dct_algo = atoi(arg);
1515 void opt_idct_algo(const char *arg)
1517 idct_algo = atoi(arg);
1521 void opt_error_resilience(const char *arg)
1523 error_resilience = atoi(arg);
1526 void opt_error_concealment(const char *arg)
1528 error_concealment = atoi(arg);
1532 void opt_frame_rate(const char *arg)
1534 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1538 void opt_frame_crop_top(const char *arg)
1540 frame_topBand = atoi(arg);
1541 if (frame_topBand < 0) {
1542 fprintf(stderr, "Incorrect top crop size\n");
1545 if ((frame_topBand % 2) != 0) {
1546 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1549 if ((frame_topBand) >= frame_height){
1550 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1553 frame_height -= frame_topBand;
1556 void opt_frame_crop_bottom(const char *arg)
1558 frame_bottomBand = atoi(arg);
1559 if (frame_bottomBand < 0) {
1560 fprintf(stderr, "Incorrect bottom crop size\n");
1563 if ((frame_bottomBand % 2) != 0) {
1564 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1567 if ((frame_bottomBand) >= frame_height){
1568 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1571 frame_height -= frame_bottomBand;
1574 void opt_frame_crop_left(const char *arg)
1576 frame_leftBand = atoi(arg);
1577 if (frame_leftBand < 0) {
1578 fprintf(stderr, "Incorrect left crop size\n");
1581 if ((frame_leftBand % 2) != 0) {
1582 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1585 if ((frame_leftBand) >= frame_width){
1586 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1589 frame_width -= frame_leftBand;
1592 void opt_frame_crop_right(const char *arg)
1594 frame_rightBand = atoi(arg);
1595 if (frame_rightBand < 0) {
1596 fprintf(stderr, "Incorrect right crop size\n");
1599 if ((frame_rightBand % 2) != 0) {
1600 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1603 if ((frame_rightBand) >= frame_width){
1604 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1607 frame_width -= frame_rightBand;
1610 void opt_frame_size(const char *arg)
1612 parse_image_size(&frame_width, &frame_height, arg);
1613 if (frame_width <= 0 || frame_height <= 0) {
1614 fprintf(stderr, "Incorrect frame size\n");
1617 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1618 fprintf(stderr, "Frame size must be a multiple of 2\n");
1623 void opt_gop_size(const char *arg)
1625 gop_size = atoi(arg);
1628 void opt_b_frames(const char *arg)
1630 b_frames = atoi(arg);
1631 if (b_frames > FF_MAX_B_FRAMES) {
1632 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1634 } else if (b_frames < 1) {
1635 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1640 void opt_qscale(const char *arg)
1642 video_qscale = atoi(arg);
1643 if (video_qscale < 0 ||
1644 video_qscale > 31) {
1645 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1650 void opt_qmin(const char *arg)
1652 video_qmin = atoi(arg);
1653 if (video_qmin < 0 ||
1655 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1660 void opt_qmax(const char *arg)
1662 video_qmax = atoi(arg);
1663 if (video_qmax < 0 ||
1665 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1670 void opt_qdiff(const char *arg)
1672 video_qdiff = atoi(arg);
1673 if (video_qdiff < 0 ||
1675 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1680 void opt_qblur(const char *arg)
1682 video_qblur = atof(arg);
1685 void opt_qcomp(const char *arg)
1687 video_qcomp = atof(arg);
1690 void opt_rc_initial_cplx(const char *arg)
1692 video_rc_initial_cplx = atof(arg);
1694 void opt_b_qfactor(const char *arg)
1696 video_b_qfactor = atof(arg);
1698 void opt_i_qfactor(const char *arg)
1700 video_i_qfactor = atof(arg);
1702 void opt_b_qoffset(const char *arg)
1704 video_b_qoffset = atof(arg);
1706 void opt_i_qoffset(const char *arg)
1708 video_i_qoffset = atof(arg);
1711 void opt_packet_size(const char *arg)
1713 packet_size= atoi(arg);
1716 void opt_audio_bitrate(const char *arg)
1718 audio_bit_rate = atoi(arg) * 1000;
1721 void opt_audio_rate(const char *arg)
1723 audio_sample_rate = atoi(arg);
1726 void opt_audio_channels(const char *arg)
1728 audio_channels = atoi(arg);
1731 void opt_video_device(const char *arg)
1733 v4l_device = strdup(arg);
1736 void opt_audio_device(const char *arg)
1738 audio_device = strdup(arg);
1741 void opt_audio_codec(const char *arg)
1745 if (!strcmp(arg, "copy")) {
1746 audio_stream_copy = 1;
1750 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1755 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1758 audio_codec_id = p->id;
1763 void add_frame_hooker(const char *arg)
1768 char *args = strdup(arg);
1770 argv[0] = strtok(args, " ");
1771 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
1774 i = frame_hook_add(argc, argv);
1777 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
1782 const char *motion_str[] = {
1792 void opt_motion_estimation(const char *arg)
1798 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1801 if (!strcmp(*p, arg))
1805 me_method = (p - motion_str) + 1;
1808 void opt_video_codec(const char *arg)
1812 if (!strcmp(arg, "copy")) {
1813 video_stream_copy = 1;
1817 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1822 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1825 video_codec_id = p->id;
1830 void opt_map(const char *arg)
1836 m = &stream_maps[nb_stream_maps++];
1838 m->file_index = strtol(arg, (char **)&p, 0);
1842 m->stream_index = strtol(p, (char **)&p, 0);
1845 void opt_recording_time(const char *arg)
1847 recording_time = parse_date(arg, 1);
1850 void print_error(const char *filename, int err)
1853 case AVERROR_NUMEXPECTED:
1854 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1855 "Use '%%d' to specify the image number:\n"
1856 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1857 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1860 case AVERROR_INVALIDDATA:
1861 fprintf(stderr, "%s: Error while parsing header\n", filename);
1864 fprintf(stderr, "%s: Unknown format\n", filename);
1867 fprintf(stderr, "%s: Error while opening file\n", filename);
1872 void opt_input_file(const char *filename)
1874 AVFormatContext *ic;
1875 AVFormatParameters params, *ap = ¶ms;
1876 int err, i, ret, rfps;
1878 if (!strcmp(filename, "-"))
1881 /* get default parameters from command line */
1882 memset(ap, 0, sizeof(*ap));
1883 ap->sample_rate = audio_sample_rate;
1884 ap->channels = audio_channels;
1885 ap->frame_rate = frame_rate;
1886 ap->width = frame_width;
1887 ap->height = frame_height;
1889 /* open the input file with generic libav function */
1890 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1892 print_error(filename, err);
1896 /* If not enough info to get the stream parameters, we decode the
1897 first frames to get it. (used in mpeg case for example) */
1898 ret = av_find_stream_info(ic);
1900 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1904 /* update the current parameters so that they match the one of the input stream */
1905 for(i=0;i<ic->nb_streams;i++) {
1906 AVCodecContext *enc = &ic->streams[i]->codec;
1907 switch(enc->codec_type) {
1908 case CODEC_TYPE_AUDIO:
1909 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1910 audio_channels = enc->channels;
1911 audio_sample_rate = enc->sample_rate;
1913 case CODEC_TYPE_VIDEO:
1914 frame_height = enc->height;
1915 frame_width = enc->width;
1916 rfps = ic->streams[i]->r_frame_rate;
1917 enc->workaround_bugs = workaround_bugs;
1918 enc->error_resilience = error_resilience;
1919 enc->error_concealment = error_concealment;
1920 enc->idct_algo= idct_algo;
1921 /* if(enc->codec->capabilities & CODEC_CAP_TRUNCATED)
1922 enc->flags|= CODEC_FLAG_TRUNCATED; */
1923 if(/*enc->codec_id==CODEC_ID_MPEG4 || */enc->codec_id==CODEC_ID_MPEG1VIDEO)
1924 enc->flags|= CODEC_FLAG_TRUNCATED;
1926 if (enc->frame_rate != rfps) {
1927 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1928 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1929 (float)rfps / FRAME_RATE_BASE);
1931 /* update the current frame rate to match the stream frame rate */
1939 input_files[nb_input_files] = ic;
1940 /* dump the file content */
1941 dump_format(ic, nb_input_files, filename, 0);
1943 file_iformat = NULL;
1944 file_oformat = NULL;
1947 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1949 int has_video, has_audio, i, j;
1950 AVFormatContext *ic;
1954 for(j=0;j<nb_input_files;j++) {
1955 ic = input_files[j];
1956 for(i=0;i<ic->nb_streams;i++) {
1957 AVCodecContext *enc = &ic->streams[i]->codec;
1958 switch(enc->codec_type) {
1959 case CODEC_TYPE_AUDIO:
1962 case CODEC_TYPE_VIDEO:
1970 *has_video_ptr = has_video;
1971 *has_audio_ptr = has_audio;
1974 void opt_output_file(const char *filename)
1977 AVFormatContext *oc;
1978 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1981 if (!strcmp(filename, "-"))
1984 oc = av_mallocz(sizeof(AVFormatContext));
1986 if (!file_oformat) {
1987 file_oformat = guess_format(NULL, filename, NULL);
1988 if (!file_oformat) {
1989 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1995 oc->oformat = file_oformat;
1997 if (!strcmp(file_oformat->name, "ffm") &&
1998 strstart(filename, "http:", NULL)) {
1999 /* special case for files sent to ffserver: we get the stream
2000 parameters from ffserver */
2001 if (read_ffserver_streams(oc, filename) < 0) {
2002 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
2006 use_video = file_oformat->video_codec != CODEC_ID_NONE;
2007 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
2009 /* disable if no corresponding type found and at least one
2011 if (nb_input_files > 0) {
2012 check_audio_video_inputs(&input_has_video, &input_has_audio);
2013 if (!input_has_video)
2015 if (!input_has_audio)
2019 /* manual disable */
2020 if (audio_disable) {
2023 if (video_disable) {
2029 AVCodecContext *video_enc;
2031 st = av_mallocz(sizeof(AVStream));
2033 fprintf(stderr, "Could not alloc stream\n");
2037 video_enc = &st->codec;
2038 if (video_stream_copy) {
2039 st->stream_copy = 1;
2040 video_enc->codec_type = CODEC_TYPE_VIDEO;
2045 codec_id = file_oformat->video_codec;
2046 if (video_codec_id != CODEC_ID_NONE)
2047 codec_id = video_codec_id;
2049 video_enc->codec_id = codec_id;
2051 video_enc->bit_rate = video_bit_rate;
2052 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
2053 video_enc->frame_rate = frame_rate;
2055 video_enc->width = frame_width;
2056 video_enc->height = frame_height;
2059 video_enc->gop_size = gop_size;
2061 video_enc->gop_size = 0;
2062 if (video_qscale || same_quality) {
2063 video_enc->flags |= CODEC_FLAG_QSCALE;
2064 video_enc->quality = video_qscale;
2068 video_enc->flags |= CODEC_FLAG_HQ;
2072 video_enc->flags |= CODEC_FLAG_HQ;
2073 video_enc->flags |= CODEC_FLAG_4MV;
2077 video_enc->flags |= CODEC_FLAG_PART;
2081 if (codec_id != CODEC_ID_MPEG4) {
2082 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
2085 video_enc->max_b_frames = b_frames;
2086 video_enc->b_frame_strategy = 0;
2087 video_enc->b_quant_factor = 2.0;
2090 video_enc->qmin = video_qmin;
2091 video_enc->qmax = video_qmax;
2092 video_enc->max_qdiff = video_qdiff;
2093 video_enc->qblur = video_qblur;
2094 video_enc->qcompress = video_qcomp;
2095 video_enc->rc_eq = video_rc_eq;
2097 p= video_rc_override_string;
2100 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
2102 fprintf(stderr, "error parsing rc_override\n");
2105 video_enc->rc_override=
2106 realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
2107 video_enc->rc_override[i].start_frame= start;
2108 video_enc->rc_override[i].end_frame = end;
2110 video_enc->rc_override[i].qscale= q;
2111 video_enc->rc_override[i].quality_factor= 1.0;
2114 video_enc->rc_override[i].qscale= 0;
2115 video_enc->rc_override[i].quality_factor= -q/100.0;
2120 video_enc->rc_override_count=i;
2122 video_enc->rc_max_rate = video_rc_max_rate;
2123 video_enc->rc_min_rate = video_rc_min_rate;
2124 video_enc->rc_buffer_size = video_rc_buffer_size;
2125 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
2126 video_enc->rc_initial_cplx= video_rc_initial_cplx;
2127 video_enc->i_quant_factor = video_i_qfactor;
2128 video_enc->b_quant_factor = video_b_qfactor;
2129 video_enc->i_quant_offset = video_i_qoffset;
2130 video_enc->b_quant_offset = video_b_qoffset;
2131 video_enc->dct_algo = dct_algo;
2132 video_enc->idct_algo = idct_algo;
2134 video_enc->rtp_mode= 1;
2135 video_enc->rtp_payload_size= packet_size;
2139 video_enc->get_psnr = 1;
2141 video_enc->get_psnr = 0;
2143 video_enc->me_method = me_method;
2148 video_enc->flags |= CODEC_FLAG_PASS1;
2150 video_enc->flags |= CODEC_FLAG_PASS2;
2154 /* XXX: need to find a way to set codec parameters */
2155 if (oc->oformat->flags & AVFMT_RGB24) {
2156 video_enc->pix_fmt = PIX_FMT_RGB24;
2159 oc->streams[nb_streams] = st;
2164 AVCodecContext *audio_enc;
2166 st = av_mallocz(sizeof(AVStream));
2168 fprintf(stderr, "Could not alloc stream\n");
2172 audio_enc = &st->codec;
2173 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2174 if (audio_stream_copy) {
2175 st->stream_copy = 1;
2177 codec_id = file_oformat->audio_codec;
2178 if (audio_codec_id != CODEC_ID_NONE)
2179 codec_id = audio_codec_id;
2180 audio_enc->codec_id = codec_id;
2182 audio_enc->bit_rate = audio_bit_rate;
2183 audio_enc->sample_rate = audio_sample_rate;
2184 /* For audio codecs other than AC3 we limit */
2185 /* the number of coded channels to stereo */
2186 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2187 audio_enc->channels = 2;
2189 audio_enc->channels = audio_channels;
2191 oc->streams[nb_streams] = st;
2195 oc->nb_streams = nb_streams;
2198 fprintf(stderr, "No audio or video streams available\n");
2203 pstrcpy(oc->title, sizeof(oc->title), str_title);
2205 pstrcpy(oc->author, sizeof(oc->author), str_author);
2207 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2209 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2212 output_files[nb_output_files++] = oc;
2214 strcpy(oc->filename, filename);
2216 /* check filename in case of an image number is expected */
2217 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2218 if (filename_number_test(oc->filename) < 0) {
2219 print_error(oc->filename, AVERROR_NUMEXPECTED);
2224 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2225 /* test if it already exists to avoid loosing precious files */
2226 if (!file_overwrite &&
2227 (strchr(filename, ':') == NULL ||
2228 strstart(filename, "file:", NULL))) {
2229 if (url_exist(filename)) {
2232 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2235 if (toupper(c) != 'Y') {
2236 fprintf(stderr, "Not overwriting - exiting\n");
2243 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2244 fprintf(stderr, "Could not open '%s'\n", filename);
2249 /* reset some options */
2250 file_oformat = NULL;
2251 file_iformat = NULL;
2254 audio_codec_id = CODEC_ID_NONE;
2255 video_codec_id = CODEC_ID_NONE;
2256 audio_stream_copy = 0;
2257 video_stream_copy = 0;
2260 /* prepare dummy protocols for grab */
2261 void prepare_grab(void)
2263 int has_video, has_audio, i, j;
2264 AVFormatContext *oc;
2265 AVFormatContext *ic;
2266 AVFormatParameters ap1, *ap = &ap1;
2268 /* see if audio/video inputs are needed */
2271 memset(ap, 0, sizeof(*ap));
2272 for(j=0;j<nb_output_files;j++) {
2273 oc = output_files[j];
2274 for(i=0;i<oc->nb_streams;i++) {
2275 AVCodecContext *enc = &oc->streams[i]->codec;
2276 switch(enc->codec_type) {
2277 case CODEC_TYPE_AUDIO:
2278 if (enc->sample_rate > ap->sample_rate)
2279 ap->sample_rate = enc->sample_rate;
2280 if (enc->channels > ap->channels)
2281 ap->channels = enc->channels;
2284 case CODEC_TYPE_VIDEO:
2285 if (enc->width > ap->width)
2286 ap->width = enc->width;
2287 if (enc->height > ap->height)
2288 ap->height = enc->height;
2289 if (enc->frame_rate > ap->frame_rate)
2290 ap->frame_rate = enc->frame_rate;
2299 if (has_video == 0 && has_audio == 0) {
2300 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2305 AVInputFormat *fmt1;
2306 fmt1 = av_find_input_format("video_grab_device");
2307 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2308 fprintf(stderr, "Could not find video grab device\n");
2311 /* by now video grab has one stream */
2312 ic->streams[0]->r_frame_rate = ap->frame_rate;
2313 input_files[nb_input_files] = ic;
2314 dump_format(ic, nb_input_files, v4l_device, 0);
2318 AVInputFormat *fmt1;
2319 fmt1 = av_find_input_format("audio_device");
2320 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2321 fprintf(stderr, "Could not find audio grab device\n");
2324 input_files[nb_input_files] = ic;
2325 dump_format(ic, nb_input_files, audio_device, 0);
2330 /* open the necessary output devices for playing */
2331 void prepare_play(void)
2333 file_iformat = NULL;
2334 file_oformat = guess_format("audio_device", NULL, NULL);
2335 if (!file_oformat) {
2336 fprintf(stderr, "Could not find audio device\n");
2340 opt_output_file(audio_device);
2343 /* same option as mencoder */
2344 void opt_pass(const char *pass_str)
2347 pass = atoi(pass_str);
2348 if (pass != 1 && pass != 2) {
2349 fprintf(stderr, "pass number can be only 1 or 2\n");
2355 #ifndef CONFIG_WIN32
2356 INT64 getutime(void)
2358 struct rusage rusage;
2360 getrusage(RUSAGE_SELF, &rusage);
2361 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2364 INT64 getutime(void)
2366 return av_gettime();
2370 extern int ffm_nopts;
2372 void opt_bitexact(void)
2374 avcodec_set_bit_exact();
2375 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2379 void show_formats(void)
2381 AVInputFormat *ifmt;
2382 AVOutputFormat *ofmt;
2387 printf("File formats:\n");
2388 printf(" Encoding:");
2389 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2390 printf(" %s", ofmt->name);
2393 printf(" Decoding:");
2394 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2395 printf(" %s", ifmt->name);
2399 printf("Codecs:\n");
2400 printf(" Encoders:");
2401 for(p = first_avcodec; p != NULL; p = p->next) {
2403 printf(" %s", p->name);
2407 printf(" Decoders:");
2408 for(p = first_avcodec; p != NULL; p = p->next) {
2410 printf(" %s", p->name);
2414 printf("Supported file protocols:");
2415 for(up = first_protocol; up != NULL; up = up->next)
2416 printf(" %s:", up->name);
2419 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2420 printf("Motion estimation methods:");
2424 if ((pp - motion_str + 1) == ME_ZERO)
2425 printf("(fastest)");
2426 else if ((pp - motion_str + 1) == ME_FULL)
2427 printf("(slowest)");
2428 else if ((pp - motion_str + 1) == ME_EPZS)
2429 printf("(default)");
2436 void show_help(void)
2439 const OptionDef *po;
2442 prog = do_play ? "ffplay" : "ffmpeg";
2444 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2448 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2449 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2451 printf("usage: ffplay [options] input_file...\n"
2452 "Simple audio player\n");
2456 "Main options are:\n");
2459 printf("\nAdvanced options are:\n");
2460 for(po = options; po->name != NULL; po++) {
2462 expert = (po->flags & OPT_EXPERT) != 0;
2464 strcpy(buf, po->name);
2465 if (po->flags & HAS_ARG) {
2467 strcat(buf, po->argname);
2469 printf("-%-17s %s\n", buf, po->help);
2477 const OptionDef options[] = {
2478 { "L", 0, {(void*)show_licence}, "show license" },
2479 { "h", 0, {(void*)show_help}, "show help" },
2480 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2481 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2482 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2483 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2484 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2485 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2486 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2487 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2488 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2489 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2490 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2491 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2493 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2494 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2495 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2496 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2497 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2498 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2499 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2500 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2501 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2502 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2503 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2504 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2505 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2506 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2507 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2508 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2509 { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
2510 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2511 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2512 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2513 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2514 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2515 { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
2516 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2517 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2518 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2519 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2520 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2521 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
2522 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2524 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2525 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2526 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2527 { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
2528 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2529 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2530 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2531 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2532 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2533 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2534 { "sameq", OPT_BOOL, {(void*)&same_quality},
2535 "use same video quality as source (implies VBR)" },
2537 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2538 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2539 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2540 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2541 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2542 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
2543 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2544 "deinterlace pictures" },
2545 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2546 "add timings for benchmarking" },
2547 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2548 "dump each input packet" },
2549 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2550 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2551 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2552 { "vhook", HAS_ARG | OPT_EXPERT, {(void*)add_frame_hooker}, "insert video processing module", "module name and parameters" },
2556 int main(int argc, char **argv)
2559 const char *opt, *arg;
2560 const OptionDef *po;
2565 /* detect if invoked as player */
2566 i = strlen(argv[0]);
2567 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2575 while (optindex < argc) {
2576 opt = argv[optindex++];
2578 if (opt[0] == '-' && opt[1] != '\0') {
2580 while (po->name != NULL) {
2581 if (!strcmp(opt + 1, po->name))
2586 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2590 if (po->flags & HAS_ARG) {
2591 arg = argv[optindex++];
2593 fprintf(stderr, "%s: missing argument for option '%s'\n", argv[0], opt);
2597 if (po->flags & OPT_STRING) {
2600 *po->u.str_arg = str;
2601 } else if (po->flags & OPT_BOOL) {
2604 po->u.func_arg(arg);
2608 opt_output_file(opt);
2610 opt_input_file(opt);
2617 /* file converter / grab */
2618 if (nb_output_files <= 0) {
2619 fprintf(stderr, "Must supply at least one output file\n");
2623 if (nb_input_files == 0) {
2628 if (nb_input_files <= 0) {
2629 fprintf(stderr, "Must supply at least one input file\n");
2636 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2637 stream_maps, nb_stream_maps);
2638 ti = getutime() - ti;
2640 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2644 for(i=0;i<nb_output_files;i++) {
2645 /* maybe av_close_output_file ??? */
2646 AVFormatContext *s = output_files[i];
2648 if (!(s->oformat->flags & AVFMT_NOFILE))
2650 for(j=0;j<s->nb_streams;j++)
2651 av_free(s->streams[j]);
2654 for(i=0;i<nb_input_files;i++)
2655 av_close_input_file(input_files[i]);