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