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