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
26 #include <sys/ioctl.h>
29 #include <sys/resource.h>
39 #define MAXINT64 INT64_C(0x7fffffffffffffff)
44 #define HAS_ARG 0x0001
45 #define OPT_BOOL 0x0002
46 #define OPT_EXPERT 0x0004
47 #define OPT_STRING 0x0008
57 /* select an input stream for an output stream */
58 typedef struct AVStreamMap {
63 extern const OptionDef options[];
69 static AVFormatContext *input_files[MAX_FILES];
70 static int nb_input_files = 0;
72 static AVFormatContext *output_files[MAX_FILES];
73 static int nb_output_files = 0;
75 static AVStreamMap stream_maps[MAX_FILES];
76 static int nb_stream_maps;
78 static AVInputFormat *file_iformat;
79 static AVOutputFormat *file_oformat;
80 static int frame_width = 160;
81 static int frame_height = 128;
82 static int frame_topBand = 0;
83 static int frame_bottomBand = 0;
84 static int frame_leftBand = 0;
85 static int frame_rightBand = 0;
86 static int frame_rate = 25 * FRAME_RATE_BASE;
87 static int video_bit_rate = 200*1000;
88 static int video_bit_rate_tolerance = 4000*1000;
89 static int video_qscale = 0;
90 static int video_qmin = 2;
91 static int video_qmax = 31;
92 static int video_qdiff = 3;
93 static float video_qblur = 0.5;
94 static float video_qcomp = 0.5;
95 static float video_rc_qsquish=1.0;
96 static float video_rc_qmod_amp=0;
97 static int video_rc_qmod_freq=0;
98 static char *video_rc_override_string=NULL;
99 static char *video_rc_eq="tex^qComp";
100 static int video_rc_buffer_size=0;
101 static float video_rc_buffer_aggressivity=1.0;
102 static int video_rc_max_rate=0;
103 static int video_rc_min_rate=0;
104 static float video_rc_initial_cplx=0;
105 static float video_b_qfactor = 1.25;
106 static float video_b_qoffset = 1.25;
107 static float video_i_qfactor = -0.8;
108 static float video_i_qoffset = 0.0;
109 static int me_method = 0;
110 static int video_disable = 0;
111 static int video_codec_id = CODEC_ID_NONE;
112 static int same_quality = 0;
113 static int b_frames = 0;
114 static int use_hq = 0;
115 static int use_4mv = 0;
116 static int do_deinterlace = 0;
117 static int workaround_bugs = 0;
118 static int error_resilience = 0;
119 static int dct_algo = 0;
121 static int gop_size = 12;
122 static int intra_only = 0;
123 static int audio_sample_rate = 44100;
124 static int audio_bit_rate = 64000;
125 static int audio_disable = 0;
126 static int audio_channels = 1;
127 static int audio_codec_id = CODEC_ID_NONE;
129 static INT64 recording_time = 0;
130 static int file_overwrite = 0;
131 static char *str_title = NULL;
132 static char *str_author = NULL;
133 static char *str_copyright = NULL;
134 static char *str_comment = NULL;
135 static int do_benchmark = 0;
136 static int do_hex_dump = 0;
137 static int do_play = 0;
138 static int do_psnr = 0;
139 static int do_vstats = 0;
140 static int mpeg_vcd = 0;
142 #ifndef CONFIG_AUDIO_OSS
143 const char *audio_device = "none";
145 #ifndef CONFIG_VIDEO4LINUX
146 const char *v4l_device = "none";
149 typedef struct AVOutputStream {
150 int file_index; /* file index */
151 int index; /* stream index in the output file */
152 int source_index; /* AVInputStream index */
153 AVStream *st; /* stream in the output file */
154 int encoding_needed; /* true if encoding needed for this stream */
157 AVPicture pict_tmp; /* temporary image for resizing */
159 ImgReSampleContext *img_resample_ctx; /* for image resampling */
163 ReSampleContext *resample; /* for audio resampling */
164 FifoBuffer fifo; /* for compression: one audio fifo per codec */
167 typedef struct AVInputStream {
171 int discard; /* true if stream data should be discarded */
172 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
173 Ticker pts_ticker; /* Ticker for PTS calculation */
174 int ticker_inited; /* to signal if the ticker was initialized */
175 INT64 pts; /* current pts */
176 int pts_increment; /* expected pts increment for next packet */
177 int frame_number; /* current frame */
178 INT64 sample_index; /* current sample */
181 typedef struct AVInputFile {
182 int eof_reached; /* true if eof reached */
183 int ist_index; /* index of first stream in ist_table */
184 int buffer_size; /* current total buffer size */
185 int buffer_size_max; /* buffer size at which we consider we can stop
187 int nb_streams; /* nb streams we are aware of */
192 /* init terminal so that we can grab keys */
193 static struct termios oldtty;
195 static void term_exit(void)
197 tcsetattr (0, TCSANOW, &oldtty);
200 static void term_init(void)
207 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
208 |INLCR|IGNCR|ICRNL|IXON);
209 tty.c_oflag |= OPOST;
210 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
211 tty.c_cflag &= ~(CSIZE|PARENB);
216 tcsetattr (0, TCSANOW, &tty);
221 /* read a key without blocking */
222 static int read_key(void)
233 n = select(1, &rfds, NULL, NULL, &tv);
246 /* no interactive support */
247 static void term_exit(void)
251 static void term_init(void)
255 static int read_key(void)
262 int read_ffserver_streams(AVFormatContext *s, const char *filename)
267 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
270 /* copy stream format */
271 s->nb_streams = ic->nb_streams;
272 for(i=0;i<ic->nb_streams;i++) {
274 st = av_mallocz(sizeof(AVFormatContext));
275 memcpy(st, ic->streams[i], sizeof(AVStream));
279 av_close_input_file(ic);
283 #define MAX_AUDIO_PACKET_SIZE 16384
285 static void do_audio_out(AVFormatContext *s,
288 unsigned char *buf, int size)
291 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
292 UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
293 int size_out, frame_bytes, ret;
296 enc = &ost->st->codec;
298 if (ost->audio_resample) {
300 size_out = audio_resample(ost->resample,
301 (short *)buftmp, (short *)buf,
302 size / (ist->st->codec.channels * 2));
303 size_out = size_out * enc->channels * 2;
309 /* now encode as many frames as possible */
310 if (enc->frame_size > 1) {
311 /* output resampled raw samples */
312 fifo_write(&ost->fifo, buftmp, size_out,
315 frame_bytes = enc->frame_size * 2 * enc->channels;
317 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
318 &ost->fifo.rptr) == 0) {
319 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
321 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
324 /* output a pcm frame */
325 /* XXX: change encoding codec API to avoid this ? */
326 switch(enc->codec->id) {
327 case CODEC_ID_PCM_S16LE:
328 case CODEC_ID_PCM_S16BE:
329 case CODEC_ID_PCM_U16LE:
330 case CODEC_ID_PCM_U16BE:
333 size_out = size_out >> 1;
336 ret = avcodec_encode_audio(enc, audio_out, size_out,
338 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
342 /* write a picture to a raw mux */
343 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
344 int pix_fmt, int w, int h)
346 UINT8 *buf, *src, *dest;
349 /* XXX: not efficient, should add test if we can take
350 directly the AVPicture */
352 case PIX_FMT_YUV420P:
353 size = avpicture_get_size(pix_fmt, w, h);
354 buf = av_malloc(size);
363 src = picture->data[i];
365 memcpy(dest, src, w);
367 src += picture->linesize[i];
371 case PIX_FMT_YUV422P:
373 buf = av_malloc(size);
381 src = picture->data[i];
383 memcpy(dest, src, w);
385 src += picture->linesize[i];
389 case PIX_FMT_YUV444P:
391 buf = av_malloc(size);
396 src = picture->data[i];
398 memcpy(dest, src, w);
400 src += picture->linesize[i];
406 buf = av_malloc(size);
410 src = picture->data[0];
412 memcpy(dest, src, w * 2);
414 src += picture->linesize[0];
420 buf = av_malloc(size);
424 src = picture->data[0];
426 memcpy(dest, src, w * 3);
428 src += picture->linesize[0];
434 s->oformat->write_packet(s, index, buf, size, 0);
439 static void do_video_out(AVFormatContext *s,
445 int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
446 AVPicture *picture, *picture2, *pict;
447 AVPicture picture_tmp1, picture_tmp2;
448 static UINT8 *video_buffer;
449 UINT8 *buf = NULL, *buf1 = NULL;
450 AVCodecContext *enc, *dec;
452 #define VIDEO_BUFFER_SIZE (1024*1024)
454 enc = &ost->st->codec;
455 dec = &ist->st->codec;
457 frame_number = ist->frame_number;
458 dec_frame_rate = ist->st->r_frame_rate;
459 // fprintf(stderr, "\n%d", dec_frame_rate);
460 /* first drop frame if needed */
461 n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
462 n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
468 video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
469 if(!video_buffer) return;
471 /* deinterlace : must be done before any resize */
472 if (do_deinterlace) {
475 /* create temporary picture */
476 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
477 buf1 = av_malloc(size);
481 picture2 = &picture_tmp2;
482 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
484 if (avpicture_deinterlace(picture2, picture1,
485 dec->pix_fmt, dec->width, dec->height) < 0) {
486 /* if error, do not deinterlace */
495 /* convert pixel format if needed */
496 if (enc->pix_fmt != dec->pix_fmt) {
499 /* create temporary picture */
500 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
501 buf = av_malloc(size);
504 pict = &picture_tmp1;
505 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
507 if (img_convert(pict, enc->pix_fmt,
508 picture2, dec->pix_fmt,
509 dec->width, dec->height) < 0) {
510 fprintf(stderr, "pixel format conversion not handled\n");
517 /* XXX: resampling could be done before raw format convertion in
518 some cases to go faster */
519 /* XXX: only works for YUV420P */
520 if (ost->video_resample) {
521 picture = &ost->pict_tmp;
522 img_resample(ost->img_resample_ctx, picture, pict);
527 /* duplicates frame if needed */
528 /* XXX: pb because no interleaving */
530 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
531 /* handles sameq here. This is not correct because it may
532 not be a global option */
534 enc->quality = dec->quality;
537 ret = avcodec_encode_video(enc,
538 video_buffer, VIDEO_BUFFER_SIZE,
540 //enc->frame_number = enc->real_pict_num;
541 s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
543 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
544 // enc->frame_number-1, enc->real_pict_num, ret,
547 write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
555 static void do_video_stats(AVOutputStream *ost,
559 static FILE *fvstats=NULL;
560 static INT64 total_size = 0;
567 double ti1, bitrate, avg_bitrate;
571 today = localtime(&today2);
572 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
575 fvstats = fopen(filename,"w");
583 enc = &ost->st->codec;
584 total_size += frame_size;
585 if (enc->codec_type == CODEC_TYPE_VIDEO) {
586 frame_number = ist->frame_number;
587 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
589 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
591 fprintf(fvstats,"f_size= %6d ", frame_size);
592 /* compute min pts value */
593 if (!ist->discard && ist->pts < ti) {
596 ti1 = (double)ti / 1000000.0;
600 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
601 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
602 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
603 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
604 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
612 * The following code is the main loop of the file converter
614 static int av_encode(AVFormatContext **output_files,
616 AVFormatContext **input_files,
618 AVStreamMap *stream_maps, int nb_stream_maps)
620 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
621 AVFormatContext *is, *os;
622 AVCodecContext *codec, *icodec;
623 AVOutputStream *ost, **ost_table = NULL;
624 AVInputStream *ist, **ist_table = NULL;
625 INT64 min_pts, start_time;
626 AVInputFile *file_table;
627 AVFormatContext *stream_no_data;
630 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
634 /* input stream init */
636 for(i=0;i<nb_input_files;i++) {
638 file_table[i].ist_index = j;
639 file_table[i].nb_streams = is->nb_streams;
644 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
648 for(i=0;i<nb_istreams;i++) {
649 ist = av_mallocz(sizeof(AVInputStream));
655 for(i=0;i<nb_input_files;i++) {
657 for(k=0;k<is->nb_streams;k++) {
658 ist = ist_table[j++];
659 ist->st = is->streams[k];
662 ist->discard = 1; /* the stream is discarded by default
667 /* output stream init */
669 for(i=0;i<nb_output_files;i++) {
670 os = output_files[i];
671 nb_ostreams += os->nb_streams;
673 os->flags |= AVF_FLAG_VCD;
675 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
676 fprintf(stderr, "Number of stream maps must match number of output streams\n");
680 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
683 for(i=0;i<nb_ostreams;i++) {
684 ost = av_mallocz(sizeof(AVOutputStream));
691 for(k=0;k<nb_output_files;k++) {
692 os = output_files[k];
693 for(i=0;i<os->nb_streams;i++) {
695 ost = ost_table[n++];
698 ost->st = os->streams[i];
699 if (nb_stream_maps > 0) {
700 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
701 stream_maps[n-1].stream_index;
703 /* get corresponding input stream index : we select the first one with the right type */
705 for(j=0;j<nb_istreams;j++) {
708 ist->st->codec.codec_type == ost->st->codec.codec_type) {
709 ost->source_index = j;
715 /* try again and reuse existing stream */
716 for(j=0;j<nb_istreams;j++) {
718 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
719 ost->source_index = j;
724 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
725 ost->file_index, ost->index);
730 ist = ist_table[ost->source_index];
735 /* dump the stream mapping */
736 fprintf(stderr, "Stream mapping:\n");
737 for(i=0;i<nb_ostreams;i++) {
739 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
740 ist_table[ost->source_index]->file_index,
741 ist_table[ost->source_index]->index,
746 /* for each output stream, we compute the right encoding parameters */
747 for(i=0;i<nb_ostreams;i++) {
749 ist = ist_table[ost->source_index];
751 codec = &ost->st->codec;
752 icodec = &ist->st->codec;
754 switch(codec->codec_type) {
755 case CODEC_TYPE_AUDIO:
756 /* check if same codec with same parameters. If so, no
757 reencoding is needed */
758 if (codec->codec_id == icodec->codec_id &&
759 codec->bit_rate == icodec->bit_rate &&
760 codec->sample_rate == icodec->sample_rate &&
761 codec->channels == icodec->channels) {
763 /* use the same frame size */
764 codec->frame_size = icodec->frame_size;
765 //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
767 //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
769 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
772 if (codec->channels == icodec->channels &&
773 codec->sample_rate == icodec->sample_rate) {
774 ost->audio_resample = 0;
776 if (codec->channels != icodec->channels &&
777 icodec->codec_id == CODEC_ID_AC3) {
778 /* Special case for 5:1 AC3 input */
779 /* and mono or stereo output */
780 /* Request specific number of channels */
781 icodec->channels = codec->channels;
782 if (codec->sample_rate == icodec->sample_rate)
783 ost->audio_resample = 0;
785 ost->audio_resample = 1;
786 ost->resample = audio_resample_init(codec->channels, icodec->channels,
788 icodec->sample_rate);
790 /* Request specific number of channels */
791 icodec->channels = codec->channels;
793 ost->audio_resample = 1;
794 ost->resample = audio_resample_init(codec->channels, icodec->channels,
796 icodec->sample_rate);
799 ist->decoding_needed = 1;
800 ost->encoding_needed = 1;
803 case CODEC_TYPE_VIDEO:
804 /* check if same codec with same parameters. If so, no
805 reencoding is needed */
806 if (codec->codec_id == icodec->codec_id &&
807 codec->bit_rate == icodec->bit_rate &&
808 codec->frame_rate == icodec->frame_rate &&
809 codec->width == icodec->width &&
810 codec->height == icodec->height) {
813 if (codec->width == icodec->width &&
814 codec->height == icodec->height) {
815 ost->video_resample = 0;
818 ost->video_resample = 1;
819 buf = av_malloc((codec->width * codec->height * 3) / 2);
822 ost->pict_tmp.data[0] = buf;
823 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
824 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
825 ost->pict_tmp.linesize[0] = codec->width;
826 ost->pict_tmp.linesize[1] = codec->width / 2;
827 ost->pict_tmp.linesize[2] = codec->width / 2;
829 ost->img_resample_ctx = img_resample_full_init(
830 ost->st->codec.width, ost->st->codec.height,
831 ist->st->codec.width, ist->st->codec.height,
832 frame_topBand, frame_bottomBand,
833 frame_leftBand, frame_rightBand);
835 ost->encoding_needed = 1;
836 ist->decoding_needed = 1;
844 /* open each encoder */
845 for(i=0;i<nb_ostreams;i++) {
847 if (ost->encoding_needed) {
849 codec = avcodec_find_encoder(ost->st->codec.codec_id);
851 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
852 ost->file_index, ost->index);
855 if (avcodec_open(&ost->st->codec, codec) < 0) {
856 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
857 ost->file_index, ost->index);
863 /* open each decoder */
864 for(i=0;i<nb_istreams;i++) {
866 if (ist->decoding_needed) {
868 codec = avcodec_find_decoder(ist->st->codec.codec_id);
870 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
871 ist->file_index, ist->index);
874 if (avcodec_open(&ist->st->codec, codec) < 0) {
875 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
876 ist->file_index, ist->index);
879 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
880 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
885 for(i=0;i<nb_istreams;i++) {
888 ist->frame_number = 0;
891 /* compute buffer size max (should use a complete heuristic) */
892 for(i=0;i<nb_input_files;i++) {
893 file_table[i].buffer_size_max = 2048;
896 /* open files and write file headers */
897 for(i=0;i<nb_output_files;i++) {
898 os = output_files[i];
899 if (av_write_header(os) < 0) {
900 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
908 fprintf(stderr, "Press [q] to stop encoding\n");
910 fprintf(stderr, "Press [q] to stop playing\n");
915 start_time = av_gettime();
921 int file_index, ist_index;
926 int data_size, got_picture;
928 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
931 /* if 'q' pressed, exits */
933 /* read_key() returns 0 on EOF */
939 /* select the input file with the smallest pts */
942 for(i=0;i<nb_istreams;i++) {
944 /* For some reason, the pts_increment code breaks q estimation?!? */
945 if (!ist->discard && !file_table[ist->file_index].eof_reached &&
946 ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
947 min_pts = ist->pts /* + ist->pts_increment */;
948 file_index = ist->file_index;
951 /* if none, if is finished */
952 if (file_index < 0) {
953 if (stream_no_data) {
954 #ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
956 snooze(10 * 1000); /* mmu_man */ /* in microsec */
957 #elif defined(__CYGWIN__)
963 ts.tv_nsec = 1000 * 1000 * 10;
972 /* finish if recording time exhausted */
973 if (recording_time > 0 && min_pts >= recording_time)
975 /* read a packet from it and output it in the fifo */
976 is = input_files[file_index];
977 if (av_read_packet(is, &pkt) < 0) {
978 file_table[file_index].eof_reached = 1;
986 /* the following test is needed in case new streams appear
987 dynamically in stream : we ignore them */
988 if (pkt.stream_index >= file_table[file_index].nb_streams)
990 ist_index = file_table[file_index].ist_index + pkt.stream_index;
991 ist = ist_table[ist_index];
995 if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
999 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1000 av_hex_dump(pkt.data, pkt.size);
1003 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1009 /* decode the packet if needed */
1010 data_buf = NULL; /* fail safe */
1012 if (ist->decoding_needed) {
1013 switch(ist->st->codec.codec_type) {
1014 case CODEC_TYPE_AUDIO:
1015 /* XXX: could avoid copy if PCM 16 bits with same
1016 endianness as CPU */
1017 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1021 /* Some bug in mpeg audio decoder gives */
1022 /* data_size < 0, it seems they are overflows */
1023 if (data_size <= 0) {
1024 /* no audio frame */
1029 data_buf = (UINT8 *)samples;
1031 case CODEC_TYPE_VIDEO:
1032 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1035 size = (ist->st->codec.width * ist->st->codec.height);
1036 avpicture_fill(&picture, ptr,
1037 ist->st->codec.pix_fmt,
1038 ist->st->codec.width,
1039 ist->st->codec.height);
1042 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1043 ret = avcodec_decode_video(&ist->st->codec,
1044 &picture, &got_picture, ptr, len);
1047 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1048 ist->file_index, ist->index);
1049 av_free_packet(&pkt);
1053 /* no picture yet */
1070 if (!ist->ticker_inited) {
1071 switch (ist->st->codec.codec_type) {
1072 case CODEC_TYPE_AUDIO:
1073 ticker_init(&ist->pts_ticker,
1074 (INT64)ist->st->codec.sample_rate,
1076 ist->ticker_inited = 1;
1078 case CODEC_TYPE_VIDEO:
1079 ticker_init(&ist->pts_ticker,
1080 (INT64)ist->st->r_frame_rate,
1081 ((INT64)1000000 * FRAME_RATE_BASE));
1082 ist->ticker_inited = 1;
1089 switch(ist->st->codec.codec_type) {
1090 case CODEC_TYPE_AUDIO:
1091 //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1092 ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
1093 ist->sample_index += data_size / (2 * ist->st->codec.channels);
1094 ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1096 case CODEC_TYPE_VIDEO:
1097 ist->frame_number++;
1098 //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
1099 // ist->st->codec.frame_rate;
1100 ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
1101 ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) /
1102 ist->st->codec.frame_rate;
1110 /* transcode raw format, encode packets and output them */
1112 for(i=0;i<nb_ostreams;i++) {
1115 if (ost->source_index == ist_index) {
1116 os = output_files[ost->file_index];
1118 if (ost->encoding_needed) {
1119 switch(ost->st->codec.codec_type) {
1120 case CODEC_TYPE_AUDIO:
1121 do_audio_out(os, ost, ist, data_buf, data_size);
1123 case CODEC_TYPE_VIDEO:
1124 do_video_out(os, ost, ist, &picture, &frame_size);
1126 do_video_stats(ost, ist, frame_size);
1132 /* no reencoding needed : output the packet directly */
1133 /* force the input stream PTS */
1134 os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1140 av_free_packet(&pkt);
1142 /* dump report by using the first video and audio streams */
1145 AVFormatContext *oc;
1146 INT64 total_size, ti;
1147 AVCodecContext *enc;
1148 int frame_number, vid;
1149 double bitrate, ti1;
1150 static INT64 last_time;
1152 if ((min_pts - last_time) >= 500000) {
1153 last_time = min_pts;
1155 oc = output_files[0];
1157 total_size = url_ftell(&oc->pb);
1162 for(i=0;i<nb_ostreams;i++) {
1164 enc = &ost->st->codec;
1165 ist = ist_table[ost->source_index];
1166 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1167 frame_number = ist->frame_number;
1168 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1169 frame_number, enc->quality);
1171 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1174 /* compute min pts value */
1175 if (!ist->discard && ist->pts < ti) {
1180 ti1 = (double)ti / 1000000.0;
1183 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1185 sprintf(buf + strlen(buf),
1186 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1187 (double)total_size / 1024, ti1, bitrate);
1189 fprintf(stderr, "%s \r", buf);
1196 /* dump report by using the first video and audio streams */
1199 AVFormatContext *oc;
1200 INT64 total_size, ti;
1201 AVCodecContext *enc;
1202 int frame_number, vid;
1203 double bitrate, ti1;
1205 oc = output_files[0];
1207 total_size = url_ftell(&oc->pb);
1212 for(i=0;i<nb_ostreams;i++) {
1214 enc = &ost->st->codec;
1215 ist = ist_table[ost->source_index];
1216 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1217 frame_number = ist->frame_number;
1218 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1219 frame_number, enc->quality);
1221 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1224 /* compute min pts value */
1225 if (!ist->discard && ist->pts < ti) {
1230 ti1 = ti / 1000000.0;
1233 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1235 sprintf(buf + strlen(buf),
1236 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1237 (double)total_size / 1024, ti1, bitrate);
1239 fprintf(stderr, "%s \n", buf);
1241 /* close each encoder */
1242 for(i=0;i<nb_ostreams;i++) {
1244 if (ost->encoding_needed) {
1245 avcodec_close(&ost->st->codec);
1249 /* close each decoder */
1250 for(i=0;i<nb_istreams;i++) {
1252 if (ist->decoding_needed) {
1253 avcodec_close(&ist->st->codec);
1258 /* write the trailer if needed and close file */
1259 for(i=0;i<nb_output_files;i++) {
1260 os = output_files[i];
1261 av_write_trailer(os);
1267 av_free(file_table);
1270 for(i=0;i<nb_istreams;i++) {
1277 for(i=0;i<nb_ostreams;i++) {
1280 fifo_free(&ost->fifo); /* works even if fifo is not
1281 initialized but set to zero */
1282 av_free(ost->pict_tmp.data[0]);
1283 if (ost->video_resample)
1284 img_resample_close(ost->img_resample_ctx);
1285 if (ost->audio_resample)
1286 audio_resample_close(ost->resample);
1299 int file_read(const char *filename)
1302 unsigned char buffer[1024];
1305 if (url_open(&h, filename, O_RDONLY) < 0) {
1306 printf("could not open '%s'\n", filename);
1310 len = url_read(h, buffer, sizeof(buffer));
1313 for(i=0;i<len;i++) putchar(buffer[i]);
1320 void show_licence(void)
1323 "ffmpeg version " FFMPEG_VERSION "\n"
1324 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1325 "This library is free software; you can redistribute it and/or\n"
1326 "modify it under the terms of the GNU Lesser General Public\n"
1327 "License as published by the Free Software Foundation; either\n"
1328 "version 2 of the License, or (at your option) any later version.\n"
1330 "This library is distributed in the hope that it will be useful,\n"
1331 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1332 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1333 "Lesser General Public License for more details.\n"
1335 "You should have received a copy of the GNU Lesser General Public\n"
1336 "License along with this library; if not, write to the Free Software\n"
1337 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1342 void opt_format(const char *arg)
1344 file_iformat = av_find_input_format(arg);
1345 file_oformat = guess_format(arg, NULL, NULL);
1346 if (!file_iformat && !file_oformat) {
1347 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1352 void opt_video_bitrate(const char *arg)
1354 video_bit_rate = atoi(arg) * 1000;
1357 void opt_video_bitrate_tolerance(const char *arg)
1359 video_bit_rate_tolerance = atoi(arg) * 1000;
1362 void opt_video_bitrate_max(const char *arg)
1364 video_rc_max_rate = atoi(arg) * 1000;
1367 void opt_video_bitrate_min(const char *arg)
1369 video_rc_min_rate = atoi(arg) * 1000;
1372 void opt_video_buffer_size(const char *arg)
1374 video_rc_buffer_size = atoi(arg) * 1000;
1377 void opt_video_rc_eq(char *arg)
1383 void opt_workaround_bugs(const char *arg)
1385 workaround_bugs = atoi(arg);
1388 void opt_dct_algo(const char *arg)
1390 dct_algo = atoi(arg);
1393 void opt_error_resilience(const char *arg)
1395 error_resilience = atoi(arg);
1398 void opt_frame_rate(const char *arg)
1400 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1404 void opt_frame_crop_top(const char *arg)
1406 frame_topBand = atoi(arg);
1407 if (frame_topBand < 0) {
1408 fprintf(stderr, "Incorrect top crop size\n");
1411 if ((frame_topBand % 2) != 0) {
1412 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1415 if ((frame_topBand) >= frame_height){
1416 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1419 frame_height -= frame_topBand;
1422 void opt_frame_crop_bottom(const char *arg)
1424 frame_bottomBand = atoi(arg);
1425 if (frame_bottomBand < 0) {
1426 fprintf(stderr, "Incorrect bottom crop size\n");
1429 if ((frame_bottomBand % 2) != 0) {
1430 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1433 if ((frame_bottomBand) >= frame_height){
1434 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1437 frame_height -= frame_bottomBand;
1440 void opt_frame_crop_left(const char *arg)
1442 frame_leftBand = atoi(arg);
1443 if (frame_leftBand < 0) {
1444 fprintf(stderr, "Incorrect left crop size\n");
1447 if ((frame_leftBand % 2) != 0) {
1448 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1451 if ((frame_leftBand) >= frame_width){
1452 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1455 frame_width -= frame_leftBand;
1458 void opt_frame_crop_right(const char *arg)
1460 frame_rightBand = atoi(arg);
1461 if (frame_rightBand < 0) {
1462 fprintf(stderr, "Incorrect right crop size\n");
1465 if ((frame_rightBand % 2) != 0) {
1466 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1469 if ((frame_rightBand) >= frame_width){
1470 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1473 frame_width -= frame_rightBand;
1476 void opt_frame_size(const char *arg)
1478 parse_image_size(&frame_width, &frame_height, arg);
1479 if (frame_width <= 0 || frame_height <= 0) {
1480 fprintf(stderr, "Incorrect frame size\n");
1483 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1484 fprintf(stderr, "Frame size must be a multiple of 2\n");
1489 void opt_gop_size(const char *arg)
1491 gop_size = atoi(arg);
1494 void opt_b_frames(const char *arg)
1496 b_frames = atoi(arg);
1497 if (b_frames > FF_MAX_B_FRAMES) {
1498 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1500 } else if (b_frames < 1) {
1501 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1506 void opt_qscale(const char *arg)
1508 video_qscale = atoi(arg);
1509 if (video_qscale < 0 ||
1510 video_qscale > 31) {
1511 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1516 void opt_qmin(const char *arg)
1518 video_qmin = atoi(arg);
1519 if (video_qmin < 0 ||
1521 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1526 void opt_qmax(const char *arg)
1528 video_qmax = atoi(arg);
1529 if (video_qmax < 0 ||
1531 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1536 void opt_qdiff(const char *arg)
1538 video_qdiff = atoi(arg);
1539 if (video_qdiff < 0 ||
1541 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1546 void opt_qblur(const char *arg)
1548 video_qblur = atof(arg);
1551 void opt_qcomp(const char *arg)
1553 video_qcomp = atof(arg);
1556 void opt_b_qfactor(const char *arg)
1558 video_b_qfactor = atof(arg);
1560 void opt_i_qfactor(const char *arg)
1562 video_i_qfactor = atof(arg);
1564 void opt_b_qoffset(const char *arg)
1566 video_b_qoffset = atof(arg);
1568 void opt_i_qoffset(const char *arg)
1570 video_i_qoffset = atof(arg);
1573 void opt_audio_bitrate(const char *arg)
1575 audio_bit_rate = atoi(arg) * 1000;
1578 void opt_audio_rate(const char *arg)
1580 audio_sample_rate = atoi(arg);
1583 void opt_audio_channels(const char *arg)
1585 audio_channels = atoi(arg);
1588 void opt_video_device(const char *arg)
1590 v4l_device = strdup(arg);
1593 void opt_audio_device(const char *arg)
1595 audio_device = strdup(arg);
1598 void opt_audio_codec(const char *arg)
1604 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1609 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1612 audio_codec_id = p->id;
1616 const char *motion_str[] = {
1626 void opt_motion_estimation(const char *arg)
1632 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1635 if (!strcmp(*p, arg))
1639 me_method = (p - motion_str) + 1;
1642 void opt_video_codec(const char *arg)
1648 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1653 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1656 video_codec_id = p->id;
1660 void opt_map(const char *arg)
1666 m = &stream_maps[nb_stream_maps++];
1668 m->file_index = strtol(arg, (char **)&p, 0);
1672 m->stream_index = strtol(p, (char **)&p, 0);
1675 void opt_recording_time(const char *arg)
1677 recording_time = parse_date(arg, 1);
1680 void print_error(const char *filename, int err)
1683 case AVERROR_NUMEXPECTED:
1684 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1685 "Use '%%d' to specify the image number:\n"
1686 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1687 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1690 case AVERROR_INVALIDDATA:
1691 fprintf(stderr, "%s: Error while parsing header\n", filename);
1694 fprintf(stderr, "%s: Unknown format\n", filename);
1697 fprintf(stderr, "%s: Error while opening file\n", filename);
1702 void opt_input_file(const char *filename)
1704 AVFormatContext *ic;
1705 AVFormatParameters params, *ap = ¶ms;
1706 int err, i, ret, rfps;
1708 /* get default parameters from command line */
1709 memset(ap, 0, sizeof(*ap));
1710 ap->sample_rate = audio_sample_rate;
1711 ap->channels = audio_channels;
1712 ap->frame_rate = frame_rate;
1713 ap->width = frame_width;
1714 ap->height = frame_height;
1716 /* open the input file with generic libav function */
1717 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1719 print_error(filename, err);
1723 /* If not enough info to get the stream parameters, we decode the
1724 first frames to get it. (used in mpeg case for example) */
1725 ret = av_find_stream_info(ic);
1727 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1731 /* update the current parameters so that they match the one of the input stream */
1732 for(i=0;i<ic->nb_streams;i++) {
1733 AVCodecContext *enc = &ic->streams[i]->codec;
1734 switch(enc->codec_type) {
1735 case CODEC_TYPE_AUDIO:
1736 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1737 audio_channels = enc->channels;
1738 audio_sample_rate = enc->sample_rate;
1740 case CODEC_TYPE_VIDEO:
1741 frame_height = enc->height;
1742 frame_width = enc->width;
1743 rfps = ic->streams[i]->r_frame_rate;
1744 enc->workaround_bugs = workaround_bugs;
1745 enc->error_resilience = error_resilience;
1746 if (enc->frame_rate != rfps) {
1747 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1748 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1749 (float)rfps / FRAME_RATE_BASE);
1751 /* update the current frame rate to match the stream frame rate */
1759 input_files[nb_input_files] = ic;
1760 /* dump the file content */
1761 dump_format(ic, nb_input_files, filename, 0);
1763 file_iformat = NULL;
1764 file_oformat = NULL;
1767 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1769 int has_video, has_audio, i, j;
1770 AVFormatContext *ic;
1774 for(j=0;j<nb_input_files;j++) {
1775 ic = input_files[j];
1776 for(i=0;i<ic->nb_streams;i++) {
1777 AVCodecContext *enc = &ic->streams[i]->codec;
1778 switch(enc->codec_type) {
1779 case CODEC_TYPE_AUDIO:
1782 case CODEC_TYPE_VIDEO:
1790 *has_video_ptr = has_video;
1791 *has_audio_ptr = has_audio;
1794 void opt_output_file(const char *filename)
1797 AVFormatContext *oc;
1798 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1801 if (!strcmp(filename, "-"))
1804 oc = av_mallocz(sizeof(AVFormatContext));
1806 if (!file_oformat) {
1807 file_oformat = guess_format(NULL, filename, NULL);
1808 if (!file_oformat) {
1809 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1815 oc->oformat = file_oformat;
1817 if (!strcmp(file_oformat->name, "ffm") &&
1818 strstart(filename, "http:", NULL)) {
1819 /* special case for files sent to ffserver: we get the stream
1820 parameters from ffserver */
1821 if (read_ffserver_streams(oc, filename) < 0) {
1822 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1826 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1827 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1829 /* disable if no corresponding type found and at least one
1831 if (nb_input_files > 0) {
1832 check_audio_video_inputs(&input_has_video, &input_has_audio);
1833 if (!input_has_video)
1835 if (!input_has_audio)
1839 /* manual disable */
1840 if (audio_disable) {
1843 if (video_disable) {
1849 AVCodecContext *video_enc;
1851 st = av_mallocz(sizeof(AVStream));
1853 fprintf(stderr, "Could not alloc stream\n");
1856 video_enc = &st->codec;
1858 codec_id = file_oformat->video_codec;
1859 if (video_codec_id != CODEC_ID_NONE)
1860 codec_id = video_codec_id;
1862 video_enc->codec_id = codec_id;
1863 video_enc->codec_type = CODEC_TYPE_VIDEO;
1865 video_enc->bit_rate = video_bit_rate;
1866 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1867 video_enc->frame_rate = frame_rate;
1869 video_enc->width = frame_width;
1870 video_enc->height = frame_height;
1872 video_enc->gop_size = gop_size;
1874 video_enc->gop_size = 0;
1875 if (video_qscale || same_quality) {
1876 video_enc->flags |= CODEC_FLAG_QSCALE;
1877 video_enc->quality = video_qscale;
1881 video_enc->flags |= CODEC_FLAG_HQ;
1885 video_enc->flags |= CODEC_FLAG_HQ;
1886 video_enc->flags |= CODEC_FLAG_4MV;
1890 if (codec_id != CODEC_ID_MPEG4) {
1891 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1894 video_enc->max_b_frames = b_frames;
1895 video_enc->b_frame_strategy = 0;
1896 video_enc->b_quant_factor = 2.0;
1899 video_enc->qmin = video_qmin;
1900 video_enc->qmax = video_qmax;
1901 video_enc->max_qdiff = video_qdiff;
1902 video_enc->qblur = video_qblur;
1903 video_enc->qcompress = video_qcomp;
1904 video_enc->rc_eq = video_rc_eq;
1905 video_enc->rc_max_rate = video_rc_max_rate;
1906 video_enc->rc_min_rate = video_rc_min_rate;
1907 video_enc->rc_buffer_size = video_rc_buffer_size;
1908 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
1909 video_enc->i_quant_factor = video_i_qfactor;
1910 video_enc->b_quant_factor = video_b_qfactor;
1911 video_enc->i_quant_offset = video_i_qoffset;
1912 video_enc->b_quant_offset = video_b_qoffset;
1913 video_enc->dct_algo = dct_algo;
1916 video_enc->get_psnr = 1;
1918 video_enc->get_psnr = 0;
1920 video_enc->me_method = me_method;
1922 /* XXX: need to find a way to set codec parameters */
1923 if (oc->oformat->flags & AVFMT_RGB24) {
1924 video_enc->pix_fmt = PIX_FMT_RGB24;
1927 oc->streams[nb_streams] = st;
1932 AVCodecContext *audio_enc;
1934 st = av_mallocz(sizeof(AVStream));
1936 fprintf(stderr, "Could not alloc stream\n");
1939 audio_enc = &st->codec;
1940 codec_id = file_oformat->audio_codec;
1941 if (audio_codec_id != CODEC_ID_NONE)
1942 codec_id = audio_codec_id;
1943 audio_enc->codec_id = codec_id;
1944 audio_enc->codec_type = CODEC_TYPE_AUDIO;
1946 audio_enc->bit_rate = audio_bit_rate;
1947 audio_enc->sample_rate = audio_sample_rate;
1948 /* For audio codecs other than AC3 we limit */
1949 /* the number of coded channels to stereo */
1950 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
1951 audio_enc->channels = 2;
1953 audio_enc->channels = audio_channels;
1954 oc->streams[nb_streams] = st;
1958 oc->nb_streams = nb_streams;
1961 fprintf(stderr, "No audio or video streams available\n");
1966 pstrcpy(oc->title, sizeof(oc->title), str_title);
1968 pstrcpy(oc->author, sizeof(oc->author), str_author);
1970 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1972 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1975 output_files[nb_output_files] = oc;
1976 /* dump the file content */
1977 dump_format(oc, nb_output_files, filename, 1);
1980 strcpy(oc->filename, filename);
1982 /* check filename in case of an image number is expected */
1983 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
1984 if (filename_number_test(oc->filename) < 0) {
1985 print_error(oc->filename, AVERROR_NUMEXPECTED);
1990 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
1991 /* test if it already exists to avoid loosing precious files */
1992 if (!file_overwrite &&
1993 (strchr(filename, ':') == NULL ||
1994 strstart(filename, "file:", NULL))) {
1995 if (url_exist(filename)) {
1998 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2001 if (toupper(c) != 'Y') {
2002 fprintf(stderr, "Not overwriting - exiting\n");
2009 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2010 fprintf(stderr, "Could not open '%s'\n", filename);
2015 /* reset some options */
2016 file_oformat = NULL;
2017 file_iformat = NULL;
2020 audio_codec_id = CODEC_ID_NONE;
2021 video_codec_id = CODEC_ID_NONE;
2024 /* prepare dummy protocols for grab */
2025 void prepare_grab(void)
2027 int has_video, has_audio, i, j;
2028 AVFormatContext *oc;
2029 AVFormatContext *ic;
2030 AVFormatParameters ap1, *ap = &ap1;
2032 /* see if audio/video inputs are needed */
2035 memset(ap, 0, sizeof(*ap));
2036 for(j=0;j<nb_output_files;j++) {
2037 oc = output_files[j];
2038 for(i=0;i<oc->nb_streams;i++) {
2039 AVCodecContext *enc = &oc->streams[i]->codec;
2040 switch(enc->codec_type) {
2041 case CODEC_TYPE_AUDIO:
2042 if (enc->sample_rate > ap->sample_rate)
2043 ap->sample_rate = enc->sample_rate;
2044 if (enc->channels > ap->channels)
2045 ap->channels = enc->channels;
2048 case CODEC_TYPE_VIDEO:
2049 if (enc->width > ap->width)
2050 ap->width = enc->width;
2051 if (enc->height > ap->height)
2052 ap->height = enc->height;
2053 if (enc->frame_rate > ap->frame_rate)
2054 ap->frame_rate = enc->frame_rate;
2063 if (has_video == 0 && has_audio == 0) {
2064 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2069 AVInputFormat *fmt1;
2070 fmt1 = av_find_input_format("video_grab_device");
2071 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2072 fprintf(stderr, "Could not find video grab device\n");
2075 /* by now video grab has one stream */
2076 ic->streams[0]->r_frame_rate = ap->frame_rate;
2077 input_files[nb_input_files] = ic;
2078 dump_format(ic, nb_input_files, v4l_device, 0);
2082 AVInputFormat *fmt1;
2083 fmt1 = av_find_input_format("audio_device");
2084 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2085 fprintf(stderr, "Could not find audio grab device\n");
2088 input_files[nb_input_files] = ic;
2089 dump_format(ic, nb_input_files, audio_device, 0);
2094 /* open the necessary output devices for playing */
2095 void prepare_play(void)
2097 file_iformat = NULL;
2098 file_oformat = guess_format("audio_device", NULL, NULL);
2099 if (!file_oformat) {
2100 fprintf(stderr, "Could not find audio device\n");
2104 opt_output_file(audio_device);
2108 #ifndef CONFIG_WIN32
2109 INT64 getutime(void)
2111 struct rusage rusage;
2113 getrusage(RUSAGE_SELF, &rusage);
2114 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2117 INT64 getutime(void)
2119 return av_gettime();
2123 extern int ffm_nopts;
2125 void opt_bitexact(void)
2127 avcodec_set_bit_exact();
2128 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2132 void show_formats(void)
2134 AVInputFormat *ifmt;
2135 AVOutputFormat *ofmt;
2140 printf("File formats:\n");
2141 printf(" Encoding:");
2142 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2143 printf(" %s", ofmt->name);
2146 printf(" Decoding:");
2147 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2148 printf(" %s", ifmt->name);
2152 printf("Codecs:\n");
2153 printf(" Encoders:");
2154 for(p = first_avcodec; p != NULL; p = p->next) {
2156 printf(" %s", p->name);
2160 printf(" Decoders:");
2161 for(p = first_avcodec; p != NULL; p = p->next) {
2163 printf(" %s", p->name);
2167 printf("Supported file protocols:");
2168 for(up = first_protocol; up != NULL; up = up->next)
2169 printf(" %s:", up->name);
2172 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2173 printf("Motion estimation methods:");
2177 if ((pp - motion_str + 1) == ME_ZERO)
2178 printf("(fastest)");
2179 else if ((pp - motion_str + 1) == ME_FULL)
2180 printf("(slowest)");
2181 else if ((pp - motion_str + 1) == ME_EPZS)
2182 printf("(default)");
2189 void show_help(void)
2192 const OptionDef *po;
2195 prog = do_play ? "ffplay" : "ffmpeg";
2197 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2201 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2202 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2204 printf("usage: ffplay [options] input_file...\n"
2205 "Simple audio player\n");
2209 "Main options are:\n");
2212 printf("\nAdvanced options are:\n");
2213 for(po = options; po->name != NULL; po++) {
2215 expert = (po->flags & OPT_EXPERT) != 0;
2217 strcpy(buf, po->name);
2218 if (po->flags & HAS_ARG) {
2220 strcat(buf, po->argname);
2222 printf("-%-17s %s\n", buf, po->help);
2230 const OptionDef options[] = {
2231 { "L", 0, {(void*)show_licence}, "show license" },
2232 { "h", 0, {(void*)show_help}, "show help" },
2233 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2234 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2235 { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2236 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2237 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2238 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2239 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2240 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2241 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2242 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2243 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2245 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2246 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2247 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2248 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2249 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2250 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2251 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2252 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2253 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2254 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2255 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2256 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2257 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2258 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2259 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2260 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2261 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2262 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2263 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2264 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2265 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2266 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2267 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2268 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2269 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2270 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2271 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2272 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2274 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2275 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2276 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2277 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2278 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2279 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2280 { "sameq", OPT_BOOL, {(void*)&same_quality},
2281 "use same video quality as source (implies VBR)" },
2283 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2284 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2285 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2286 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2287 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2288 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2289 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2290 "deinterlace pictures" },
2291 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2292 "add timings for benchmarking" },
2293 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2294 "dump each input packet" },
2295 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2296 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2297 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2301 int main(int argc, char **argv)
2304 const char *opt, *arg;
2305 const OptionDef *po;
2310 /* detect if invoked as player */
2311 i = strlen(argv[0]);
2312 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2320 while (optindex < argc) {
2321 opt = argv[optindex++];
2323 if (opt[0] == '-' && opt[1] != '\0') {
2325 while (po->name != NULL) {
2326 if (!strcmp(opt + 1, po->name))
2331 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2335 if (po->flags & HAS_ARG)
2336 arg = argv[optindex++];
2337 if (po->flags & OPT_STRING) {
2340 *po->u.str_arg = str;
2341 } else if (po->flags & OPT_BOOL) {
2344 po->u.func_arg(arg);
2348 opt_output_file(opt);
2350 opt_input_file(opt);
2357 /* file converter / grab */
2358 if (nb_output_files <= 0) {
2359 fprintf(stderr, "Must supply at least one output file\n");
2363 if (nb_input_files == 0) {
2368 if (nb_input_files <= 0) {
2369 fprintf(stderr, "Must supply at least one input file\n");
2376 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2377 stream_maps, nb_stream_maps);
2378 ti = getutime() - ti;
2380 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2384 for(i=0;i<nb_output_files;i++) {
2385 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
2386 url_fclose(&output_files[i]->pb);
2388 for(i=0;i<nb_input_files;i++)
2389 av_close_input_file(input_files[i]);