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