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