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