added two pass support (same syntax as mencoder)
[libav.git] / ffmpeg.c
1 /*
2 * FFmpeg main
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 *
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.
9 *
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.
14 *
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
18 */
19 #define HAVE_AV_CONFIG_H
20 #include "avformat.h"
21 #include "tick.h"
22
23 #ifndef CONFIG_WIN32
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/ioctl.h>
27 #include <sys/time.h>
28 #include <termios.h>
29 #include <sys/resource.h>
30 #endif
31 #ifdef __BEOS__
32 /* for snooze() */
33 #include <OS.h>
34 #endif
35 #include <time.h>
36 #include <ctype.h>
37
38
39 #define MAXINT64 INT64_C(0x7fffffffffffffff)
40
41 typedef struct {
42 const char *name;
43 int flags;
44 #define HAS_ARG 0x0001
45 #define OPT_BOOL 0x0002
46 #define OPT_EXPERT 0x0004
47 #define OPT_STRING 0x0008
48 union {
49 void (*func_arg)();
50 int *int_arg;
51 char **str_arg;
52 } u;
53 const char *help;
54 const char *argname;
55 } OptionDef;
56
57 /* select an input stream for an output stream */
58 typedef struct AVStreamMap {
59 int file_index;
60 int stream_index;
61 } AVStreamMap;
62
63 extern const OptionDef options[];
64
65 void show_help(void);
66
67 #define MAX_FILES 20
68
69 static AVFormatContext *input_files[MAX_FILES];
70 static int nb_input_files = 0;
71
72 static AVFormatContext *output_files[MAX_FILES];
73 static int nb_output_files = 0;
74
75 static AVStreamMap stream_maps[MAX_FILES];
76 static int nb_stream_maps;
77
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;
120 static int idct_algo = 0;
121 static int use_part = 0;
122 static int packet_size = 0;
123
124 static int gop_size = 12;
125 static int intra_only = 0;
126 static int audio_sample_rate = 44100;
127 static int audio_bit_rate = 64000;
128 static int audio_disable = 0;
129 static int audio_channels = 1;
130 static int audio_codec_id = CODEC_ID_NONE;
131
132 static INT64 recording_time = 0;
133 static int file_overwrite = 0;
134 static char *str_title = NULL;
135 static char *str_author = NULL;
136 static char *str_copyright = NULL;
137 static char *str_comment = NULL;
138 static int do_benchmark = 0;
139 static int do_hex_dump = 0;
140 static int do_play = 0;
141 static int do_psnr = 0;
142 static int do_vstats = 0;
143 static int mpeg_vcd = 0;
144 static int do_pass = 0;
145 static char *pass_logfilename = NULL;
146
147 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
148
149 #ifndef CONFIG_AUDIO_OSS
150 const char *audio_device = "none";
151 #endif
152 #ifndef CONFIG_VIDEO4LINUX
153 const char *v4l_device = "none";
154 #endif
155
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 */
162
163 /* video only */
164 AVPicture pict_tmp; /* temporary image for resizing */
165 int video_resample;
166 ImgReSampleContext *img_resample_ctx; /* for image resampling */
167
168 /* audio only */
169 int audio_resample;
170 ReSampleContext *resample; /* for audio resampling */
171 FifoBuffer fifo; /* for compression: one audio fifo per codec */
172 FILE *logfile;
173 } AVOutputStream;
174
175 typedef struct AVInputStream {
176 int file_index;
177 int index;
178 AVStream *st;
179 int discard; /* true if stream data should be discarded */
180 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
181 Ticker pts_ticker; /* Ticker for PTS calculation */
182 int ticker_inited; /* to signal if the ticker was initialized */
183 INT64 pts; /* current pts */
184 int pts_increment; /* expected pts increment for next packet */
185 int frame_number; /* current frame */
186 INT64 sample_index; /* current sample */
187 } AVInputStream;
188
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
194 buffering */
195 int nb_streams; /* nb streams we are aware of */
196 } AVInputFile;
197
198 #ifndef CONFIG_WIN32
199
200 /* init terminal so that we can grab keys */
201 static struct termios oldtty;
202
203 static void term_exit(void)
204 {
205 tcsetattr (0, TCSANOW, &oldtty);
206 }
207
208 static void term_init(void)
209 {
210 struct termios tty;
211
212 tcgetattr (0, &tty);
213 oldtty = tty;
214
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);
220 tty.c_cflag |= CS8;
221 tty.c_cc[VMIN] = 1;
222 tty.c_cc[VTIME] = 0;
223
224 tcsetattr (0, TCSANOW, &tty);
225
226 atexit(term_exit);
227 }
228
229 /* read a key without blocking */
230 static int read_key(void)
231 {
232 struct timeval tv;
233 int n;
234 unsigned char ch;
235 fd_set rfds;
236
237 FD_ZERO(&rfds);
238 FD_SET(0, &rfds);
239 tv.tv_sec = 0;
240 tv.tv_usec = 0;
241 n = select(1, &rfds, NULL, NULL, &tv);
242 if (n > 0) {
243 n = read(0, &ch, 1);
244 if (n == 1)
245 return ch;
246
247 return n;
248 }
249 return -1;
250 }
251
252 #else
253
254 /* no interactive support */
255 static void term_exit(void)
256 {
257 }
258
259 static void term_init(void)
260 {
261 }
262
263 static int read_key(void)
264 {
265 return 0;
266 }
267
268 #endif
269
270 int read_ffserver_streams(AVFormatContext *s, const char *filename)
271 {
272 int i, err;
273 AVFormatContext *ic;
274
275 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
276 if (err < 0)
277 return err;
278 /* copy stream format */
279 s->nb_streams = ic->nb_streams;
280 for(i=0;i<ic->nb_streams;i++) {
281 AVStream *st;
282 st = av_mallocz(sizeof(AVFormatContext));
283 memcpy(st, ic->streams[i], sizeof(AVStream));
284 s->streams[i] = st;
285 }
286
287 av_close_input_file(ic);
288 return 0;
289 }
290
291 #define MAX_AUDIO_PACKET_SIZE 16384
292
293 static void do_audio_out(AVFormatContext *s,
294 AVOutputStream *ost,
295 AVInputStream *ist,
296 unsigned char *buf, int size)
297 {
298 UINT8 *buftmp;
299 UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
300 UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
301 int size_out, frame_bytes, ret;
302 AVCodecContext *enc;
303
304 enc = &ost->st->codec;
305
306 if (ost->audio_resample) {
307 buftmp = audio_buf;
308 size_out = audio_resample(ost->resample,
309 (short *)buftmp, (short *)buf,
310 size / (ist->st->codec.channels * 2));
311 size_out = size_out * enc->channels * 2;
312 } else {
313 buftmp = buf;
314 size_out = size;
315 }
316
317 /* now encode as many frames as possible */
318 if (enc->frame_size > 1) {
319 /* output resampled raw samples */
320 fifo_write(&ost->fifo, buftmp, size_out,
321 &ost->fifo.wptr);
322
323 frame_bytes = enc->frame_size * 2 * enc->channels;
324
325 while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
326 &ost->fifo.rptr) == 0) {
327 ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
328 (short *)audio_buf);
329 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
330 }
331 } else {
332 /* output a pcm frame */
333 /* XXX: change encoding codec API to avoid this ? */
334 switch(enc->codec->id) {
335 case CODEC_ID_PCM_S16LE:
336 case CODEC_ID_PCM_S16BE:
337 case CODEC_ID_PCM_U16LE:
338 case CODEC_ID_PCM_U16BE:
339 break;
340 default:
341 size_out = size_out >> 1;
342 break;
343 }
344 ret = avcodec_encode_audio(enc, audio_out, size_out,
345 (short *)buftmp);
346 s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
347 }
348 }
349
350 /* write a picture to a raw mux */
351 static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
352 int pix_fmt, int w, int h)
353 {
354 UINT8 *buf, *src, *dest;
355 int size, j, i;
356
357 /* XXX: not efficient, should add test if we can take
358 directly the AVPicture */
359 switch(pix_fmt) {
360 case PIX_FMT_YUV420P:
361 size = avpicture_get_size(pix_fmt, w, h);
362 buf = av_malloc(size);
363 if (!buf)
364 return;
365 dest = buf;
366 for(i=0;i<3;i++) {
367 if (i == 1) {
368 w >>= 1;
369 h >>= 1;
370 }
371 src = picture->data[i];
372 for(j=0;j<h;j++) {
373 memcpy(dest, src, w);
374 dest += w;
375 src += picture->linesize[i];
376 }
377 }
378 break;
379 case PIX_FMT_YUV422P:
380 size = (w * h) * 2;
381 buf = av_malloc(size);
382 if (!buf)
383 return;
384 dest = buf;
385 for(i=0;i<3;i++) {
386 if (i == 1) {
387 w >>= 1;
388 }
389 src = picture->data[i];
390 for(j=0;j<h;j++) {
391 memcpy(dest, src, w);
392 dest += w;
393 src += picture->linesize[i];
394 }
395 }
396 break;
397 case PIX_FMT_YUV444P:
398 size = (w * h) * 3;
399 buf = av_malloc(size);
400 if (!buf)
401 return;
402 dest = buf;
403 for(i=0;i<3;i++) {
404 src = picture->data[i];
405 for(j=0;j<h;j++) {
406 memcpy(dest, src, w);
407 dest += w;
408 src += picture->linesize[i];
409 }
410 }
411 break;
412 case PIX_FMT_YUV422:
413 size = (w * h) * 2;
414 buf = av_malloc(size);
415 if (!buf)
416 return;
417 dest = buf;
418 src = picture->data[0];
419 for(j=0;j<h;j++) {
420 memcpy(dest, src, w * 2);
421 dest += w * 2;
422 src += picture->linesize[0];
423 }
424 break;
425 case PIX_FMT_RGB24:
426 case PIX_FMT_BGR24:
427 size = (w * h) * 3;
428 buf = av_malloc(size);
429 if (!buf)
430 return;
431 dest = buf;
432 src = picture->data[0];
433 for(j=0;j<h;j++) {
434 memcpy(dest, src, w * 3);
435 dest += w * 3;
436 src += picture->linesize[0];
437 }
438 break;
439 default:
440 return;
441 }
442 s->oformat->write_packet(s, index, buf, size, 0);
443 av_free(buf);
444 }
445
446
447 static void do_video_out(AVFormatContext *s,
448 AVOutputStream *ost,
449 AVInputStream *ist,
450 AVPicture *picture1,
451 int *frame_size)
452 {
453 int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
454 AVPicture *picture, *picture2, *pict;
455 AVPicture picture_tmp1, picture_tmp2;
456 static UINT8 *video_buffer;
457 UINT8 *buf = NULL, *buf1 = NULL;
458 AVCodecContext *enc, *dec;
459
460 #define VIDEO_BUFFER_SIZE (1024*1024)
461
462 enc = &ost->st->codec;
463 dec = &ist->st->codec;
464
465 frame_number = ist->frame_number;
466 dec_frame_rate = ist->st->r_frame_rate;
467 // fprintf(stderr, "\n%d", dec_frame_rate);
468 /* first drop frame if needed */
469 n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
470 n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
471 nb = n2 - n1;
472 if (nb <= 0)
473 return;
474
475 if (!video_buffer)
476 video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
477 if(!video_buffer) return;
478
479 /* deinterlace : must be done before any resize */
480 if (do_deinterlace) {
481 int size;
482
483 /* create temporary picture */
484 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
485 buf1 = av_malloc(size);
486 if (!buf1)
487 return;
488
489 picture2 = &picture_tmp2;
490 avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
491
492 if (avpicture_deinterlace(picture2, picture1,
493 dec->pix_fmt, dec->width, dec->height) < 0) {
494 /* if error, do not deinterlace */
495 av_free(buf1);
496 buf1 = NULL;
497 picture2 = picture1;
498 }
499 } else {
500 picture2 = picture1;
501 }
502
503 /* convert pixel format if needed */
504 if (enc->pix_fmt != dec->pix_fmt) {
505 int size;
506
507 /* create temporary picture */
508 size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
509 buf = av_malloc(size);
510 if (!buf)
511 return;
512 pict = &picture_tmp1;
513 avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
514
515 if (img_convert(pict, enc->pix_fmt,
516 picture2, dec->pix_fmt,
517 dec->width, dec->height) < 0) {
518 fprintf(stderr, "pixel format conversion not handled\n");
519 goto the_end;
520 }
521 } else {
522 pict = picture2;
523 }
524
525 /* XXX: resampling could be done before raw format convertion in
526 some cases to go faster */
527 /* XXX: only works for YUV420P */
528 if (ost->video_resample) {
529 picture = &ost->pict_tmp;
530 img_resample(ost->img_resample_ctx, picture, pict);
531 } else {
532 picture = pict;
533 }
534 nb=1;
535 /* duplicates frame if needed */
536 /* XXX: pb because no interleaving */
537 for(i=0;i<nb;i++) {
538 if (enc->codec_id != CODEC_ID_RAWVIDEO) {
539 /* handles sameq here. This is not correct because it may
540 not be a global option */
541 if (same_quality) {
542 enc->quality = dec->quality;
543 }
544
545 ret = avcodec_encode_video(enc,
546 video_buffer, VIDEO_BUFFER_SIZE,
547 picture);
548 //enc->frame_number = enc->real_pict_num;
549 s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
550 *frame_size = ret;
551 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
552 // enc->frame_number-1, enc->real_pict_num, ret,
553 // enc->pict_type);
554 /* if two pass, output log */
555 if (ost->logfile && enc->stats_out) {
556 fprintf(ost->logfile, "%s", enc->stats_out);
557 }
558 } else {
559 write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
560 }
561 }
562 the_end:
563 av_free(buf);
564 av_free(buf1);
565 }
566
567 static void do_video_stats(AVOutputStream *ost,
568 AVInputStream *ist,
569 int frame_size)
570 {
571 static FILE *fvstats=NULL;
572 static INT64 total_size = 0;
573 char filename[40];
574 time_t today2;
575 struct tm *today;
576 AVCodecContext *enc;
577 int frame_number;
578 INT64 ti;
579 double ti1, bitrate, avg_bitrate;
580
581 if (!fvstats) {
582 today2 = time(NULL);
583 today = localtime(&today2);
584 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
585 today->tm_min,
586 today->tm_sec);
587 fvstats = fopen(filename,"w");
588 if (!fvstats) {
589 perror("fopen");
590 exit(1);
591 }
592 }
593
594 ti = MAXINT64;
595 enc = &ost->st->codec;
596 total_size += frame_size;
597 if (enc->codec_type == CODEC_TYPE_VIDEO) {
598 frame_number = ist->frame_number;
599 fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
600 if (do_psnr)
601 fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
602
603 fprintf(fvstats,"f_size= %6d ", frame_size);
604 /* compute min pts value */
605 if (!ist->discard && ist->pts < ti) {
606 ti = ist->pts;
607 }
608 ti1 = (double)ti / 1000000.0;
609 if (ti1 < 0.01)
610 ti1 = 0.01;
611
612 bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
613 avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
614 fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
615 (double)total_size / 1024, ti1, bitrate, avg_bitrate);
616 fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
617 }
618
619
620
621 }
622
623 /*
624 * The following code is the main loop of the file converter
625 */
626 static int av_encode(AVFormatContext **output_files,
627 int nb_output_files,
628 AVFormatContext **input_files,
629 int nb_input_files,
630 AVStreamMap *stream_maps, int nb_stream_maps)
631 {
632 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
633 AVFormatContext *is, *os;
634 AVCodecContext *codec, *icodec;
635 AVOutputStream *ost, **ost_table = NULL;
636 AVInputStream *ist, **ist_table = NULL;
637 INT64 min_pts, start_time;
638 AVInputFile *file_table;
639 AVFormatContext *stream_no_data;
640 int key;
641
642 file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
643 if (!file_table)
644 goto fail;
645
646 /* input stream init */
647 j = 0;
648 for(i=0;i<nb_input_files;i++) {
649 is = input_files[i];
650 file_table[i].ist_index = j;
651 file_table[i].nb_streams = is->nb_streams;
652 j += is->nb_streams;
653 }
654 nb_istreams = j;
655
656 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
657 if (!ist_table)
658 goto fail;
659
660 for(i=0;i<nb_istreams;i++) {
661 ist = av_mallocz(sizeof(AVInputStream));
662 if (!ist)
663 goto fail;
664 ist_table[i] = ist;
665 }
666 j = 0;
667 for(i=0;i<nb_input_files;i++) {
668 is = input_files[i];
669 for(k=0;k<is->nb_streams;k++) {
670 ist = ist_table[j++];
671 ist->st = is->streams[k];
672 ist->file_index = i;
673 ist->index = k;
674 ist->discard = 1; /* the stream is discarded by default
675 (changed later) */
676 }
677 }
678
679 /* output stream init */
680 nb_ostreams = 0;
681 for(i=0;i<nb_output_files;i++) {
682 os = output_files[i];
683 nb_ostreams += os->nb_streams;
684 if (mpeg_vcd)
685 os->flags |= AVF_FLAG_VCD;
686 }
687 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
688 fprintf(stderr, "Number of stream maps must match number of output streams\n");
689 exit(1);
690 }
691
692 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
693 if (!ost_table)
694 goto fail;
695 for(i=0;i<nb_ostreams;i++) {
696 ost = av_mallocz(sizeof(AVOutputStream));
697 if (!ost)
698 goto fail;
699 ost_table[i] = ost;
700 }
701
702 n = 0;
703 for(k=0;k<nb_output_files;k++) {
704 os = output_files[k];
705 for(i=0;i<os->nb_streams;i++) {
706 int found;
707 ost = ost_table[n++];
708 ost->file_index = k;
709 ost->index = i;
710 ost->st = os->streams[i];
711 if (nb_stream_maps > 0) {
712 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
713 stream_maps[n-1].stream_index;
714 } else {
715 /* get corresponding input stream index : we select the first one with the right type */
716 found = 0;
717 for(j=0;j<nb_istreams;j++) {
718 ist = ist_table[j];
719 if (ist->discard &&
720 ist->st->codec.codec_type == ost->st->codec.codec_type) {
721 ost->source_index = j;
722 found = 1;
723 }
724 }
725
726 if (!found) {
727 /* try again and reuse existing stream */
728 for(j=0;j<nb_istreams;j++) {
729 ist = ist_table[j];
730 if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
731 ost->source_index = j;
732 found = 1;
733 }
734 }
735 if (!found) {
736 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
737 ost->file_index, ost->index);
738 exit(1);
739 }
740 }
741 }
742 ist = ist_table[ost->source_index];
743 ist->discard = 0;
744 }
745 }
746
747 /* dump the stream mapping */
748 fprintf(stderr, "Stream mapping:\n");
749 for(i=0;i<nb_ostreams;i++) {
750 ost = ost_table[i];
751 fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
752 ist_table[ost->source_index]->file_index,
753 ist_table[ost->source_index]->index,
754 ost->file_index,
755 ost->index);
756 }
757
758 /* for each output stream, we compute the right encoding parameters */
759 for(i=0;i<nb_ostreams;i++) {
760 ost = ost_table[i];
761 ist = ist_table[ost->source_index];
762
763 codec = &ost->st->codec;
764 icodec = &ist->st->codec;
765
766 switch(codec->codec_type) {
767 case CODEC_TYPE_AUDIO:
768 /* check if same codec with same parameters. If so, no
769 reencoding is needed */
770 if (codec->codec_id == icodec->codec_id &&
771 codec->bit_rate == icodec->bit_rate &&
772 codec->sample_rate == icodec->sample_rate &&
773 codec->channels == icodec->channels) {
774 /* no reencoding */
775 /* use the same frame size */
776 codec->frame_size = icodec->frame_size;
777 //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
778 // icodec->bit_rate;
779 //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
780 } else {
781 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
782 goto fail;
783
784 if (codec->channels == icodec->channels &&
785 codec->sample_rate == icodec->sample_rate) {
786 ost->audio_resample = 0;
787 } else {
788 if (codec->channels != icodec->channels &&
789 icodec->codec_id == CODEC_ID_AC3) {
790 /* Special case for 5:1 AC3 input */
791 /* and mono or stereo output */
792 /* Request specific number of channels */
793 icodec->channels = codec->channels;
794 if (codec->sample_rate == icodec->sample_rate)
795 ost->audio_resample = 0;
796 else {
797 ost->audio_resample = 1;
798 ost->resample = audio_resample_init(codec->channels, icodec->channels,
799 codec->sample_rate,
800 icodec->sample_rate);
801 }
802 /* Request specific number of channels */
803 icodec->channels = codec->channels;
804 } else {
805 ost->audio_resample = 1;
806 ost->resample = audio_resample_init(codec->channels, icodec->channels,
807 codec->sample_rate,
808 icodec->sample_rate);
809 }
810 }
811 ist->decoding_needed = 1;
812 ost->encoding_needed = 1;
813 }
814 break;
815 case CODEC_TYPE_VIDEO:
816 /* check if same codec with same parameters. If so, no
817 reencoding is needed */
818 if (codec->codec_id == icodec->codec_id &&
819 codec->bit_rate == icodec->bit_rate &&
820 codec->frame_rate == icodec->frame_rate &&
821 codec->width == icodec->width &&
822 codec->height == icodec->height) {
823 /* no reencoding */
824 } else {
825 if (codec->width == icodec->width &&
826 codec->height == icodec->height) {
827 ost->video_resample = 0;
828 } else {
829 UINT8 *buf;
830 ost->video_resample = 1;
831 buf = av_malloc((codec->width * codec->height * 3) / 2);
832 if (!buf)
833 goto fail;
834 ost->pict_tmp.data[0] = buf;
835 ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
836 ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
837 ost->pict_tmp.linesize[0] = codec->width;
838 ost->pict_tmp.linesize[1] = codec->width / 2;
839 ost->pict_tmp.linesize[2] = codec->width / 2;
840
841 ost->img_resample_ctx = img_resample_full_init(
842 ost->st->codec.width, ost->st->codec.height,
843 ist->st->codec.width, ist->st->codec.height,
844 frame_topBand, frame_bottomBand,
845 frame_leftBand, frame_rightBand);
846 }
847 ost->encoding_needed = 1;
848 ist->decoding_needed = 1;
849 }
850 break;
851 default:
852 av_abort();
853 }
854 /* two pass mode */
855 if (ost->encoding_needed &&
856 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
857 char logfilename[1024];
858 FILE *f;
859 int size;
860 char *logbuffer;
861
862 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
863 pass_logfilename ?
864 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
865 if (codec->flags & CODEC_FLAG_PASS1) {
866 f = fopen(logfilename, "w");
867 if (!f) {
868 perror(logfilename);
869 exit(1);
870 }
871 ost->logfile = f;
872 } else {
873 /* read the log file */
874 f = fopen(logfilename, "r");
875 if (!f) {
876 perror(logfilename);
877 exit(1);
878 }
879 fseek(f, 0, SEEK_END);
880 size = ftell(f);
881 fseek(f, 0, SEEK_SET);
882 logbuffer = av_malloc(size + 1);
883 if (!logbuffer) {
884 fprintf(stderr, "Could not allocate log buffer\n");
885 exit(1);
886 }
887 fread(logbuffer, 1, size, f);
888 fclose(f);
889 logbuffer[size] = '\0';
890 codec->stats_in = logbuffer;
891 }
892 }
893 }
894
895 /* open each encoder */
896 for(i=0;i<nb_ostreams;i++) {
897 ost = ost_table[i];
898 if (ost->encoding_needed) {
899 AVCodec *codec;
900 codec = avcodec_find_encoder(ost->st->codec.codec_id);
901 if (!codec) {
902 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
903 ost->file_index, ost->index);
904 exit(1);
905 }
906 if (avcodec_open(&ost->st->codec, codec) < 0) {
907 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
908 ost->file_index, ost->index);
909 exit(1);
910 }
911 }
912 }
913
914 /* open each decoder */
915 for(i=0;i<nb_istreams;i++) {
916 ist = ist_table[i];
917 if (ist->decoding_needed) {
918 AVCodec *codec;
919 codec = avcodec_find_decoder(ist->st->codec.codec_id);
920 if (!codec) {
921 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
922 ist->file_index, ist->index);
923 exit(1);
924 }
925 if (avcodec_open(&ist->st->codec, codec) < 0) {
926 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
927 ist->file_index, ist->index);
928 exit(1);
929 }
930 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
931 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
932 }
933 }
934
935 /* init pts */
936 for(i=0;i<nb_istreams;i++) {
937 ist = ist_table[i];
938 ist->pts = 0;
939 ist->frame_number = 0;
940 }
941
942 /* compute buffer size max (should use a complete heuristic) */
943 for(i=0;i<nb_input_files;i++) {
944 file_table[i].buffer_size_max = 2048;
945 }
946
947 /* open files and write file headers */
948 for(i=0;i<nb_output_files;i++) {
949 os = output_files[i];
950 if (av_write_header(os) < 0) {
951 fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
952 ret = -EINVAL;
953 goto fail;
954 }
955 }
956
957 #ifndef CONFIG_WIN32
958 if (!do_play) {
959 fprintf(stderr, "Press [q] to stop encoding\n");
960 } else {
961 fprintf(stderr, "Press [q] to stop playing\n");
962 }
963 #endif
964 term_init();
965
966 start_time = av_gettime();
967 min_pts = 0;
968 stream_no_data = 0;
969 key = -1;
970
971 for(;;) {
972 int file_index, ist_index;
973 AVPacket pkt;
974 UINT8 *ptr;
975 int len;
976 UINT8 *data_buf;
977 int data_size, got_picture;
978 AVPicture picture;
979 short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
980
981 redo:
982 /* if 'q' pressed, exits */
983 if (key) {
984 /* read_key() returns 0 on EOF */
985 key = read_key();
986 if (key == 'q')
987 break;
988 }
989
990 /* select the input file with the smallest pts */
991 file_index = -1;
992 min_pts = MAXINT64;
993 for(i=0;i<nb_istreams;i++) {
994 ist = ist_table[i];
995 /* For some reason, the pts_increment code breaks q estimation?!? */
996 if (!ist->discard && !file_table[ist->file_index].eof_reached &&
997 ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
998 min_pts = ist->pts /* + ist->pts_increment */;
999 file_index = ist->file_index;
1000 }
1001 }
1002 /* if none, if is finished */
1003 if (file_index < 0) {
1004 if (stream_no_data) {
1005 #ifndef CONFIG_WIN32 /* no usleep in VisualC ? */
1006 #ifdef __BEOS__
1007 snooze(10 * 1000); /* mmu_man */ /* in microsec */
1008 #elif defined(__CYGWIN__)
1009 usleep(10 * 1000);
1010 #else
1011 struct timespec ts;
1012
1013 ts.tv_sec = 0;
1014 ts.tv_nsec = 1000 * 1000 * 10;
1015 nanosleep(&ts, 0);
1016 #endif
1017 #endif
1018 stream_no_data = 0;
1019 continue;
1020 }
1021 break;
1022 }
1023 /* finish if recording time exhausted */
1024 if (recording_time > 0 && min_pts >= recording_time)
1025 break;
1026 /* read a packet from it and output it in the fifo */
1027 is = input_files[file_index];
1028 if (av_read_packet(is, &pkt) < 0) {
1029 file_table[file_index].eof_reached = 1;
1030 continue;
1031 }
1032 if (!pkt.size) {
1033 stream_no_data = is;
1034 } else {
1035 stream_no_data = 0;
1036 }
1037 /* the following test is needed in case new streams appear
1038 dynamically in stream : we ignore them */
1039 if (pkt.stream_index >= file_table[file_index].nb_streams)
1040 goto discard_packet;
1041 ist_index = file_table[file_index].ist_index + pkt.stream_index;
1042 ist = ist_table[ist_index];
1043 if (ist->discard)
1044 goto discard_packet;
1045
1046 if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
1047 ist->frame_number++;
1048
1049 if (do_hex_dump) {
1050 printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
1051 av_hex_dump(pkt.data, pkt.size);
1052 }
1053
1054 // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1055
1056 len = pkt.size;
1057 ptr = pkt.data;
1058 while (len > 0) {
1059
1060 /* decode the packet if needed */
1061 data_buf = NULL; /* fail safe */
1062 data_size = 0;
1063 if (ist->decoding_needed) {
1064 switch(ist->st->codec.codec_type) {
1065 case CODEC_TYPE_AUDIO:
1066 /* XXX: could avoid copy if PCM 16 bits with same
1067 endianness as CPU */
1068 ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1069 ptr, len);
1070 if (ret < 0)
1071 goto fail_decode;
1072 /* Some bug in mpeg audio decoder gives */
1073 /* data_size < 0, it seems they are overflows */
1074 if (data_size <= 0) {
1075 /* no audio frame */
1076 ptr += ret;
1077 len -= ret;
1078 continue;
1079 }
1080 data_buf = (UINT8 *)samples;
1081 break;
1082 case CODEC_TYPE_VIDEO:
1083 if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1084 int size;
1085
1086 size = (ist->st->codec.width * ist->st->codec.height);
1087 avpicture_fill(&picture, ptr,
1088 ist->st->codec.pix_fmt,
1089 ist->st->codec.width,
1090 ist->st->codec.height);
1091 ret = len;
1092 } else {
1093 data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1094 ret = avcodec_decode_video(&ist->st->codec,
1095 &picture, &got_picture, ptr, len);
1096 if (ret < 0) {
1097 fail_decode:
1098 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1099 ist->file_index, ist->index);
1100 av_free_packet(&pkt);
1101 goto redo;
1102 }
1103 if (!got_picture) {
1104 /* no picture yet */
1105 ptr += ret;
1106 len -= ret;
1107 continue;
1108 }
1109
1110 }
1111 break;
1112 default:
1113 goto fail_decode;
1114 }
1115 } else {
1116 data_buf = ptr;
1117 data_size = len;
1118 ret = len;
1119 }
1120 /* init tickers */
1121 if (!ist->ticker_inited) {
1122 switch (ist->st->codec.codec_type) {
1123 case CODEC_TYPE_AUDIO:
1124 ticker_init(&ist->pts_ticker,
1125 (INT64)ist->st->codec.sample_rate,
1126 (INT64)(1000000));
1127 ist->ticker_inited = 1;
1128 break;
1129 case CODEC_TYPE_VIDEO:
1130 ticker_init(&ist->pts_ticker,
1131 (INT64)ist->st->r_frame_rate,
1132 ((INT64)1000000 * FRAME_RATE_BASE));
1133 ist->ticker_inited = 1;
1134 break;
1135 default:
1136 av_abort();
1137 }
1138 }
1139 /* update pts */
1140 switch(ist->st->codec.codec_type) {
1141 case CODEC_TYPE_AUDIO:
1142 //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1143 ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
1144 ist->sample_index += data_size / (2 * ist->st->codec.channels);
1145 ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1146 break;
1147 case CODEC_TYPE_VIDEO:
1148 ist->frame_number++;
1149 //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) /
1150 // ist->st->codec.frame_rate;
1151 ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
1152 ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) /
1153 ist->st->codec.frame_rate;
1154 break;
1155 default:
1156 av_abort();
1157 }
1158 ptr += ret;
1159 len -= ret;
1160
1161 /* transcode raw format, encode packets and output them */
1162
1163 for(i=0;i<nb_ostreams;i++) {
1164 int frame_size;
1165 ost = ost_table[i];
1166 if (ost->source_index == ist_index) {
1167 os = output_files[ost->file_index];
1168
1169 if (ost->encoding_needed) {
1170 switch(ost->st->codec.codec_type) {
1171 case CODEC_TYPE_AUDIO:
1172 do_audio_out(os, ost, ist, data_buf, data_size);
1173 break;
1174 case CODEC_TYPE_VIDEO:
1175 do_video_out(os, ost, ist, &picture, &frame_size);
1176 if (do_vstats)
1177 do_video_stats(ost, ist, frame_size);
1178 break;
1179 default:
1180 av_abort();
1181 }
1182 } else {
1183 /* no reencoding needed : output the packet directly */
1184 /* force the input stream PTS */
1185 os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1186 }
1187 }
1188 }
1189 }
1190 discard_packet:
1191 av_free_packet(&pkt);
1192
1193 /* dump report by using the first video and audio streams */
1194 {
1195 char buf[1024];
1196 AVFormatContext *oc;
1197 INT64 total_size, ti;
1198 AVCodecContext *enc;
1199 int frame_number, vid;
1200 double bitrate, ti1;
1201 static INT64 last_time;
1202
1203 if ((min_pts - last_time) >= 500000) {
1204 last_time = min_pts;
1205
1206 oc = output_files[0];
1207
1208 total_size = url_ftell(&oc->pb);
1209
1210 buf[0] = '\0';
1211 ti = MAXINT64;
1212 vid = 0;
1213 for(i=0;i<nb_ostreams;i++) {
1214 ost = ost_table[i];
1215 enc = &ost->st->codec;
1216 ist = ist_table[ost->source_index];
1217 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1218 frame_number = ist->frame_number;
1219 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1220 frame_number, enc->quality);
1221 if (do_psnr)
1222 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1223 vid = 1;
1224 }
1225 /* compute min pts value */
1226 if (!ist->discard && ist->pts < ti) {
1227 ti = ist->pts;
1228 }
1229 }
1230
1231 ti1 = (double)ti / 1000000.0;
1232 if (ti1 < 0.01)
1233 ti1 = 0.01;
1234 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1235
1236 sprintf(buf + strlen(buf),
1237 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1238 (double)total_size / 1024, ti1, bitrate);
1239
1240 fprintf(stderr, "%s \r", buf);
1241 fflush(stderr);
1242 }
1243 }
1244 }
1245 term_exit();
1246
1247 /* dump report by using the first video and audio streams */
1248 {
1249 char buf[1024];
1250 AVFormatContext *oc;
1251 INT64 total_size, ti;
1252 AVCodecContext *enc;
1253 int frame_number, vid;
1254 double bitrate, ti1;
1255
1256 oc = output_files[0];
1257
1258 total_size = url_ftell(&oc->pb);
1259
1260 buf[0] = '\0';
1261 ti = MAXINT64;
1262 vid = 0;
1263 for(i=0;i<nb_ostreams;i++) {
1264 ost = ost_table[i];
1265 enc = &ost->st->codec;
1266 ist = ist_table[ost->source_index];
1267 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1268 frame_number = ist->frame_number;
1269 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1270 frame_number, enc->quality);
1271 if (do_psnr)
1272 sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1273 vid = 1;
1274 }
1275 /* compute min pts value */
1276 if (!ist->discard && ist->pts < ti) {
1277 ti = ist->pts;
1278 }
1279 }
1280
1281 ti1 = ti / 1000000.0;
1282 if (ti1 < 0.01)
1283 ti1 = 0.01;
1284 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1285
1286 sprintf(buf + strlen(buf),
1287 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1288 (double)total_size / 1024, ti1, bitrate);
1289
1290 fprintf(stderr, "%s \n", buf);
1291 }
1292 /* close each encoder */
1293 for(i=0;i<nb_ostreams;i++) {
1294 ost = ost_table[i];
1295 if (ost->encoding_needed) {
1296 av_freep(&ost->st->codec.stats_in);
1297 avcodec_close(&ost->st->codec);
1298 }
1299 }
1300
1301 /* close each decoder */
1302 for(i=0;i<nb_istreams;i++) {
1303 ist = ist_table[i];
1304 if (ist->decoding_needed) {
1305 avcodec_close(&ist->st->codec);
1306 }
1307 }
1308
1309
1310 /* write the trailer if needed and close file */
1311 for(i=0;i<nb_output_files;i++) {
1312 os = output_files[i];
1313 av_write_trailer(os);
1314 }
1315 /* finished ! */
1316
1317 ret = 0;
1318 fail1:
1319 av_free(file_table);
1320
1321 if (ist_table) {
1322 for(i=0;i<nb_istreams;i++) {
1323 ist = ist_table[i];
1324 av_free(ist);
1325 }
1326 av_free(ist_table);
1327 }
1328 if (ost_table) {
1329 for(i=0;i<nb_ostreams;i++) {
1330 ost = ost_table[i];
1331 if (ost) {
1332 if (ost->logfile) {
1333 fclose(ost->logfile);
1334 ost->logfile = NULL;
1335 }
1336 fifo_free(&ost->fifo); /* works even if fifo is not
1337 initialized but set to zero */
1338 av_free(ost->pict_tmp.data[0]);
1339 if (ost->video_resample)
1340 img_resample_close(ost->img_resample_ctx);
1341 if (ost->audio_resample)
1342 audio_resample_close(ost->resample);
1343 av_free(ost);
1344 }
1345 }
1346 av_free(ost_table);
1347 }
1348 return ret;
1349 fail:
1350 ret = -ENOMEM;
1351 goto fail1;
1352 }
1353
1354 #if 0
1355 int file_read(const char *filename)
1356 {
1357 URLContext *h;
1358 unsigned char buffer[1024];
1359 int len, i;
1360
1361 if (url_open(&h, filename, O_RDONLY) < 0) {
1362 printf("could not open '%s'\n", filename);
1363 return -1;
1364 }
1365 for(;;) {
1366 len = url_read(h, buffer, sizeof(buffer));
1367 if (len <= 0)
1368 break;
1369 for(i=0;i<len;i++) putchar(buffer[i]);
1370 }
1371 url_close(h);
1372 return 0;
1373 }
1374 #endif
1375
1376 void show_licence(void)
1377 {
1378 printf(
1379 "ffmpeg version " FFMPEG_VERSION "\n"
1380 "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1381 "This library is free software; you can redistribute it and/or\n"
1382 "modify it under the terms of the GNU Lesser General Public\n"
1383 "License as published by the Free Software Foundation; either\n"
1384 "version 2 of the License, or (at your option) any later version.\n"
1385 "\n"
1386 "This library is distributed in the hope that it will be useful,\n"
1387 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1388 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1389 "Lesser General Public License for more details.\n"
1390 "\n"
1391 "You should have received a copy of the GNU Lesser General Public\n"
1392 "License along with this library; if not, write to the Free Software\n"
1393 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
1394 );
1395 exit(1);
1396 }
1397
1398 void opt_format(const char *arg)
1399 {
1400 file_iformat = av_find_input_format(arg);
1401 file_oformat = guess_format(arg, NULL, NULL);
1402 if (!file_iformat && !file_oformat) {
1403 fprintf(stderr, "Unknown input or output format: %s\n", arg);
1404 exit(1);
1405 }
1406 }
1407
1408 void opt_video_bitrate(const char *arg)
1409 {
1410 video_bit_rate = atoi(arg) * 1000;
1411 }
1412
1413 void opt_video_bitrate_tolerance(const char *arg)
1414 {
1415 video_bit_rate_tolerance = atoi(arg) * 1000;
1416 }
1417
1418 void opt_video_bitrate_max(const char *arg)
1419 {
1420 video_rc_max_rate = atoi(arg) * 1000;
1421 }
1422
1423 void opt_video_bitrate_min(const char *arg)
1424 {
1425 video_rc_min_rate = atoi(arg) * 1000;
1426 }
1427
1428 void opt_video_buffer_size(const char *arg)
1429 {
1430 video_rc_buffer_size = atoi(arg) * 1000;
1431 }
1432
1433 void opt_video_rc_eq(char *arg)
1434 {
1435 video_rc_eq = arg;
1436 }
1437
1438
1439 void opt_workaround_bugs(const char *arg)
1440 {
1441 workaround_bugs = atoi(arg);
1442 }
1443
1444 void opt_dct_algo(const char *arg)
1445 {
1446 dct_algo = atoi(arg);
1447 }
1448
1449 void opt_idct_algo(const char *arg)
1450 {
1451 idct_algo = atoi(arg);
1452 }
1453
1454
1455 void opt_error_resilience(const char *arg)
1456 {
1457 error_resilience = atoi(arg);
1458 }
1459
1460 void opt_frame_rate(const char *arg)
1461 {
1462 frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1463 }
1464
1465
1466 void opt_frame_crop_top(const char *arg)
1467 {
1468 frame_topBand = atoi(arg);
1469 if (frame_topBand < 0) {
1470 fprintf(stderr, "Incorrect top crop size\n");
1471 exit(1);
1472 }
1473 if ((frame_topBand % 2) != 0) {
1474 fprintf(stderr, "Top crop size must be a multiple of 2\n");
1475 exit(1);
1476 }
1477 if ((frame_topBand) >= frame_height){
1478 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1479 exit(1);
1480 }
1481 frame_height -= frame_topBand;
1482 }
1483
1484 void opt_frame_crop_bottom(const char *arg)
1485 {
1486 frame_bottomBand = atoi(arg);
1487 if (frame_bottomBand < 0) {
1488 fprintf(stderr, "Incorrect bottom crop size\n");
1489 exit(1);
1490 }
1491 if ((frame_bottomBand % 2) != 0) {
1492 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
1493 exit(1);
1494 }
1495 if ((frame_bottomBand) >= frame_height){
1496 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1497 exit(1);
1498 }
1499 frame_height -= frame_bottomBand;
1500 }
1501
1502 void opt_frame_crop_left(const char *arg)
1503 {
1504 frame_leftBand = atoi(arg);
1505 if (frame_leftBand < 0) {
1506 fprintf(stderr, "Incorrect left crop size\n");
1507 exit(1);
1508 }
1509 if ((frame_leftBand % 2) != 0) {
1510 fprintf(stderr, "Left crop size must be a multiple of 2\n");
1511 exit(1);
1512 }
1513 if ((frame_leftBand) >= frame_width){
1514 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1515 exit(1);
1516 }
1517 frame_width -= frame_leftBand;
1518 }
1519
1520 void opt_frame_crop_right(const char *arg)
1521 {
1522 frame_rightBand = atoi(arg);
1523 if (frame_rightBand < 0) {
1524 fprintf(stderr, "Incorrect right crop size\n");
1525 exit(1);
1526 }
1527 if ((frame_rightBand % 2) != 0) {
1528 fprintf(stderr, "Right crop size must be a multiple of 2\n");
1529 exit(1);
1530 }
1531 if ((frame_rightBand) >= frame_width){
1532 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
1533 exit(1);
1534 }
1535 frame_width -= frame_rightBand;
1536 }
1537
1538 void opt_frame_size(const char *arg)
1539 {
1540 parse_image_size(&frame_width, &frame_height, arg);
1541 if (frame_width <= 0 || frame_height <= 0) {
1542 fprintf(stderr, "Incorrect frame size\n");
1543 exit(1);
1544 }
1545 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1546 fprintf(stderr, "Frame size must be a multiple of 2\n");
1547 exit(1);
1548 }
1549 }
1550
1551 void opt_gop_size(const char *arg)
1552 {
1553 gop_size = atoi(arg);
1554 }
1555
1556 void opt_b_frames(const char *arg)
1557 {
1558 b_frames = atoi(arg);
1559 if (b_frames > FF_MAX_B_FRAMES) {
1560 fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1561 exit(1);
1562 } else if (b_frames < 1) {
1563 fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1564 exit(1);
1565 }
1566 }
1567
1568 void opt_qscale(const char *arg)
1569 {
1570 video_qscale = atoi(arg);
1571 if (video_qscale < 0 ||
1572 video_qscale > 31) {
1573 fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1574 exit(1);
1575 }
1576 }
1577
1578 void opt_qmin(const char *arg)
1579 {
1580 video_qmin = atoi(arg);
1581 if (video_qmin < 0 ||
1582 video_qmin > 31) {
1583 fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1584 exit(1);
1585 }
1586 }
1587
1588 void opt_qmax(const char *arg)
1589 {
1590 video_qmax = atoi(arg);
1591 if (video_qmax < 0 ||
1592 video_qmax > 31) {
1593 fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1594 exit(1);
1595 }
1596 }
1597
1598 void opt_qdiff(const char *arg)
1599 {
1600 video_qdiff = atoi(arg);
1601 if (video_qdiff < 0 ||
1602 video_qdiff > 31) {
1603 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1604 exit(1);
1605 }
1606 }
1607
1608 void opt_qblur(const char *arg)
1609 {
1610 video_qblur = atof(arg);
1611 }
1612
1613 void opt_qcomp(const char *arg)
1614 {
1615 video_qcomp = atof(arg);
1616 }
1617
1618 void opt_b_qfactor(const char *arg)
1619 {
1620 video_b_qfactor = atof(arg);
1621 }
1622 void opt_i_qfactor(const char *arg)
1623 {
1624 video_i_qfactor = atof(arg);
1625 }
1626 void opt_b_qoffset(const char *arg)
1627 {
1628 video_b_qoffset = atof(arg);
1629 }
1630 void opt_i_qoffset(const char *arg)
1631 {
1632 video_i_qoffset = atof(arg);
1633 }
1634
1635 void opt_packet_size(const char *arg)
1636 {
1637 packet_size= atoi(arg);
1638 }
1639
1640 void opt_audio_bitrate(const char *arg)
1641 {
1642 audio_bit_rate = atoi(arg) * 1000;
1643 }
1644
1645 void opt_audio_rate(const char *arg)
1646 {
1647 audio_sample_rate = atoi(arg);
1648 }
1649
1650 void opt_audio_channels(const char *arg)
1651 {
1652 audio_channels = atoi(arg);
1653 }
1654
1655 void opt_video_device(const char *arg)
1656 {
1657 v4l_device = strdup(arg);
1658 }
1659
1660 void opt_audio_device(const char *arg)
1661 {
1662 audio_device = strdup(arg);
1663 }
1664
1665 void opt_audio_codec(const char *arg)
1666 {
1667 AVCodec *p;
1668
1669 p = first_avcodec;
1670 while (p) {
1671 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1672 break;
1673 p = p->next;
1674 }
1675 if (p == NULL) {
1676 fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1677 exit(1);
1678 } else {
1679 audio_codec_id = p->id;
1680 }
1681 }
1682
1683 const char *motion_str[] = {
1684 "zero",
1685 "full",
1686 "log",
1687 "phods",
1688 "epzs",
1689 "x1",
1690 NULL,
1691 };
1692
1693 void opt_motion_estimation(const char *arg)
1694 {
1695 const char **p;
1696 p = motion_str;
1697 for(;;) {
1698 if (!*p) {
1699 fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1700 exit(1);
1701 }
1702 if (!strcmp(*p, arg))
1703 break;
1704 p++;
1705 }
1706 me_method = (p - motion_str) + 1;
1707 }
1708
1709 void opt_video_codec(const char *arg)
1710 {
1711 AVCodec *p;
1712
1713 p = first_avcodec;
1714 while (p) {
1715 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1716 break;
1717 p = p->next;
1718 }
1719 if (p == NULL) {
1720 fprintf(stderr, "Unknown video codec '%s'\n", arg);
1721 exit(1);
1722 } else {
1723 video_codec_id = p->id;
1724 }
1725 }
1726
1727 void opt_map(const char *arg)
1728 {
1729 AVStreamMap *m;
1730 const char *p;
1731
1732 p = arg;
1733 m = &stream_maps[nb_stream_maps++];
1734
1735 m->file_index = strtol(arg, (char **)&p, 0);
1736 if (*p)
1737 p++;
1738
1739 m->stream_index = strtol(p, (char **)&p, 0);
1740 }
1741
1742 void opt_recording_time(const char *arg)
1743 {
1744 recording_time = parse_date(arg, 1);
1745 }
1746
1747 void print_error(const char *filename, int err)
1748 {
1749 switch(err) {
1750 case AVERROR_NUMEXPECTED:
1751 fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1752 "Use '%%d' to specify the image number:\n"
1753 " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1754 " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
1755 filename);
1756 break;
1757 case AVERROR_INVALIDDATA:
1758 fprintf(stderr, "%s: Error while parsing header\n", filename);
1759 break;
1760 case AVERROR_NOFMT:
1761 fprintf(stderr, "%s: Unknown format\n", filename);
1762 break;
1763 default:
1764 fprintf(stderr, "%s: Error while opening file\n", filename);
1765 break;
1766 }
1767 }
1768
1769 void opt_input_file(const char *filename)
1770 {
1771 AVFormatContext *ic;
1772 AVFormatParameters params, *ap = &params;
1773 int err, i, ret, rfps;
1774
1775 /* get default parameters from command line */
1776 memset(ap, 0, sizeof(*ap));
1777 ap->sample_rate = audio_sample_rate;
1778 ap->channels = audio_channels;
1779 ap->frame_rate = frame_rate;
1780 ap->width = frame_width;
1781 ap->height = frame_height;
1782
1783 /* open the input file with generic libav function */
1784 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1785 if (err < 0) {
1786 print_error(filename, err);
1787 exit(1);
1788 }
1789
1790 /* If not enough info to get the stream parameters, we decode the
1791 first frames to get it. (used in mpeg case for example) */
1792 ret = av_find_stream_info(ic);
1793 if (ret < 0) {
1794 fprintf(stderr, "%s: could not find codec parameters\n", filename);
1795 exit(1);
1796 }
1797
1798 /* update the current parameters so that they match the one of the input stream */
1799 for(i=0;i<ic->nb_streams;i++) {
1800 AVCodecContext *enc = &ic->streams[i]->codec;
1801 switch(enc->codec_type) {
1802 case CODEC_TYPE_AUDIO:
1803 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1804 audio_channels = enc->channels;
1805 audio_sample_rate = enc->sample_rate;
1806 break;
1807 case CODEC_TYPE_VIDEO:
1808 frame_height = enc->height;
1809 frame_width = enc->width;
1810 rfps = ic->streams[i]->r_frame_rate;
1811 enc->workaround_bugs = workaround_bugs;
1812 enc->error_resilience = error_resilience;
1813 enc->idct_algo= idct_algo;
1814 if (enc->frame_rate != rfps) {
1815 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1816 i, (float)enc->frame_rate / FRAME_RATE_BASE,
1817 (float)rfps / FRAME_RATE_BASE);
1818 }
1819 /* update the current frame rate to match the stream frame rate */
1820 frame_rate = rfps;
1821 break;
1822 default:
1823 av_abort();
1824 }
1825 }
1826
1827 input_files[nb_input_files] = ic;
1828 /* dump the file content */
1829 dump_format(ic, nb_input_files, filename, 0);
1830 nb_input_files++;
1831 file_iformat = NULL;
1832 file_oformat = NULL;
1833 }
1834
1835 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1836 {
1837 int has_video, has_audio, i, j;
1838 AVFormatContext *ic;
1839
1840 has_video = 0;
1841 has_audio = 0;
1842 for(j=0;j<nb_input_files;j++) {
1843 ic = input_files[j];
1844 for(i=0;i<ic->nb_streams;i++) {
1845 AVCodecContext *enc = &ic->streams[i]->codec;
1846 switch(enc->codec_type) {
1847 case CODEC_TYPE_AUDIO:
1848 has_audio = 1;
1849 break;
1850 case CODEC_TYPE_VIDEO:
1851 has_video = 1;
1852 break;
1853 default:
1854 av_abort();
1855 }
1856 }
1857 }
1858 *has_video_ptr = has_video;
1859 *has_audio_ptr = has_audio;
1860 }
1861
1862 void opt_output_file(const char *filename)
1863 {
1864 AVStream *st;
1865 AVFormatContext *oc;
1866 int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1867 int codec_id;
1868
1869 if (!strcmp(filename, "-"))
1870 filename = "pipe:";
1871
1872 oc = av_mallocz(sizeof(AVFormatContext));
1873
1874 if (!file_oformat) {
1875 file_oformat = guess_format(NULL, filename, NULL);
1876 if (!file_oformat) {
1877 fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1878 filename);
1879 exit(1);
1880 }
1881 }
1882
1883 oc->oformat = file_oformat;
1884
1885 if (!strcmp(file_oformat->name, "ffm") &&
1886 strstart(filename, "http:", NULL)) {
1887 /* special case for files sent to ffserver: we get the stream
1888 parameters from ffserver */
1889 if (read_ffserver_streams(oc, filename) < 0) {
1890 fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1891 exit(1);
1892 }
1893 } else {
1894 use_video = file_oformat->video_codec != CODEC_ID_NONE;
1895 use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1896
1897 /* disable if no corresponding type found and at least one
1898 input file */
1899 if (nb_input_files > 0) {
1900 check_audio_video_inputs(&input_has_video, &input_has_audio);
1901 if (!input_has_video)
1902 use_video = 0;
1903 if (!input_has_audio)
1904 use_audio = 0;
1905 }
1906
1907 /* manual disable */
1908 if (audio_disable) {
1909 use_audio = 0;
1910 }
1911 if (video_disable) {
1912 use_video = 0;
1913 }
1914
1915 nb_streams = 0;
1916 if (use_video) {
1917 AVCodecContext *video_enc;
1918
1919 st = av_mallocz(sizeof(AVStream));
1920 if (!st) {
1921 fprintf(stderr, "Could not alloc stream\n");
1922 exit(1);
1923 }
1924 video_enc = &st->codec;
1925
1926 codec_id = file_oformat->video_codec;
1927 if (video_codec_id != CODEC_ID_NONE)
1928 codec_id = video_codec_id;
1929
1930 video_enc->codec_id = codec_id;
1931 video_enc->codec_type = CODEC_TYPE_VIDEO;
1932
1933 video_enc->bit_rate = video_bit_rate;
1934 video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1935 video_enc->frame_rate = frame_rate;
1936
1937 video_enc->width = frame_width;
1938 video_enc->height = frame_height;
1939 if (!intra_only)
1940 video_enc->gop_size = gop_size;
1941 else
1942 video_enc->gop_size = 0;
1943 if (video_qscale || same_quality) {
1944 video_enc->flags |= CODEC_FLAG_QSCALE;
1945 video_enc->quality = video_qscale;
1946 }
1947
1948 if (use_hq) {
1949 video_enc->flags |= CODEC_FLAG_HQ;
1950 }
1951
1952 if (use_4mv) {
1953 video_enc->flags |= CODEC_FLAG_HQ;
1954 video_enc->flags |= CODEC_FLAG_4MV;
1955 }
1956
1957 if(use_part)
1958 video_enc->flags |= CODEC_FLAG_PART;
1959
1960
1961 if (b_frames) {
1962 if (codec_id != CODEC_ID_MPEG4) {
1963 fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1964 exit(1);
1965 }
1966 video_enc->max_b_frames = b_frames;
1967 video_enc->b_frame_strategy = 0;
1968 video_enc->b_quant_factor = 2.0;
1969 }
1970
1971 video_enc->qmin = video_qmin;
1972 video_enc->qmax = video_qmax;
1973 video_enc->max_qdiff = video_qdiff;
1974 video_enc->qblur = video_qblur;
1975 video_enc->qcompress = video_qcomp;
1976 video_enc->rc_eq = video_rc_eq;
1977 video_enc->rc_max_rate = video_rc_max_rate;
1978 video_enc->rc_min_rate = video_rc_min_rate;
1979 video_enc->rc_buffer_size = video_rc_buffer_size;
1980 video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
1981 video_enc->i_quant_factor = video_i_qfactor;
1982 video_enc->b_quant_factor = video_b_qfactor;
1983 video_enc->i_quant_offset = video_i_qoffset;
1984 video_enc->b_quant_offset = video_b_qoffset;
1985 video_enc->dct_algo = dct_algo;
1986 video_enc->idct_algo = idct_algo;
1987 if(packet_size){
1988 video_enc->rtp_mode= 1;
1989 video_enc->rtp_payload_size= packet_size;
1990 }
1991
1992 if (do_psnr)
1993 video_enc->get_psnr = 1;
1994 else
1995 video_enc->get_psnr = 0;
1996
1997 video_enc->me_method = me_method;
1998
1999 /* two pass mode */
2000 if (do_pass) {
2001 if (do_pass == 1) {
2002 video_enc->flags |= CODEC_FLAG_PASS1;
2003 } else {
2004 video_enc->flags |= CODEC_FLAG_PASS2;
2005 }
2006 }
2007
2008 /* XXX: need to find a way to set codec parameters */
2009 if (oc->oformat->flags & AVFMT_RGB24) {
2010 video_enc->pix_fmt = PIX_FMT_RGB24;
2011 }
2012
2013 oc->streams[nb_streams] = st;
2014 nb_streams++;
2015 }
2016
2017 if (use_audio) {
2018 AVCodecContext *audio_enc;
2019
2020 st = av_mallocz(sizeof(AVStream));
2021 if (!st) {
2022 fprintf(stderr, "Could not alloc stream\n");
2023 exit(1);
2024 }
2025 audio_enc = &st->codec;
2026 codec_id = file_oformat->audio_codec;
2027 if (audio_codec_id != CODEC_ID_NONE)
2028 codec_id = audio_codec_id;
2029 audio_enc->codec_id = codec_id;
2030 audio_enc->codec_type = CODEC_TYPE_AUDIO;
2031
2032 audio_enc->bit_rate = audio_bit_rate;
2033 audio_enc->sample_rate = audio_sample_rate;
2034 /* For audio codecs other than AC3 we limit */
2035 /* the number of coded channels to stereo */
2036 if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
2037 audio_enc->channels = 2;
2038 } else
2039 audio_enc->channels = audio_channels;
2040 oc->streams[nb_streams] = st;
2041 nb_streams++;
2042 }
2043
2044 oc->nb_streams = nb_streams;
2045
2046 if (!nb_streams) {
2047 fprintf(stderr, "No audio or video streams available\n");
2048 exit(1);
2049 }
2050
2051 if (str_title)
2052 pstrcpy(oc->title, sizeof(oc->title), str_title);
2053 if (str_author)
2054 pstrcpy(oc->author, sizeof(oc->author), str_author);
2055 if (str_copyright)
2056 pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
2057 if (str_comment)
2058 pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
2059 }
2060
2061 output_files[nb_output_files] = oc;
2062 /* dump the file content */
2063 dump_format(oc, nb_output_files, filename, 1);
2064 nb_output_files++;
2065
2066 strcpy(oc->filename, filename);
2067
2068 /* check filename in case of an image number is expected */
2069 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2070 if (filename_number_test(oc->filename) < 0) {
2071 print_error(oc->filename, AVERROR_NUMEXPECTED);
2072 exit(1);
2073 }
2074 }
2075
2076 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2077 /* test if it already exists to avoid loosing precious files */
2078 if (!file_overwrite &&
2079 (strchr(filename, ':') == NULL ||
2080 strstart(filename, "file:", NULL))) {
2081 if (url_exist(filename)) {
2082 int c;
2083
2084 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
2085 fflush(stdout);
2086 c = getchar();
2087 if (toupper(c) != 'Y') {
2088 fprintf(stderr, "Not overwriting - exiting\n");
2089 exit(1);
2090 }
2091 }
2092 }
2093
2094 /* open the file */
2095 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
2096 fprintf(stderr, "Could not open '%s'\n", filename);
2097 exit(1);
2098 }
2099 }
2100
2101 /* reset some options */
2102 file_oformat = NULL;
2103 file_iformat = NULL;
2104 audio_disable = 0;
2105 video_disable = 0;
2106 audio_codec_id = CODEC_ID_NONE;
2107 video_codec_id = CODEC_ID_NONE;
2108 }
2109
2110 /* prepare dummy protocols for grab */
2111 void prepare_grab(void)
2112 {
2113 int has_video, has_audio, i, j;
2114 AVFormatContext *oc;
2115 AVFormatContext *ic;
2116 AVFormatParameters ap1, *ap = &ap1;
2117
2118 /* see if audio/video inputs are needed */
2119 has_video = 0;
2120 has_audio = 0;
2121 memset(ap, 0, sizeof(*ap));
2122 for(j=0;j<nb_output_files;j++) {
2123 oc = output_files[j];
2124 for(i=0;i<oc->nb_streams;i++) {
2125 AVCodecContext *enc = &oc->streams[i]->codec;
2126 switch(enc->codec_type) {
2127 case CODEC_TYPE_AUDIO:
2128 if (enc->sample_rate > ap->sample_rate)
2129 ap->sample_rate = enc->sample_rate;
2130 if (enc->channels > ap->channels)
2131 ap->channels = enc->channels;
2132 has_audio = 1;
2133 break;
2134 case CODEC_TYPE_VIDEO:
2135 if (enc->width > ap->width)
2136 ap->width = enc->width;
2137 if (enc->height > ap->height)
2138 ap->height = enc->height;
2139 if (enc->frame_rate > ap->frame_rate)
2140 ap->frame_rate = enc->frame_rate;
2141 has_video = 1;
2142 break;
2143 default:
2144 av_abort();
2145 }
2146 }
2147 }
2148
2149 if (has_video == 0 && has_audio == 0) {
2150 fprintf(stderr, "Output file must have at least one audio or video stream\n");
2151 exit(1);
2152 }
2153
2154 if (has_video) {
2155 AVInputFormat *fmt1;
2156 fmt1 = av_find_input_format("video_grab_device");
2157 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2158 fprintf(stderr, "Could not find video grab device\n");
2159 exit(1);
2160 }
2161 /* by now video grab has one stream */
2162 ic->streams[0]->r_frame_rate = ap->frame_rate;
2163 input_files[nb_input_files] = ic;
2164 dump_format(ic, nb_input_files, v4l_device, 0);
2165 nb_input_files++;
2166 }
2167 if (has_audio) {
2168 AVInputFormat *fmt1;
2169 fmt1 = av_find_input_format("audio_device");
2170 if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
2171 fprintf(stderr, "Could not find audio grab device\n");
2172 exit(1);
2173 }
2174 input_files[nb_input_files] = ic;
2175 dump_format(ic, nb_input_files, audio_device, 0);
2176 nb_input_files++;
2177 }
2178 }
2179
2180 /* open the necessary output devices for playing */
2181 void prepare_play(void)
2182 {
2183 file_iformat = NULL;
2184 file_oformat = guess_format("audio_device", NULL, NULL);
2185 if (!file_oformat) {
2186 fprintf(stderr, "Could not find audio device\n");
2187 exit(1);
2188 }
2189
2190 opt_output_file(audio_device);
2191 }
2192
2193 /* same option as mencoder */
2194 void opt_pass(const char *pass_str)
2195 {
2196 int pass;
2197 pass = atoi(pass_str);
2198 if (pass != 1 && pass != 2) {
2199 fprintf(stderr, "pass number can be only 1 or 2\n");
2200 exit(1);
2201 }
2202 do_pass = pass;
2203 }
2204
2205 #ifndef CONFIG_WIN32
2206 INT64 getutime(void)
2207 {
2208 struct rusage rusage;
2209
2210 getrusage(RUSAGE_SELF, &rusage);
2211 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2212 }
2213 #else
2214 INT64 getutime(void)
2215 {
2216 return av_gettime();
2217 }
2218 #endif
2219
2220 extern int ffm_nopts;
2221
2222 void opt_bitexact(void)
2223 {
2224 avcodec_set_bit_exact();
2225 /* disable generate of real time pts in ffm (need to be supressed anyway) */
2226 ffm_nopts = 1;
2227 }
2228
2229 void show_formats(void)
2230 {
2231 AVInputFormat *ifmt;
2232 AVOutputFormat *ofmt;
2233 URLProtocol *up;
2234 AVCodec *p;
2235 const char **pp;
2236
2237 printf("File formats:\n");
2238 printf(" Encoding:");
2239 for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2240 printf(" %s", ofmt->name);
2241 }
2242 printf("\n");
2243 printf(" Decoding:");
2244 for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2245 printf(" %s", ifmt->name);
2246 }
2247 printf("\n");
2248
2249 printf("Codecs:\n");
2250 printf(" Encoders:");
2251 for(p = first_avcodec; p != NULL; p = p->next) {
2252 if (p->encode)
2253 printf(" %s", p->name);
2254 }
2255 printf("\n");
2256
2257 printf(" Decoders:");
2258 for(p = first_avcodec; p != NULL; p = p->next) {
2259 if (p->decode)
2260 printf(" %s", p->name);
2261 }
2262 printf("\n");
2263
2264 printf("Supported file protocols:");
2265 for(up = first_protocol; up != NULL; up = up->next)
2266 printf(" %s:", up->name);
2267 printf("\n");
2268
2269 printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2270 printf("Motion estimation methods:");
2271 pp = motion_str;
2272 while (*pp) {
2273 printf(" %s", *pp);
2274 if ((pp - motion_str + 1) == ME_ZERO)
2275 printf("(fastest)");
2276 else if ((pp - motion_str + 1) == ME_FULL)
2277 printf("(slowest)");
2278 else if ((pp - motion_str + 1) == ME_EPZS)
2279 printf("(default)");
2280 pp++;
2281 }
2282 printf("\n");
2283 exit(1);
2284 }
2285
2286 void show_help(void)
2287 {
2288 const char *prog;
2289 const OptionDef *po;
2290 int i, expert;
2291
2292 prog = do_play ? "ffplay" : "ffmpeg";
2293
2294 printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2295 prog);
2296
2297 if (!do_play) {
2298 printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2299 "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2300 } else {
2301 printf("usage: ffplay [options] input_file...\n"
2302 "Simple audio player\n");
2303 }
2304
2305 printf("\n"
2306 "Main options are:\n");
2307 for(i=0;i<2;i++) {
2308 if (i == 1)
2309 printf("\nAdvanced options are:\n");
2310 for(po = options; po->name != NULL; po++) {
2311 char buf[64];
2312 expert = (po->flags & OPT_EXPERT) != 0;
2313 if (expert == i) {
2314 strcpy(buf, po->name);
2315 if (po->flags & HAS_ARG) {
2316 strcat(buf, " ");
2317 strcat(buf, po->argname);
2318 }
2319 printf("-%-17s %s\n", buf, po->help);
2320 }
2321 }
2322 }
2323
2324 exit(1);
2325 }
2326
2327 const OptionDef options[] = {
2328 { "L", 0, {(void*)show_licence}, "show license" },
2329 { "h", 0, {(void*)show_help}, "show help" },
2330 { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2331 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2332 { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2333 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2334 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2335 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2336 { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2337 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2338 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2339 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2340 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2341 { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
2342 { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
2343 /* video options */
2344 { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2345 { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2346 { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2347 { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
2348 { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
2349 { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
2350 { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
2351 { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2352 { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2353 { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2354 { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2355 { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2356 { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2357 { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2358 { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2359 { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2360 { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
2361 { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
2362 { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
2363 { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
2364 { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2365 { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2366 { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2367 { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2368 { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
2369 { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2370 { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2371 { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
2372 "method" },
2373 { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
2374 { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
2375 { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
2376 { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2377 { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2378 { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2379 { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
2380 { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2381 { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
2382 { "sameq", OPT_BOOL, {(void*)&same_quality},
2383 "use same video quality as source (implies VBR)" },
2384 /* audio options */
2385 { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2386 { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2387 { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2388 { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2389 { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2390 { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2391 { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
2392 "deinterlace pictures" },
2393 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
2394 "add timings for benchmarking" },
2395 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
2396 "dump each input packet" },
2397 { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2398 { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
2399 { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
2400 { NULL, },
2401 };
2402
2403 int main(int argc, char **argv)
2404 {
2405 int optindex, i;
2406 const char *opt, *arg;
2407 const OptionDef *po;
2408 INT64 ti;
2409
2410 av_register_all();
2411
2412 /* detect if invoked as player */
2413 i = strlen(argv[0]);
2414 if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2415 do_play = 1;
2416
2417 if (argc <= 1)
2418 show_help();
2419
2420 /* parse options */
2421 optindex = 1;
2422 while (optindex < argc) {
2423 opt = argv[optindex++];
2424
2425 if (opt[0] == '-' && opt[1] != '\0') {
2426 po = options;
2427 while (po->name != NULL) {
2428 if (!strcmp(opt + 1, po->name))
2429 break;
2430 po++;
2431 }
2432 if (!po->name) {
2433 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2434 exit(1);
2435 }
2436 arg = NULL;
2437 if (po->flags & HAS_ARG)
2438 arg = argv[optindex++];
2439 if (po->flags & OPT_STRING) {
2440 char *str;
2441 str = strdup(arg);
2442 *po->u.str_arg = str;
2443 } else if (po->flags & OPT_BOOL) {
2444 *po->u.int_arg = 1;
2445 } else {
2446 po->u.func_arg(arg);
2447 }
2448 } else {
2449 if (!do_play) {
2450 opt_output_file(opt);
2451 } else {
2452 opt_input_file(opt);
2453 }
2454 }
2455 }
2456
2457
2458 if (!do_play) {
2459 /* file converter / grab */
2460 if (nb_output_files <= 0) {
2461 fprintf(stderr, "Must supply at least one output file\n");
2462 exit(1);
2463 }
2464
2465 if (nb_input_files == 0) {
2466 prepare_grab();
2467 }
2468 } else {
2469 /* player */
2470 if (nb_input_files <= 0) {
2471 fprintf(stderr, "Must supply at least one input file\n");
2472 exit(1);
2473 }
2474 prepare_play();
2475 }
2476
2477 ti = getutime();
2478 av_encode(output_files, nb_output_files, input_files, nb_input_files,
2479 stream_maps, nb_stream_maps);
2480 ti = getutime() - ti;
2481 if (do_benchmark) {
2482 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2483 }
2484
2485 /* close files */
2486 for(i=0;i<nb_output_files;i++) {
2487 if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
2488 url_fclose(&output_files[i]->pb);
2489 }
2490 for(i=0;i<nb_input_files;i++)
2491 av_close_input_file(input_files[i]);
2492
2493 return 0;
2494 }