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