3 * Copyright (c) 2000-2003 Fabrice Bellard
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.
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.
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
19 #define HAVE_AV_CONFIG_H
22 #include "framehook.h"
28 #include <sys/ioctl.h>
31 #include <sys/resource.h>
35 #include <sys/types.h>
36 #include <sys/select.h>
39 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
47 #if !defined(INFINITY) && defined(HUGE_VAL)
48 #define INFINITY HUGE_VAL
51 /* select an input stream for an output stream */
52 typedef struct AVStreamMap
{
56 int sync_stream_index
;
59 /** select an input file for an output file */
60 typedef struct AVMetaDataMap
{
65 extern const OptionDef options
[];
67 static void show_help(void);
68 static void show_license(void);
72 static AVFormatContext
*input_files
[MAX_FILES
];
73 static int64_t input_files_ts_offset
[MAX_FILES
];
74 static int nb_input_files
= 0;
76 static AVFormatContext
*output_files
[MAX_FILES
];
77 static int nb_output_files
= 0;
79 static AVStreamMap stream_maps
[MAX_FILES
];
80 static int nb_stream_maps
;
82 static AVMetaDataMap meta_data_maps
[MAX_FILES
];
83 static int nb_meta_data_maps
;
85 static AVInputFormat
*file_iformat
;
86 static AVOutputFormat
*file_oformat
;
87 static AVImageFormat
*image_format
;
88 static int frame_width
= 0;
89 static int frame_height
= 0;
90 static float frame_aspect_ratio
= 0;
91 static enum PixelFormat frame_pix_fmt
= PIX_FMT_NONE
;
92 static int frame_padtop
= 0;
93 static int frame_padbottom
= 0;
94 static int frame_padleft
= 0;
95 static int frame_padright
= 0;
96 static int padcolor
[3] = {16,128,128}; /* default to black */
97 static int frame_topBand
= 0;
98 static int frame_bottomBand
= 0;
99 static int frame_leftBand
= 0;
100 static int frame_rightBand
= 0;
101 static int max_frames
[4] = {INT_MAX
, INT_MAX
, INT_MAX
, INT_MAX
};
102 static int frame_rate
= 25;
103 static int frame_rate_base
= 1;
104 static int video_bit_rate
= 200*1000;
105 static int video_bit_rate_tolerance
= 4000*1000;
106 static float video_qscale
= 0;
107 static int video_qmin
= 2;
108 static int video_qmax
= 31;
109 static int video_lmin
= 2*FF_QP2LAMBDA
;
110 static int video_lmax
= 31*FF_QP2LAMBDA
;
111 static int video_mb_lmin
= 2*FF_QP2LAMBDA
;
112 static int video_mb_lmax
= 31*FF_QP2LAMBDA
;
113 static int video_qdiff
= 3;
114 static int video_lelim
= 0;
115 static int video_celim
= 0;
116 static float video_qblur
= 0.5;
117 static float video_qsquish
= 0.0;
118 static float video_qcomp
= 0.5;
119 static uint16_t *intra_matrix
= NULL
;
120 static uint16_t *inter_matrix
= NULL
;
121 #if 0 //experimental, (can be removed)
122 static float video_rc_qsquish
=1.0;
123 static float video_rc_qmod_amp
=0;
124 static int video_rc_qmod_freq
=0;
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;
175 static int closed_gop
= 0;
176 static int strict_gop
= 0;
177 static int no_output
= 0;
178 static int do_deinterlace
= 0;
179 static int do_interlace_dct
= 0;
180 static int do_interlace_me
= 0;
181 static int workaround_bugs
= FF_BUG_AUTODETECT
;
182 static int error_resilience
= 2;
183 static int error_concealment
= 3;
184 static int dct_algo
= 0;
185 static int idct_algo
= 0;
186 static int use_part
= 0;
187 static int packet_size
= 0;
188 static int error_rate
= 0;
189 static int strict
= 0;
190 static int top_field_first
= -1;
191 static int noise_reduction
= 0;
192 static int sc_threshold
= 0;
193 static int debug
= 0;
194 static int debug_mv
= 0;
195 static int me_threshold
= 0;
196 static int mb_threshold
= 0;
197 static int intra_dc_precision
= 8;
198 static int coder
= 0;
199 static int context
= 0;
200 static int predictor
= 0;
201 static int video_profile
= FF_PROFILE_UNKNOWN
;
202 static int video_level
= FF_LEVEL_UNKNOWN
;
203 static int nsse_weight
= 8;
204 static int subpel_quality
= 8;
205 static int me_penalty_compensation
= 256;
206 static int lowres
= 0;
207 static int frame_skip_threshold
= 0;
208 static int frame_skip_factor
= 0;
209 static int frame_skip_exp
= 0;
210 static int frame_skip_cmp
= FF_CMP_DCTMAX
;
211 extern int loop_input
; /* currently a hack */
212 static int gray_only
= 0;
214 static int gop_size
= 12;
215 static int intra_only
= 0;
216 static int audio_sample_rate
= 44100;
217 static int audio_bit_rate
= 64000;
218 static int audio_disable
= 0;
219 static int audio_channels
= 1;
220 static int audio_codec_id
= CODEC_ID_NONE
;
221 static int audio_codec_tag
= 0;
222 static char *audio_language
= NULL
;
224 static int subtitle_codec_id
= CODEC_ID_NONE
;
225 static char *subtitle_language
= NULL
;
227 static int mux_rate
= 0;
228 static int mux_packet_size
= 0;
229 static float mux_preload
= 0.5;
230 static float mux_max_delay
= 0.7;
232 static int64_t recording_time
= 0;
233 static int64_t start_time
= 0;
234 static int64_t rec_timestamp
= 0;
235 static int64_t input_ts_offset
= 0;
236 static int file_overwrite
= 0;
237 static char *str_title
= NULL
;
238 static char *str_author
= NULL
;
239 static char *str_copyright
= NULL
;
240 static char *str_comment
= NULL
;
241 static int do_benchmark
= 0;
242 static int do_hex_dump
= 0;
243 static int do_pkt_dump
= 0;
244 static int do_psnr
= 0;
245 static int do_vstats
= 0;
246 static int do_pass
= 0;
247 static int bitexact
= 0;
248 static char *pass_logfilename
= NULL
;
249 static int audio_stream_copy
= 0;
250 static int video_stream_copy
= 0;
251 static int subtitle_stream_copy
= 0;
252 static int video_sync_method
= 1;
253 static int audio_sync_method
= 0;
254 static int copy_ts
= 0;
255 static int opt_shortest
= 0; //
257 static int rate_emu
= 0;
259 static char *video_grab_format
= "video4linux";
260 static char *video_device
= NULL
;
261 static char *grab_device
= NULL
;
262 static int video_channel
= 0;
263 static char *video_standard
= "ntsc";
265 static char *audio_grab_format
= "audio_device";
266 static char *audio_device
= NULL
;
267 static int audio_volume
= 256;
269 static int using_stdin
= 0;
270 static int using_vhook
= 0;
271 static int verbose
= 1;
272 static int thread_count
= 1;
273 static int q_pressed
= 0;
274 static int me_range
= 0;
275 static int64_t video_size
= 0;
276 static int64_t audio_size
= 0;
277 static int64_t extra_size
= 0;
278 static int nb_frames_dup
= 0;
279 static int nb_frames_drop
= 0;
280 static int input_sync
;
281 static int limit_filesize
= 0; //
283 static int pgmyuv_compatibility_hack
=0;
286 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
288 struct AVInputStream
;
290 typedef struct AVOutputStream
{
291 int file_index
; /* file index */
292 int index
; /* stream index in the output file */
293 int source_index
; /* AVInputStream index */
294 AVStream
*st
; /* stream in the output file */
295 int encoding_needed
; /* true if encoding needed for this stream */
297 /* input pts and corresponding output pts
299 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
300 struct AVInputStream
*sync_ist
; /* input stream to sync against */
301 int64_t sync_opts
; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
303 int video_resample
; /* video_resample and video_crop are mutually exclusive */
304 AVFrame pict_tmp
; /* temporary image for resampling */
305 ImgReSampleContext
*img_resample_ctx
; /* for image resampling */
307 int video_crop
; /* video_resample and video_crop are mutually exclusive */
308 int topBand
; /* cropping area sizes */
311 int video_pad
; /* video_resample and video_pad are mutually exclusive */
312 int padtop
; /* padding area sizes */
319 ReSampleContext
*resample
; /* for audio resampling */
320 FifoBuffer fifo
; /* for compression: one audio fifo per codec */
324 typedef struct AVInputStream
{
328 int discard
; /* true if stream data should be discarded */
329 int decoding_needed
; /* true if the packets must be decoded in 'raw_fifo' */
330 int64_t sample_index
; /* current sample */
332 int64_t start
; /* time when read started */
333 unsigned long frame
; /* current frame */
334 int64_t next_pts
; /* synthetic pts for cases where pkt.pts
336 int64_t pts
; /* current pts */
337 int is_start
; /* is 1 at the start and after a discontinuity */
340 typedef struct AVInputFile
{
341 int eof_reached
; /* true if eof reached */
342 int ist_index
; /* index of first stream in ist_table */
343 int buffer_size
; /* current total buffer size */
344 int buffer_size_max
; /* buffer size at which we consider we can stop
346 int nb_streams
; /* nb streams we are aware of */
351 /* init terminal so that we can grab keys */
352 static struct termios oldtty
;
354 static void term_exit(void)
356 tcsetattr (0, TCSANOW
, &oldtty
);
359 static volatile sig_atomic_t received_sigterm
= 0;
362 sigterm_handler(int sig
)
364 received_sigterm
= sig
;
368 static void term_init(void)
375 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
376 |INLCR
|IGNCR
|ICRNL
|IXON
);
377 tty
.c_oflag
|= OPOST
;
378 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
379 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
384 tcsetattr (0, TCSANOW
, &tty
);
386 signal(SIGINT
, sigterm_handler
); /* Interrupt (ANSI). */
387 signal(SIGQUIT
, sigterm_handler
); /* Quit (POSIX). */
388 signal(SIGTERM
, sigterm_handler
); /* Termination (ANSI). */
390 register a function to be called at normal program termination
393 #ifdef CONFIG_BEOS_NETSERVER
394 fcntl(0, F_SETFL
, fcntl(0, F_GETFL
) | O_NONBLOCK
);
398 /* read a key without blocking */
399 static int read_key(void)
403 #ifndef CONFIG_BEOS_NETSERVER
411 n
= select(1, &rfds
, NULL
, NULL
, &tv
);
423 static int decode_interrupt_cb(void)
425 return q_pressed
|| (q_pressed
= read_key() == 'q');
430 static volatile int received_sigterm
= 0;
432 /* no interactive support */
433 static void term_exit(void)
437 static void term_init(void)
441 static int read_key(void)
448 static int read_ffserver_streams(AVFormatContext
*s
, const char *filename
)
453 err
= av_open_input_file(&ic
, filename
, NULL
, FFM_PACKET_SIZE
, NULL
);
456 /* copy stream format */
457 s
->nb_streams
= ic
->nb_streams
;
458 for(i
=0;i
<ic
->nb_streams
;i
++) {
461 st
= av_mallocz(sizeof(AVStream
));
462 memcpy(st
, ic
->streams
[i
], sizeof(AVStream
));
466 av_close_input_file(ic
);
471 get_sync_ipts(const AVOutputStream
*ost
)
473 const AVInputStream
*ist
= ost
->sync_ist
;
474 return (double)(ist
->pts
+ input_files_ts_offset
[ist
->file_index
] - start_time
)/AV_TIME_BASE
;
477 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
479 static void do_audio_out(AVFormatContext
*s
,
482 unsigned char *buf
, int size
)
485 static uint8_t *audio_buf
= NULL
;
486 static uint8_t *audio_out
= NULL
;
487 const int audio_out_size
= 4*MAX_AUDIO_PACKET_SIZE
;
489 int size_out
, frame_bytes
, ret
;
490 AVCodecContext
*enc
= &ost
->st
->codec
;
492 /* SC: dynamic allocation of buffers */
494 audio_buf
= av_malloc(2*MAX_AUDIO_PACKET_SIZE
);
496 audio_out
= av_malloc(audio_out_size
);
497 if (!audio_buf
|| !audio_out
)
498 return; /* Should signal an error ! */
500 if(audio_sync_method
){
501 double delta
= get_sync_ipts(ost
) * enc
->sample_rate
- ost
->sync_opts
502 - fifo_size(&ost
->fifo
, ost
->fifo
.rptr
)/(ost
->st
->codec
.channels
* 2);
503 double idelta
= delta
*ist
->st
->codec
.sample_rate
/ enc
->sample_rate
;
504 int byte_delta
= ((int)idelta
)*2*ist
->st
->codec
.channels
;
506 //FIXME resample delay
507 if(fabs(delta
) > 50){
510 byte_delta
= FFMAX(byte_delta
, -size
);
514 fprintf(stderr
, "discarding %d audio samples\n", (int)-delta
);
519 static uint8_t *input_tmp
= NULL
;
520 input_tmp
= av_realloc(input_tmp
, byte_delta
+ size
);
522 if(byte_delta
+ size
<= MAX_AUDIO_PACKET_SIZE
)
525 byte_delta
= MAX_AUDIO_PACKET_SIZE
- size
;
527 memset(input_tmp
, 0, byte_delta
);
528 memcpy(input_tmp
+ byte_delta
, buf
, size
);
532 fprintf(stderr
, "adding %d audio samples of silence\n", (int)delta
);
534 }else if(audio_sync_method
>1){
535 int comp
= clip(delta
, -audio_sync_method
, audio_sync_method
);
536 assert(ost
->audio_resample
);
538 fprintf(stderr
, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta
, comp
, enc
->sample_rate
);
539 // fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec.channels * 2));
540 av_resample_compensate(*(struct AVResampleContext
**)ost
->resample
, comp
, enc
->sample_rate
);
544 ost
->sync_opts
= lrintf(get_sync_ipts(ost
) * enc
->sample_rate
)
545 - fifo_size(&ost
->fifo
, ost
->fifo
.rptr
)/(ost
->st
->codec
.channels
* 2); //FIXME wrong
547 if (ost
->audio_resample
) {
549 size_out
= audio_resample(ost
->resample
,
550 (short *)buftmp
, (short *)buf
,
551 size
/ (ist
->st
->codec
.channels
* 2));
552 size_out
= size_out
* enc
->channels
* 2;
558 /* now encode as many frames as possible */
559 if (enc
->frame_size
> 1) {
560 /* output resampled raw samples */
561 fifo_write(&ost
->fifo
, buftmp
, size_out
,
564 frame_bytes
= enc
->frame_size
* 2 * enc
->channels
;
566 while (fifo_read(&ost
->fifo
, audio_buf
, frame_bytes
,
567 &ost
->fifo
.rptr
) == 0) {
569 av_init_packet(&pkt
);
571 ret
= avcodec_encode_audio(enc
, audio_out
, audio_out_size
,
574 pkt
.stream_index
= ost
->index
;
578 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
579 pkt
.flags
|= PKT_FLAG_KEY
;
580 av_interleaved_write_frame(s
, &pkt
);
582 ost
->sync_opts
+= enc
->frame_size
;
586 av_init_packet(&pkt
);
588 ost
->sync_opts
+= size_out
/ (2 * enc
->channels
);
590 /* output a pcm frame */
591 /* XXX: change encoding codec API to avoid this ? */
592 switch(enc
->codec
->id
) {
593 case CODEC_ID_PCM_S16LE
:
594 case CODEC_ID_PCM_S16BE
:
595 case CODEC_ID_PCM_U16LE
:
596 case CODEC_ID_PCM_U16BE
:
599 size_out
= size_out
>> 1;
602 ret
= avcodec_encode_audio(enc
, audio_out
, size_out
,
605 pkt
.stream_index
= ost
->index
;
609 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
610 pkt
.flags
|= PKT_FLAG_KEY
;
611 av_interleaved_write_frame(s
, &pkt
);
615 static void pre_process_video_frame(AVInputStream
*ist
, AVPicture
*picture
, void **bufp
)
619 AVPicture picture_tmp
;
622 dec
= &ist
->st
->codec
;
624 /* deinterlace : must be done before any resize */
625 if (do_deinterlace
|| using_vhook
) {
628 /* create temporary picture */
629 size
= avpicture_get_size(dec
->pix_fmt
, dec
->width
, dec
->height
);
630 buf
= av_malloc(size
);
634 picture2
= &picture_tmp
;
635 avpicture_fill(picture2
, buf
, dec
->pix_fmt
, dec
->width
, dec
->height
);
638 if(avpicture_deinterlace(picture2
, picture
,
639 dec
->pix_fmt
, dec
->width
, dec
->height
) < 0) {
640 /* if error, do not deinterlace */
646 if (img_convert(picture2
, dec
->pix_fmt
, picture
,
647 dec
->pix_fmt
, dec
->width
, dec
->height
) < 0) {
648 /* if error, do not copy */
658 frame_hook_process(picture2
, dec
->pix_fmt
, dec
->width
, dec
->height
);
660 if (picture
!= picture2
)
661 *picture
= *picture2
;
665 /* we begin to correct av delay at this threshold */
666 #define AV_DELAY_MAX 0.100
669 /* Expects img to be yuv420 */
670 static void fill_pad_region(AVPicture
* img
, int height
, int width
,
671 int padtop
, int padbottom
, int padleft
, int padright
, int *color
) {
676 for (i
= 0; i
< 3; i
++) {
677 shift
= (i
== 0) ?
0 : 1;
679 if (padtop
|| padleft
) {
680 memset(img
->data
[i
], color
[i
], (((img
->linesize
[i
] * padtop
) +
684 if (padleft
|| padright
) {
685 optr
= img
->data
[i
] + (img
->linesize
[i
] * (padtop
>> shift
)) +
686 (img
->linesize
[i
] - (padright
>> shift
));
688 for (y
= 0; y
< ((height
- (padtop
+ padbottom
) - 1) >> shift
); y
++) {
689 memset(optr
, color
[i
], (padleft
+ padright
) >> shift
);
690 optr
+= img
->linesize
[i
];
694 if (padbottom
|| padright
) {
695 optr
= img
->data
[i
] + (((img
->linesize
[i
] * (height
- padbottom
)) - padright
) >> shift
);
696 memset(optr
, color
[i
], (((img
->linesize
[i
] * padbottom
) + padright
) >> shift
));
701 static void do_subtitle_out(AVFormatContext
*s
,
707 static uint8_t *subtitle_out
= NULL
;
708 int subtitle_out_max_size
= 65536;
709 int subtitle_out_size
, nb
, i
;
713 if (pts
== AV_NOPTS_VALUE
) {
714 fprintf(stderr
, "Subtitle packets must have a pts\n");
718 enc
= &ost
->st
->codec
;
721 subtitle_out
= av_malloc(subtitle_out_max_size
);
724 /* Note: DVB subtitle need one packet to draw them and one other
725 packet to clear them */
726 /* XXX: signal it in the codec context ? */
727 if (enc
->codec_id
== CODEC_ID_DVB_SUBTITLE
)
732 for(i
= 0; i
< nb
; i
++) {
733 subtitle_out_size
= avcodec_encode_subtitle(enc
, subtitle_out
,
734 subtitle_out_max_size
, sub
);
736 av_init_packet(&pkt
);
737 pkt
.stream_index
= ost
->index
;
738 pkt
.data
= subtitle_out
;
739 pkt
.size
= subtitle_out_size
;
740 pkt
.pts
= av_rescale_q(av_rescale_q(pts
, ist
->st
->time_base
, AV_TIME_BASE_Q
) + input_files_ts_offset
[ist
->file_index
], AV_TIME_BASE_Q
, ost
->st
->time_base
);
741 if (enc
->codec_id
== CODEC_ID_DVB_SUBTITLE
) {
742 /* XXX: the pts correction is handled here. Maybe handling
743 it in the codec would be better */
745 pkt
.pts
+= 90 * sub
->start_display_time
;
747 pkt
.pts
+= 90 * sub
->end_display_time
;
749 av_interleaved_write_frame(s
, &pkt
);
753 static int bit_buffer_size
= 1024*256;
754 static uint8_t *bit_buffer
= NULL
;
756 static void do_video_out(AVFormatContext
*s
,
762 int nb_frames
, i
, ret
;
763 AVFrame
*final_picture
, *formatted_picture
;
764 AVFrame picture_format_temp
, picture_crop_temp
;
765 uint8_t *buf
= NULL
, *buf1
= NULL
;
766 AVCodecContext
*enc
, *dec
;
767 enum PixelFormat target_pixfmt
;
769 avcodec_get_frame_defaults(&picture_format_temp
);
770 avcodec_get_frame_defaults(&picture_crop_temp
);
772 enc
= &ost
->st
->codec
;
773 dec
= &ist
->st
->codec
;
775 /* by default, we output a single frame */
780 if(video_sync_method
){
782 vdelta
= get_sync_ipts(ost
) / av_q2d(enc
->time_base
) - ost
->sync_opts
;
783 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
786 else if (vdelta
> 1.1)
787 nb_frames
= lrintf(vdelta
);
788 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
792 fprintf(stderr
, "*** drop!\n");
793 }else if (nb_frames
> 1) {
794 nb_frames_dup
+= nb_frames
;
796 fprintf(stderr
, "*** %d dup!\n", nb_frames
-1);
799 ost
->sync_opts
= lrintf(get_sync_ipts(ost
) / av_q2d(enc
->time_base
));
801 nb_frames
= FFMIN(nb_frames
, max_frames
[CODEC_TYPE_VIDEO
] - ost
->frame_number
);
805 /* convert pixel format if needed */
806 target_pixfmt
= ost
->video_resample
|| ost
->video_pad
807 ? PIX_FMT_YUV420P
: enc
->pix_fmt
;
808 if (dec
->pix_fmt
!= target_pixfmt
) {
811 /* create temporary picture */
812 size
= avpicture_get_size(target_pixfmt
, dec
->width
, dec
->height
);
813 buf
= av_malloc(size
);
816 formatted_picture
= &picture_format_temp
;
817 avpicture_fill((AVPicture
*)formatted_picture
, buf
, target_pixfmt
, dec
->width
, dec
->height
);
819 if (img_convert((AVPicture
*)formatted_picture
, target_pixfmt
,
820 (AVPicture
*)in_picture
, dec
->pix_fmt
,
821 dec
->width
, dec
->height
) < 0) {
824 fprintf(stderr
, "pixel format conversion not handled\n");
829 formatted_picture
= in_picture
;
832 /* XXX: resampling could be done before raw format conversion in
833 some cases to go faster */
834 /* XXX: only works for YUV420P */
835 if (ost
->video_resample
) {
836 final_picture
= &ost
->pict_tmp
;
837 img_resample(ost
->img_resample_ctx
, (AVPicture
*)final_picture
, (AVPicture
*)formatted_picture
);
839 if (ost
->padtop
|| ost
->padbottom
|| ost
->padleft
|| ost
->padright
) {
840 fill_pad_region((AVPicture
*)final_picture
, enc
->height
, enc
->width
,
841 ost
->padtop
, ost
->padbottom
, ost
->padleft
, ost
->padright
,
845 if (enc
->pix_fmt
!= PIX_FMT_YUV420P
) {
849 /* create temporary picture */
850 size
= avpicture_get_size(enc
->pix_fmt
, enc
->width
, enc
->height
);
851 buf
= av_malloc(size
);
854 final_picture
= &picture_format_temp
;
855 avpicture_fill((AVPicture
*)final_picture
, buf
, enc
->pix_fmt
, enc
->width
, enc
->height
);
857 if (img_convert((AVPicture
*)final_picture
, enc
->pix_fmt
,
858 (AVPicture
*)&ost
->pict_tmp
, PIX_FMT_YUV420P
,
859 enc
->width
, enc
->height
) < 0) {
862 fprintf(stderr
, "pixel format conversion not handled\n");
867 } else if (ost
->video_crop
) {
868 picture_crop_temp
.data
[0] = formatted_picture
->data
[0] +
869 (ost
->topBand
* formatted_picture
->linesize
[0]) + ost
->leftBand
;
871 picture_crop_temp
.data
[1] = formatted_picture
->data
[1] +
872 ((ost
->topBand
>> 1) * formatted_picture
->linesize
[1]) +
873 (ost
->leftBand
>> 1);
875 picture_crop_temp
.data
[2] = formatted_picture
->data
[2] +
876 ((ost
->topBand
>> 1) * formatted_picture
->linesize
[2]) +
877 (ost
->leftBand
>> 1);
879 picture_crop_temp
.linesize
[0] = formatted_picture
->linesize
[0];
880 picture_crop_temp
.linesize
[1] = formatted_picture
->linesize
[1];
881 picture_crop_temp
.linesize
[2] = formatted_picture
->linesize
[2];
882 final_picture
= &picture_crop_temp
;
883 } else if (ost
->video_pad
) {
884 final_picture
= &ost
->pict_tmp
;
886 for (i
= 0; i
< 3; i
++) {
887 uint8_t *optr
, *iptr
;
888 int shift
= (i
== 0) ?
0 : 1;
891 /* set offset to start writing image into */
892 optr
= final_picture
->data
[i
] + (((final_picture
->linesize
[i
] *
893 ost
->padtop
) + ost
->padleft
) >> shift
);
894 iptr
= formatted_picture
->data
[i
];
896 yheight
= (enc
->height
- ost
->padtop
- ost
->padbottom
) >> shift
;
897 for (y
= 0; y
< yheight
; y
++) {
898 /* copy unpadded image row into padded image row */
899 memcpy(optr
, iptr
, formatted_picture
->linesize
[i
]);
900 optr
+= final_picture
->linesize
[i
];
901 iptr
+= formatted_picture
->linesize
[i
];
905 fill_pad_region((AVPicture
*)final_picture
, enc
->height
, enc
->width
,
906 ost
->padtop
, ost
->padbottom
, ost
->padleft
, ost
->padright
,
909 if (enc
->pix_fmt
!= PIX_FMT_YUV420P
) {
913 /* create temporary picture */
914 size
= avpicture_get_size(enc
->pix_fmt
, enc
->width
, enc
->height
);
915 buf
= av_malloc(size
);
918 final_picture
= &picture_format_temp
;
919 avpicture_fill((AVPicture
*)final_picture
, buf
, enc
->pix_fmt
, enc
->width
, enc
->height
);
921 if (img_convert((AVPicture
*)final_picture
, enc
->pix_fmt
,
922 (AVPicture
*)&ost
->pict_tmp
, PIX_FMT_YUV420P
,
923 enc
->width
, enc
->height
) < 0) {
926 fprintf(stderr
, "pixel format conversion not handled\n");
932 final_picture
= formatted_picture
;
934 /* duplicates frame if needed */
935 for(i
=0;i
<nb_frames
;i
++) {
937 av_init_packet(&pkt
);
938 pkt
.stream_index
= ost
->index
;
940 if (s
->oformat
->flags
& AVFMT_RAWPICTURE
) {
941 /* raw pictures are written as AVPicture structure to
942 avoid any copies. We support temorarily the older
944 AVFrame
* old_frame
= enc
->coded_frame
;
945 enc
->coded_frame
= dec
->coded_frame
; //FIXME/XXX remove this hack
946 pkt
.data
= (uint8_t *)final_picture
;
947 pkt
.size
= sizeof(AVPicture
);
949 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
950 if(dec
->coded_frame
&& dec
->coded_frame
->key_frame
)
951 pkt
.flags
|= PKT_FLAG_KEY
;
953 av_interleaved_write_frame(s
, &pkt
);
954 enc
->coded_frame
= old_frame
;
958 big_picture
= *final_picture
;
959 /* better than nothing: use input picture interlaced
961 big_picture
.interlaced_frame
= in_picture
->interlaced_frame
;
962 if(do_interlace_me
|| do_interlace_dct
){
963 if(top_field_first
== -1)
964 big_picture
.top_field_first
= in_picture
->top_field_first
;
966 big_picture
.top_field_first
= top_field_first
;
969 /* handles sameq here. This is not correct because it may
970 not be a global option */
972 big_picture
.quality
= ist
->st
->quality
;
974 big_picture
.quality
= ost
->st
->quality
;
976 big_picture
.pict_type
= 0;
977 // big_picture.pts = AV_NOPTS_VALUE;
978 big_picture
.pts
= ost
->sync_opts
;
979 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
980 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
981 ret
= avcodec_encode_video(enc
,
982 bit_buffer
, bit_buffer_size
,
984 //enc->frame_number = enc->real_pict_num;
986 pkt
.data
= bit_buffer
;
989 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
990 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
991 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
992 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
994 if(enc
->coded_frame
&& enc
->coded_frame
->key_frame
)
995 pkt
.flags
|= PKT_FLAG_KEY
;
996 av_interleaved_write_frame(s
, &pkt
);
998 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
999 // enc->frame_number-1, enc->real_pict_num, ret,
1001 /* if two pass, output log */
1002 if (ost
->logfile
&& enc
->stats_out
) {
1003 fprintf(ost
->logfile
, "%s", enc
->stats_out
);
1008 ost
->frame_number
++;
1015 static double psnr(double d
){
1016 if(d
==0) return INFINITY
;
1017 return -10.0*log(d
)/log(10.0);
1020 static void do_video_stats(AVFormatContext
*os
, AVOutputStream
*ost
,
1023 static FILE *fvstats
=NULL
;
1027 AVCodecContext
*enc
;
1030 double ti1
, bitrate
, avg_bitrate
;
1033 today2
= time(NULL
);
1034 today
= localtime(&today2
);
1035 snprintf(filename
, sizeof(filename
), "vstats_%02d%02d%02d.log", today
->tm_hour
,
1038 fvstats
= fopen(filename
,"w");
1046 enc
= &ost
->st
->codec
;
1047 if (enc
->codec_type
== CODEC_TYPE_VIDEO
) {
1048 frame_number
= ost
->frame_number
;
1049 fprintf(fvstats
, "frame= %5d q= %2.1f ", frame_number
, enc
->coded_frame
->quality
/(float)FF_QP2LAMBDA
);
1050 if (enc
->flags
&CODEC_FLAG_PSNR
)
1051 fprintf(fvstats
, "PSNR= %6.2f ", psnr(enc
->coded_frame
->error
[0]/(enc
->width
*enc
->height
*255.0*255.0)));
1053 fprintf(fvstats
,"f_size= %6d ", frame_size
);
1054 /* compute pts value */
1055 ti1
= ost
->sync_opts
* av_q2d(enc
->time_base
);
1059 bitrate
= (frame_size
* 8) / av_q2d(enc
->time_base
) / 1000.0;
1060 avg_bitrate
= (double)(video_size
* 8) / ti1
/ 1000.0;
1061 fprintf(fvstats
, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1062 (double)video_size
/ 1024, ti1
, bitrate
, avg_bitrate
);
1063 fprintf(fvstats
,"type= %c\n", av_get_pict_type_char(enc
->coded_frame
->pict_type
));
1067 static void print_report(AVFormatContext
**output_files
,
1068 AVOutputStream
**ost_table
, int nb_ostreams
,
1072 AVOutputStream
*ost
;
1073 AVFormatContext
*oc
, *os
;
1075 AVCodecContext
*enc
;
1076 int frame_number
, vid
, i
;
1077 double bitrate
, ti1
, pts
;
1078 static int64_t last_time
= -1;
1080 if (!is_last_report
) {
1082 /* display the report every 0.5 seconds */
1083 cur_time
= av_gettime();
1084 if (last_time
== -1) {
1085 last_time
= cur_time
;
1088 if ((cur_time
- last_time
) < 500000)
1090 last_time
= cur_time
;
1094 oc
= output_files
[0];
1096 total_size
= url_ftell(&oc
->pb
);
1101 for(i
=0;i
<nb_ostreams
;i
++) {
1103 os
= output_files
[ost
->file_index
];
1104 enc
= &ost
->st
->codec
;
1105 if (vid
&& enc
->codec_type
== CODEC_TYPE_VIDEO
) {
1106 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "q=%2.1f ",
1107 enc
->coded_frame
->quality
/(float)FF_QP2LAMBDA
);
1109 if (!vid
&& enc
->codec_type
== CODEC_TYPE_VIDEO
) {
1110 frame_number
= ost
->frame_number
;
1111 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "frame=%5d q=%2.1f ",
1112 frame_number
, enc
->coded_frame ? enc
->coded_frame
->quality
/(float)FF_QP2LAMBDA
: 0);
1114 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "L");
1115 if (enc
->flags
&CODEC_FLAG_PSNR
){
1117 double error
, error_sum
=0;
1118 double scale
, scale_sum
=0;
1119 char type
[3]= {'Y','U','V'};
1120 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "PSNR=");
1123 error
= enc
->error
[j
];
1124 scale
= enc
->width
*enc
->height
*255.0*255.0*frame_number
;
1126 error
= enc
->coded_frame
->error
[j
];
1127 scale
= enc
->width
*enc
->height
*255.0*255.0;
1132 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "%c:%2.2f ", type
[j
], psnr(error
/scale
));
1134 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), "*:%2.2f ", psnr(error_sum
/scale_sum
));
1138 /* compute min output value */
1139 pts
= (double)ost
->st
->pts
.val
* ost
->st
->time_base
.num
/ ost
->st
->time_base
.den
;
1140 if ((pts
< ti1
) && (pts
> 0))
1146 if (verbose
|| is_last_report
) {
1147 bitrate
= (double)(total_size
* 8) / ti1
/ 1000.0;
1149 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
),
1150 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1151 (double)total_size
/ 1024, ti1
, bitrate
);
1154 snprintf(buf
+ strlen(buf
), sizeof(buf
) - strlen(buf
), " dup=%d drop=%d",
1155 nb_frames_dup
, nb_frames_drop
);
1158 fprintf(stderr
, "%s \r", buf
);
1163 if (is_last_report
&& verbose
>= 0){
1164 int64_t raw
= audio_size
+ video_size
+ extra_size
;
1165 fprintf(stderr
, "\n");
1166 fprintf(stderr
, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1170 100.0*(total_size
- raw
)/raw
1175 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1176 static int output_packet(AVInputStream
*ist
, int ist_index
,
1177 AVOutputStream
**ost_table
, int nb_ostreams
,
1178 const AVPacket
*pkt
)
1180 AVFormatContext
*os
;
1181 AVOutputStream
*ost
;
1185 int data_size
, got_picture
;
1187 void *buffer_to_free
;
1188 static int samples_size
= 0;
1189 static short *samples
= NULL
;
1190 AVSubtitle subtitle
, *subtitle_to_free
;
1194 ist
->pts
= ist
->next_pts
; // needed for last packet if vsync=0
1195 } else if (pkt
->dts
!= AV_NOPTS_VALUE
) { //FIXME seems redundant, as libavformat does this too
1196 ist
->next_pts
= ist
->pts
= av_rescale_q(pkt
->dts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
1198 // assert(ist->pts == ist->next_pts);
1212 /* decode the packet if needed */
1213 data_buf
= NULL
; /* fail safe */
1215 subtitle_to_free
= NULL
;
1216 if (ist
->decoding_needed
) {
1217 switch(ist
->st
->codec
.codec_type
) {
1218 case CODEC_TYPE_AUDIO
:{
1220 samples
= av_fast_realloc(samples
, &samples_size
, FFMAX(pkt
->size
, AVCODEC_MAX_AUDIO_FRAME_SIZE
));
1221 /* XXX: could avoid copy if PCM 16 bits with same
1222 endianness as CPU */
1223 ret
= avcodec_decode_audio(&ist
->st
->codec
, samples
, &data_size
,
1229 /* Some bug in mpeg audio decoder gives */
1230 /* data_size < 0, it seems they are overflows */
1231 if (data_size
<= 0) {
1232 /* no audio frame */
1235 data_buf
= (uint8_t *)samples
;
1236 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
/2 * data_size
) /
1237 (ist
->st
->codec
.sample_rate
* ist
->st
->codec
.channels
);
1239 case CODEC_TYPE_VIDEO
:
1240 data_size
= (ist
->st
->codec
.width
* ist
->st
->codec
.height
* 3) / 2;
1241 /* XXX: allocate picture correctly */
1242 avcodec_get_frame_defaults(&picture
);
1244 ret
= avcodec_decode_video(&ist
->st
->codec
,
1245 &picture
, &got_picture
, ptr
, len
);
1246 ist
->st
->quality
= picture
.quality
;
1250 /* no picture yet */
1251 goto discard_packet
;
1253 if (ist
->st
->codec
.time_base
.num
!= 0) {
1254 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
*
1255 ist
->st
->codec
.time_base
.num
) /
1256 ist
->st
->codec
.time_base
.den
;
1260 case CODEC_TYPE_SUBTITLE
:
1261 ret
= avcodec_decode_subtitle(&ist
->st
->codec
,
1262 &subtitle
, &got_subtitle
, ptr
, len
);
1265 if (!got_subtitle
) {
1266 goto discard_packet
;
1268 subtitle_to_free
= &subtitle
;
1275 switch(ist
->st
->codec
.codec_type
) {
1276 case CODEC_TYPE_AUDIO
:
1277 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
* ist
->st
->codec
.frame_size
) /
1278 (ist
->st
->codec
.sample_rate
* ist
->st
->codec
.channels
);
1280 case CODEC_TYPE_VIDEO
:
1281 if (ist
->st
->codec
.time_base
.num
!= 0) {
1282 ist
->next_pts
+= ((int64_t)AV_TIME_BASE
*
1283 ist
->st
->codec
.time_base
.num
) /
1284 ist
->st
->codec
.time_base
.den
;
1294 buffer_to_free
= NULL
;
1295 if (ist
->st
->codec
.codec_type
== CODEC_TYPE_VIDEO
) {
1296 pre_process_video_frame(ist
, (AVPicture
*)&picture
,
1300 // preprocess audio (volume)
1301 if (ist
->st
->codec
.codec_type
== CODEC_TYPE_AUDIO
) {
1302 if (audio_volume
!= 256) {
1305 for(i
=0;i
<(data_size
/ sizeof(short));i
++) {
1306 int v
= ((*volp
) * audio_volume
+ 128) >> 8;
1307 if (v
< -32768) v
= -32768;
1308 if (v
> 32767) v
= 32767;
1314 /* frame rate emulation */
1315 if (ist
->st
->codec
.rate_emu
) {
1316 int64_t pts
= av_rescale((int64_t) ist
->frame
* ist
->st
->codec
.time_base
.num
, 1000000, ist
->st
->codec
.time_base
.den
);
1317 int64_t now
= av_gettime() - ist
->start
;
1325 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1326 is the one of the next displayed one */
1327 /* XXX: add mpeg4 too ? */
1328 if (ist
->st
->codec
.codec_id
== CODEC_ID_MPEG1VIDEO
) {
1329 if (ist
->st
->codec
.pict_type
!= B_TYPE
) {
1331 tmp
= ist
->last_ip_pts
;
1332 ist
->last_ip_pts
= ist
->frac_pts
.val
;
1333 ist
->frac_pts
.val
= tmp
;
1337 /* if output time reached then transcode raw format,
1338 encode packets and output them */
1339 if (start_time
== 0 || ist
->pts
>= start_time
)
1340 for(i
=0;i
<nb_ostreams
;i
++) {
1344 if (ost
->source_index
== ist_index
) {
1345 os
= output_files
[ost
->file_index
];
1348 printf("%d: got pts=%0.3f %0.3f\n", i
,
1349 (double)pkt
->pts
/ AV_TIME_BASE
,
1350 ((double)ist
->pts
/ AV_TIME_BASE
) -
1351 ((double)ost
->st
->pts
.val
* ost
->st
->time_base
.num
/ ost
->st
->time_base
.den
));
1353 /* set the input output pts pairs */
1354 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1356 if (ost
->encoding_needed
) {
1357 switch(ost
->st
->codec
.codec_type
) {
1358 case CODEC_TYPE_AUDIO
:
1359 do_audio_out(os
, ost
, ist
, data_buf
, data_size
);
1361 case CODEC_TYPE_VIDEO
:
1362 do_video_out(os
, ost
, ist
, &picture
, &frame_size
);
1363 video_size
+= frame_size
;
1364 if (do_vstats
&& frame_size
)
1365 do_video_stats(os
, ost
, frame_size
);
1367 case CODEC_TYPE_SUBTITLE
:
1368 do_subtitle_out(os
, ost
, ist
, &subtitle
,
1375 AVFrame avframe
; //FIXME/XXX remove this
1377 av_init_packet(&opkt
);
1379 /* no reencoding needed : output the packet directly */
1380 /* force the input stream PTS */
1382 avcodec_get_frame_defaults(&avframe
);
1383 ost
->st
->codec
.coded_frame
= &avframe
;
1384 avframe
.key_frame
= pkt
->flags
& PKT_FLAG_KEY
;
1386 if(ost
->st
->codec
.codec_type
== CODEC_TYPE_AUDIO
)
1387 audio_size
+= data_size
;
1388 else if (ost
->st
->codec
.codec_type
== CODEC_TYPE_VIDEO
) {
1389 video_size
+= data_size
;
1393 opkt
.stream_index
= ost
->index
;
1394 opkt
.data
= data_buf
;
1395 opkt
.size
= data_size
;
1396 if(pkt
->pts
!= AV_NOPTS_VALUE
)
1397 opkt
.pts
= av_rescale_q(av_rescale_q(pkt
->pts
, ist
->st
->time_base
, AV_TIME_BASE_Q
) + input_files_ts_offset
[ist
->file_index
], AV_TIME_BASE_Q
, ost
->st
->time_base
);
1399 opkt
.pts
= AV_NOPTS_VALUE
;
1403 if (pkt
->dts
== AV_NOPTS_VALUE
)
1404 dts
= ist
->next_pts
;
1406 dts
= av_rescale_q(pkt
->dts
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
1407 opkt
.dts
= av_rescale_q(dts
+ input_files_ts_offset
[ist
->file_index
], AV_TIME_BASE_Q
, ost
->st
->time_base
);
1409 opkt
.flags
= pkt
->flags
;
1410 av_interleaved_write_frame(os
, &opkt
);
1411 ost
->st
->codec
.frame_number
++;
1412 ost
->frame_number
++;
1416 av_free(buffer_to_free
);
1417 /* XXX: allocate the subtitles in the codec ? */
1418 if (subtitle_to_free
) {
1419 av_free(subtitle_to_free
->bitmap
);
1420 av_free(subtitle_to_free
->rgba_palette
);
1421 subtitle_to_free
= NULL
;
1428 for(i
=0;i
<nb_ostreams
;i
++) {
1430 if (ost
->source_index
== ist_index
) {
1431 AVCodecContext
*enc
= &ost
->st
->codec
;
1432 os
= output_files
[ost
->file_index
];
1434 if(ost
->st
->codec
.codec_type
== CODEC_TYPE_AUDIO
&& enc
->frame_size
<=1)
1436 if(ost
->st
->codec
.codec_type
== CODEC_TYPE_VIDEO
&& (os
->oformat
->flags
& AVFMT_RAWPICTURE
))
1439 if (ost
->encoding_needed
) {
1442 av_init_packet(&pkt
);
1443 pkt
.stream_index
= ost
->index
;
1445 switch(ost
->st
->codec
.codec_type
) {
1446 case CODEC_TYPE_AUDIO
:
1447 ret
= avcodec_encode_audio(enc
, bit_buffer
, bit_buffer_size
, NULL
);
1449 pkt
.flags
|= PKT_FLAG_KEY
;
1451 case CODEC_TYPE_VIDEO
:
1452 ret
= avcodec_encode_video(enc
, bit_buffer
, bit_buffer_size
, NULL
);
1454 if(enc
->coded_frame
&& enc
->coded_frame
->key_frame
)
1455 pkt
.flags
|= PKT_FLAG_KEY
;
1456 if (ost
->logfile
&& enc
->stats_out
) {
1457 fprintf(ost
->logfile
, "%s", enc
->stats_out
);
1466 pkt
.data
= bit_buffer
;
1468 if(enc
->coded_frame
)
1469 pkt
.pts
= av_rescale_q(enc
->coded_frame
->pts
, enc
->time_base
, ost
->st
->time_base
);
1470 av_interleaved_write_frame(os
, &pkt
);
1484 * The following code is the main loop of the file converter
1486 static int av_encode(AVFormatContext
**output_files
,
1487 int nb_output_files
,
1488 AVFormatContext
**input_files
,
1490 AVStreamMap
*stream_maps
, int nb_stream_maps
)
1492 int ret
, i
, j
, k
, n
, nb_istreams
= 0, nb_ostreams
= 0;
1493 AVFormatContext
*is
, *os
;
1494 AVCodecContext
*codec
, *icodec
;
1495 AVOutputStream
*ost
, **ost_table
= NULL
;
1496 AVInputStream
*ist
, **ist_table
= NULL
;
1497 AVInputFile
*file_table
;
1498 AVFormatContext
*stream_no_data
;
1501 file_table
= (AVInputFile
*) av_mallocz(nb_input_files
* sizeof(AVInputFile
));
1505 /* input stream init */
1507 for(i
=0;i
<nb_input_files
;i
++) {
1508 is
= input_files
[i
];
1509 file_table
[i
].ist_index
= j
;
1510 file_table
[i
].nb_streams
= is
->nb_streams
;
1511 j
+= is
->nb_streams
;
1515 ist_table
= av_mallocz(nb_istreams
* sizeof(AVInputStream
*));
1519 for(i
=0;i
<nb_istreams
;i
++) {
1520 ist
= av_mallocz(sizeof(AVInputStream
));
1526 for(i
=0;i
<nb_input_files
;i
++) {
1527 is
= input_files
[i
];
1528 for(k
=0;k
<is
->nb_streams
;k
++) {
1529 ist
= ist_table
[j
++];
1530 ist
->st
= is
->streams
[k
];
1531 ist
->file_index
= i
;
1533 ist
->discard
= 1; /* the stream is discarded by default
1536 if (ist
->st
->codec
.rate_emu
) {
1537 ist
->start
= av_gettime();
1543 /* output stream init */
1545 for(i
=0;i
<nb_output_files
;i
++) {
1546 os
= output_files
[i
];
1547 nb_ostreams
+= os
->nb_streams
;
1549 if (nb_stream_maps
> 0 && nb_stream_maps
!= nb_ostreams
) {
1550 fprintf(stderr
, "Number of stream maps must match number of output streams\n");
1554 /* Sanity check the mapping args -- do the input files & streams exist? */
1555 for(i
=0;i
<nb_stream_maps
;i
++) {
1556 int fi
= stream_maps
[i
].file_index
;
1557 int si
= stream_maps
[i
].stream_index
;
1559 if (fi
< 0 || fi
> nb_input_files
- 1 ||
1560 si
< 0 || si
> file_table
[fi
].nb_streams
- 1) {
1561 fprintf(stderr
,"Could not find input stream #%d.%d\n", fi
, si
);
1564 fi
= stream_maps
[i
].sync_file_index
;
1565 si
= stream_maps
[i
].sync_stream_index
;
1566 if (fi
< 0 || fi
> nb_input_files
- 1 ||
1567 si
< 0 || si
> file_table
[fi
].nb_streams
- 1) {
1568 fprintf(stderr
,"Could not find sync stream #%d.%d\n", fi
, si
);
1573 ost_table
= av_mallocz(sizeof(AVOutputStream
*) * nb_ostreams
);
1576 for(i
=0;i
<nb_ostreams
;i
++) {
1577 ost
= av_mallocz(sizeof(AVOutputStream
));
1584 for(k
=0;k
<nb_output_files
;k
++) {
1585 os
= output_files
[k
];
1586 for(i
=0;i
<os
->nb_streams
;i
++) {
1588 ost
= ost_table
[n
++];
1589 ost
->file_index
= k
;
1591 ost
->st
= os
->streams
[i
];
1592 if (nb_stream_maps
> 0) {
1593 ost
->source_index
= file_table
[stream_maps
[n
-1].file_index
].ist_index
+
1594 stream_maps
[n
-1].stream_index
;
1596 /* Sanity check that the stream types match */
1597 if (ist_table
[ost
->source_index
]->st
->codec
.codec_type
!= ost
->st
->codec
.codec_type
) {
1598 fprintf(stderr
, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1599 stream_maps
[n
-1].file_index
, stream_maps
[n
-1].stream_index
,
1600 ost
->file_index
, ost
->index
);
1605 /* get corresponding input stream index : we select the first one with the right type */
1607 for(j
=0;j
<nb_istreams
;j
++) {
1610 ist
->st
->codec
.codec_type
== ost
->st
->codec
.codec_type
) {
1611 ost
->source_index
= j
;
1618 /* try again and reuse existing stream */
1619 for(j
=0;j
<nb_istreams
;j
++) {
1621 if (ist
->st
->codec
.codec_type
== ost
->st
->codec
.codec_type
) {
1622 ost
->source_index
= j
;
1627 fprintf(stderr
, "Could not find input stream matching output stream #%d.%d\n",
1628 ost
->file_index
, ost
->index
);
1633 ist
= ist_table
[ost
->source_index
];
1635 ost
->sync_ist
= (nb_stream_maps
> 0) ?
1636 ist_table
[file_table
[stream_maps
[n
-1].sync_file_index
].ist_index
+
1637 stream_maps
[n
-1].sync_stream_index
] : ist
;
1641 /* for each output stream, we compute the right encoding parameters */
1642 for(i
=0;i
<nb_ostreams
;i
++) {
1644 ist
= ist_table
[ost
->source_index
];
1646 codec
= &ost
->st
->codec
;
1647 icodec
= &ist
->st
->codec
;
1649 if (ost
->st
->stream_copy
) {
1650 /* if stream_copy is selected, no need to decode or encode */
1651 codec
->codec_id
= icodec
->codec_id
;
1652 codec
->codec_type
= icodec
->codec_type
;
1653 if(!codec
->codec_tag
) codec
->codec_tag
= icodec
->codec_tag
;
1654 codec
->bit_rate
= icodec
->bit_rate
;
1655 codec
->extradata
= icodec
->extradata
;
1656 codec
->extradata_size
= icodec
->extradata_size
;
1657 switch(codec
->codec_type
) {
1658 case CODEC_TYPE_AUDIO
:
1659 codec
->sample_rate
= icodec
->sample_rate
;
1660 codec
->channels
= icodec
->channels
;
1661 codec
->frame_size
= icodec
->frame_size
;
1662 codec
->block_align
= icodec
->block_align
;
1664 case CODEC_TYPE_VIDEO
:
1665 codec
->time_base
= icodec
->time_base
;
1666 codec
->width
= icodec
->width
;
1667 codec
->height
= icodec
->height
;
1668 codec
->has_b_frames
= icodec
->has_b_frames
;
1670 case CODEC_TYPE_SUBTITLE
:
1676 switch(codec
->codec_type
) {
1677 case CODEC_TYPE_AUDIO
:
1678 if (fifo_init(&ost
->fifo
, 2 * MAX_AUDIO_PACKET_SIZE
))
1681 if (codec
->channels
== icodec
->channels
&&
1682 codec
->sample_rate
== icodec
->sample_rate
) {
1683 ost
->audio_resample
= 0;
1685 if (codec
->channels
!= icodec
->channels
&&
1686 (icodec
->codec_id
== CODEC_ID_AC3
||
1687 icodec
->codec_id
== CODEC_ID_DTS
)) {
1688 /* Special case for 5:1 AC3 and DTS input */
1689 /* and mono or stereo output */
1690 /* Request specific number of channels */
1691 icodec
->channels
= codec
->channels
;
1692 if (codec
->sample_rate
== icodec
->sample_rate
)
1693 ost
->audio_resample
= 0;
1695 ost
->audio_resample
= 1;
1698 ost
->audio_resample
= 1;
1701 if(audio_sync_method
>1)
1702 ost
->audio_resample
= 1;
1704 if(ost
->audio_resample
){
1705 ost
->resample
= audio_resample_init(codec
->channels
, icodec
->channels
,
1706 codec
->sample_rate
, icodec
->sample_rate
);
1708 printf("Can't resample. Aborting.\n");
1712 ist
->decoding_needed
= 1;
1713 ost
->encoding_needed
= 1;
1715 case CODEC_TYPE_VIDEO
:
1716 if (codec
->width
== icodec
->width
&&
1717 codec
->height
== icodec
->height
&&
1718 frame_topBand
== 0 &&
1719 frame_bottomBand
== 0 &&
1720 frame_leftBand
== 0 &&
1721 frame_rightBand
== 0 &&
1722 frame_padtop
== 0 &&
1723 frame_padbottom
== 0 &&
1724 frame_padleft
== 0 &&
1725 frame_padright
== 0)
1727 ost
->video_resample
= 0;
1728 ost
->video_crop
= 0;
1730 } else if ((codec
->width
== icodec
->width
-
1731 (frame_leftBand
+ frame_rightBand
)) &&
1732 (codec
->height
== icodec
->height
-
1733 (frame_topBand
+ frame_bottomBand
)))
1735 ost
->video_resample
= 0;
1736 ost
->video_crop
= 1;
1737 ost
->topBand
= frame_topBand
;
1738 ost
->leftBand
= frame_leftBand
;
1739 } else if ((codec
->width
== icodec
->width
+
1740 (frame_padleft
+ frame_padright
)) &&
1741 (codec
->height
== icodec
->height
+
1742 (frame_padtop
+ frame_padbottom
))) {
1743 ost
->video_resample
= 0;
1744 ost
->video_crop
= 0;
1746 ost
->padtop
= frame_padtop
;
1747 ost
->padleft
= frame_padleft
;
1748 ost
->padbottom
= frame_padbottom
;
1749 ost
->padright
= frame_padright
;
1750 avcodec_get_frame_defaults(&ost
->pict_tmp
);
1751 if( avpicture_alloc( (AVPicture
*)&ost
->pict_tmp
, PIX_FMT_YUV420P
,
1752 codec
->width
, codec
->height
) )
1755 ost
->video_resample
= 1;
1756 ost
->video_crop
= 0; // cropping is handled as part of resample
1757 avcodec_get_frame_defaults(&ost
->pict_tmp
);
1758 if( avpicture_alloc( (AVPicture
*)&ost
->pict_tmp
, PIX_FMT_YUV420P
,
1759 codec
->width
, codec
->height
) )
1762 ost
->img_resample_ctx
= img_resample_full_init(
1763 ost
->st
->codec
.width
, ost
->st
->codec
.height
,
1764 ist
->st
->codec
.width
, ist
->st
->codec
.height
,
1765 frame_topBand
, frame_bottomBand
,
1766 frame_leftBand
, frame_rightBand
,
1767 frame_padtop
, frame_padbottom
,
1768 frame_padleft
, frame_padright
);
1770 ost
->padtop
= frame_padtop
;
1771 ost
->padleft
= frame_padleft
;
1772 ost
->padbottom
= frame_padbottom
;
1773 ost
->padright
= frame_padright
;
1776 ost
->encoding_needed
= 1;
1777 ist
->decoding_needed
= 1;
1779 case CODEC_TYPE_SUBTITLE
:
1780 ost
->encoding_needed
= 1;
1781 ist
->decoding_needed
= 1;
1788 if (ost
->encoding_needed
&&
1789 (codec
->flags
& (CODEC_FLAG_PASS1
| CODEC_FLAG_PASS2
))) {
1790 char logfilename
[1024];
1795 snprintf(logfilename
, sizeof(logfilename
), "%s-%d.log",
1797 pass_logfilename
: DEFAULT_PASS_LOGFILENAME
, i
);
1798 if (codec
->flags
& CODEC_FLAG_PASS1
) {
1799 f
= fopen(logfilename
, "w");
1801 perror(logfilename
);
1806 /* read the log file */
1807 f
= fopen(logfilename
, "r");
1809 perror(logfilename
);
1812 fseek(f
, 0, SEEK_END
);
1814 fseek(f
, 0, SEEK_SET
);
1815 logbuffer
= av_malloc(size
+ 1);
1817 fprintf(stderr
, "Could not allocate log buffer\n");
1820 size
= fread(logbuffer
, 1, size
, f
);
1822 logbuffer
[size
] = '\0';
1823 codec
->stats_in
= logbuffer
;
1827 if(codec
->codec_type
== CODEC_TYPE_VIDEO
){
1828 int size
= codec
->width
* codec
->height
;
1829 bit_buffer_size
= FFMAX(bit_buffer_size
, 4*size
);
1834 bit_buffer
= av_malloc(bit_buffer_size
);
1838 /* dump the file output parameters - cannot be done before in case
1840 for(i
=0;i
<nb_output_files
;i
++) {
1841 dump_format(output_files
[i
], i
, output_files
[i
]->filename
, 1);
1844 /* dump the stream mapping */
1846 fprintf(stderr
, "Stream mapping:\n");
1847 for(i
=0;i
<nb_ostreams
;i
++) {
1849 fprintf(stderr
, " Stream #%d.%d -> #%d.%d",
1850 ist_table
[ost
->source_index
]->file_index
,
1851 ist_table
[ost
->source_index
]->index
,
1854 if (ost
->sync_ist
!= ist_table
[ost
->source_index
])
1855 fprintf(stderr
, " [sync #%d.%d]",
1856 ost
->sync_ist
->file_index
,
1857 ost
->sync_ist
->index
);
1858 fprintf(stderr
, "\n");
1862 /* open each encoder */
1863 for(i
=0;i
<nb_ostreams
;i
++) {
1865 if (ost
->encoding_needed
) {
1867 codec
= avcodec_find_encoder(ost
->st
->codec
.codec_id
);
1869 fprintf(stderr
, "Unsupported codec for output stream #%d.%d\n",
1870 ost
->file_index
, ost
->index
);
1873 if (avcodec_open(&ost
->st
->codec
, codec
) < 0) {
1874 fprintf(stderr
, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1875 ost
->file_index
, ost
->index
);
1878 extra_size
+= ost
->st
->codec
.extradata_size
;
1882 /* open each decoder */
1883 for(i
=0;i
<nb_istreams
;i
++) {
1885 if (ist
->decoding_needed
) {
1887 codec
= avcodec_find_decoder(ist
->st
->codec
.codec_id
);
1889 fprintf(stderr
, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1890 ist
->st
->codec
.codec_id
, ist
->file_index
, ist
->index
);
1893 if (avcodec_open(&ist
->st
->codec
, codec
) < 0) {
1894 fprintf(stderr
, "Error while opening codec for input stream #%d.%d\n",
1895 ist
->file_index
, ist
->index
);
1898 //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
1899 // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
1904 for(i
=0;i
<nb_istreams
;i
++) {
1906 is
= input_files
[ist
->file_index
];
1908 ist
->next_pts
= av_rescale_q(ist
->st
->start_time
, ist
->st
->time_base
, AV_TIME_BASE_Q
);
1909 if(ist
->st
->start_time
== AV_NOPTS_VALUE
)
1911 if(input_files_ts_offset
[ist
->file_index
])
1912 ist
->next_pts
= AV_NOPTS_VALUE
;
1916 /* compute buffer size max (should use a complete heuristic) */
1917 for(i
=0;i
<nb_input_files
;i
++) {
1918 file_table
[i
].buffer_size_max
= 2048;
1921 /* set meta data information from input file if required */
1922 for (i
=0;i
<nb_meta_data_maps
;i
++) {
1923 AVFormatContext
*out_file
;
1924 AVFormatContext
*in_file
;
1926 int out_file_index
= meta_data_maps
[i
].out_file
;
1927 int in_file_index
= meta_data_maps
[i
].in_file
;
1928 if ( out_file_index
< 0 || out_file_index
>= nb_output_files
) {
1929 fprintf(stderr
, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index
, out_file_index
, in_file_index
);
1933 if ( in_file_index
< 0 || in_file_index
>= nb_input_files
) {
1934 fprintf(stderr
, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index
, out_file_index
, in_file_index
);
1939 out_file
= output_files
[out_file_index
];
1940 in_file
= input_files
[in_file_index
];
1942 strcpy(out_file
->title
, in_file
->title
);
1943 strcpy(out_file
->author
, in_file
->author
);
1944 strcpy(out_file
->copyright
, in_file
->copyright
);
1945 strcpy(out_file
->comment
, in_file
->comment
);
1946 strcpy(out_file
->album
, in_file
->album
);
1947 out_file
->year
= in_file
->year
;
1948 out_file
->track
= in_file
->track
;
1949 strcpy(out_file
->genre
, in_file
->genre
);
1952 /* open files and write file headers */
1953 for(i
=0;i
<nb_output_files
;i
++) {
1954 os
= output_files
[i
];
1955 if (av_write_header(os
) < 0) {
1956 fprintf(stderr
, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i
);
1962 #ifndef CONFIG_WIN32
1963 if ( !using_stdin
&& verbose
>= 0) {
1964 fprintf(stderr
, "Press [q] to stop encoding\n");
1965 url_set_interrupt_cb(decode_interrupt_cb
);
1973 for(; received_sigterm
== 0;) {
1974 int file_index
, ist_index
;
1982 /* if 'q' pressed, exits */
1986 /* read_key() returns 0 on EOF */
1992 /* select the stream that we must read now by looking at the
1993 smallest output pts */
1995 for(i
=0;i
<nb_ostreams
;i
++) {
1998 os
= output_files
[ost
->file_index
];
1999 ist
= ist_table
[ost
->source_index
];
2000 if(ost
->st
->codec
.codec_type
== CODEC_TYPE_VIDEO
)
2001 opts
= ost
->sync_opts
* av_q2d(ost
->st
->codec
.time_base
);
2003 opts
= ost
->st
->pts
.val
* av_q2d(ost
->st
->time_base
);
2004 ipts
= (double)ist
->pts
;
2005 if (!file_table
[ist
->file_index
].eof_reached
){
2006 if(ipts
< ipts_min
) {
2008 if(input_sync
) file_index
= ist
->file_index
;
2010 if(opts
< opts_min
) {
2012 if(!input_sync
) file_index
= ist
->file_index
;
2015 if(ost
->frame_number
>= max_frames
[ost
->st
->codec
.codec_type
]){
2020 /* if none, if is finished */
2021 if (file_index
< 0) {
2025 /* finish if recording time exhausted */
2026 if (recording_time
> 0 && opts_min
>= (recording_time
/ 1000000.0))
2029 /* finish if limit size exhausted */
2030 if (limit_filesize
!= 0 && (limit_filesize
* 1024) < url_ftell(&output_files
[0]->pb
))
2033 /* read a frame from it and output it in the fifo */
2034 is
= input_files
[file_index
];
2035 if (av_read_frame(is
, &pkt
) < 0) {
2036 file_table
[file_index
].eof_reached
= 1;
2037 if (opt_shortest
) break; else continue; //
2041 stream_no_data
= is
;
2046 av_pkt_dump(stdout
, &pkt
, do_hex_dump
);
2048 /* the following test is needed in case new streams appear
2049 dynamically in stream : we ignore them */
2050 if (pkt
.stream_index
>= file_table
[file_index
].nb_streams
)
2051 goto discard_packet
;
2052 ist_index
= file_table
[file_index
].ist_index
+ pkt
.stream_index
;
2053 ist
= ist_table
[ist_index
];
2055 goto discard_packet
;
2057 // fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec.codec_type);
2058 if (pkt
.dts
!= AV_NOPTS_VALUE
&& ist
->next_pts
!= AV_NOPTS_VALUE
) {
2059 int64_t delta
= av_rescale_q(pkt
.dts
, ist
->st
->time_base
, AV_TIME_BASE_Q
) - ist
->next_pts
;
2060 if(ABS(delta
) > 10LL*AV_TIME_BASE
&& !copy_ts
){
2061 input_files_ts_offset
[ist
->file_index
]-= delta
;
2063 fprintf(stderr
, "timestamp discontinuity %lld, new offset= %lld\n", delta
, input_files_ts_offset
[ist
->file_index
]);
2064 for(i
=0; i
<file_table
[file_index
].nb_streams
; i
++){
2065 int index
= file_table
[file_index
].ist_index
+ i
;
2066 ist_table
[index
]->next_pts
+= delta
;
2067 ist_table
[index
]->is_start
=1;
2072 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
2073 if (output_packet(ist
, ist_index
, ost_table
, nb_ostreams
, &pkt
) < 0) {
2076 fprintf(stderr
, "Error while decoding stream #%d.%d\n",
2077 ist
->file_index
, ist
->index
);
2079 av_free_packet(&pkt
);
2084 av_free_packet(&pkt
);
2086 /* dump report by using the output first video and audio streams */
2087 print_report(output_files
, ost_table
, nb_ostreams
, 0);
2090 /* at the end of stream, we must flush the decoder buffers */
2091 for(i
=0;i
<nb_istreams
;i
++) {
2093 if (ist
->decoding_needed
) {
2094 output_packet(ist
, i
, ost_table
, nb_ostreams
, NULL
);
2100 /* write the trailer if needed and close file */
2101 for(i
=0;i
<nb_output_files
;i
++) {
2102 os
= output_files
[i
];
2103 av_write_trailer(os
);
2106 /* dump report by using the first video and audio streams */
2107 print_report(output_files
, ost_table
, nb_ostreams
, 1);
2109 /* close each encoder */
2110 for(i
=0;i
<nb_ostreams
;i
++) {
2112 if (ost
->encoding_needed
) {
2113 av_freep(&ost
->st
->codec
.stats_in
);
2114 avcodec_close(&ost
->st
->codec
);
2118 /* close each decoder */
2119 for(i
=0;i
<nb_istreams
;i
++) {
2121 if (ist
->decoding_needed
) {
2122 avcodec_close(&ist
->st
->codec
);
2130 av_freep(&bit_buffer
);
2131 av_free(file_table
);
2134 for(i
=0;i
<nb_istreams
;i
++) {
2141 for(i
=0;i
<nb_ostreams
;i
++) {
2145 fclose(ost
->logfile
);
2146 ost
->logfile
= NULL
;
2148 fifo_free(&ost
->fifo
); /* works even if fifo is not
2149 initialized but set to zero */
2150 av_free(ost
->pict_tmp
.data
[0]);
2151 if (ost
->video_resample
)
2152 img_resample_close(ost
->img_resample_ctx
);
2153 if (ost
->audio_resample
)
2154 audio_resample_close(ost
->resample
);
2167 int file_read(const char *filename
)
2170 unsigned char buffer
[1024];
2173 if (url_open(&h
, filename
, O_RDONLY
) < 0) {
2174 printf("could not open '%s'\n", filename
);
2178 len
= url_read(h
, buffer
, sizeof(buffer
));
2181 for(i
=0;i
<len
;i
++) putchar(buffer
[i
]);
2188 static void opt_image_format(const char *arg
)
2192 for(f
= first_image_format
; f
!= NULL
; f
= f
->next
) {
2193 if (!strcmp(arg
, f
->name
))
2197 fprintf(stderr
, "Unknown image format: '%s'\n", arg
);
2203 static void opt_format(const char *arg
)
2205 /* compatibility stuff for pgmyuv */
2206 if (!strcmp(arg
, "pgmyuv")) {
2207 pgmyuv_compatibility_hack
=1;
2208 // opt_image_format(arg);
2212 file_iformat
= av_find_input_format(arg
);
2213 file_oformat
= guess_format(arg
, NULL
, NULL
);
2214 if (!file_iformat
&& !file_oformat
) {
2215 fprintf(stderr
, "Unknown input or output format: %s\n", arg
);
2220 static void opt_video_bitrate(const char *arg
)
2222 video_bit_rate
= atoi(arg
) * 1000;
2225 static void opt_video_bitrate_tolerance(const char *arg
)
2227 video_bit_rate_tolerance
= atoi(arg
) * 1000;
2230 static void opt_video_bitrate_max(const char *arg
)
2232 video_rc_max_rate
= atoi(arg
) * 1000;
2235 static void opt_video_bitrate_min(const char *arg
)
2237 video_rc_min_rate
= atoi(arg
) * 1000;
2240 static void opt_video_buffer_size(const char *arg
)
2242 video_rc_buffer_size
= atoi(arg
) * 8*1024;
2245 static void opt_video_rc_eq(char *arg
)
2250 static void opt_video_rc_override_string(char *arg
)
2252 video_rc_override_string
= arg
;
2256 static void opt_workaround_bugs(const char *arg
)
2258 workaround_bugs
= atoi(arg
);
2261 static void opt_dct_algo(const char *arg
)
2263 dct_algo
= atoi(arg
);
2266 static void opt_idct_algo(const char *arg
)
2268 idct_algo
= atoi(arg
);
2271 static void opt_me_threshold(const char *arg
)
2273 me_threshold
= atoi(arg
);
2276 static void opt_mb_threshold(const char *arg
)
2278 mb_threshold
= atoi(arg
);
2281 static void opt_error_resilience(const char *arg
)
2283 error_resilience
= atoi(arg
);
2286 static void opt_error_concealment(const char *arg
)
2288 error_concealment
= atoi(arg
);
2291 static void opt_debug(const char *arg
)
2296 static void opt_vismv(const char *arg
)
2298 debug_mv
= atoi(arg
);
2301 static void opt_verbose(const char *arg
)
2303 verbose
= atoi(arg
);
2304 av_log_set_level(atoi(arg
));
2307 static void opt_frame_rate(const char *arg
)
2309 if (parse_frame_rate(&frame_rate
, &frame_rate_base
, arg
) < 0) {
2310 fprintf(stderr
, "Incorrect frame rate\n");
2315 static void opt_frame_crop_top(const char *arg
)
2317 frame_topBand
= atoi(arg
);
2318 if (frame_topBand
< 0) {
2319 fprintf(stderr
, "Incorrect top crop size\n");
2322 if ((frame_topBand
% 2) != 0) {
2323 fprintf(stderr
, "Top crop size must be a multiple of 2\n");
2326 if ((frame_topBand
) >= frame_height
){
2327 fprintf(stderr
, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2330 frame_height
-= frame_topBand
;
2333 static void opt_frame_crop_bottom(const char *arg
)
2335 frame_bottomBand
= atoi(arg
);
2336 if (frame_bottomBand
< 0) {
2337 fprintf(stderr
, "Incorrect bottom crop size\n");
2340 if ((frame_bottomBand
% 2) != 0) {
2341 fprintf(stderr
, "Bottom crop size must be a multiple of 2\n");
2344 if ((frame_bottomBand
) >= frame_height
){
2345 fprintf(stderr
, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2348 frame_height
-= frame_bottomBand
;
2351 static void opt_frame_crop_left(const char *arg
)
2353 frame_leftBand
= atoi(arg
);
2354 if (frame_leftBand
< 0) {
2355 fprintf(stderr
, "Incorrect left crop size\n");
2358 if ((frame_leftBand
% 2) != 0) {
2359 fprintf(stderr
, "Left crop size must be a multiple of 2\n");
2362 if ((frame_leftBand
) >= frame_width
){
2363 fprintf(stderr
, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2366 frame_width
-= frame_leftBand
;
2369 static void opt_frame_crop_right(const char *arg
)
2371 frame_rightBand
= atoi(arg
);
2372 if (frame_rightBand
< 0) {
2373 fprintf(stderr
, "Incorrect right crop size\n");
2376 if ((frame_rightBand
% 2) != 0) {
2377 fprintf(stderr
, "Right crop size must be a multiple of 2\n");
2380 if ((frame_rightBand
) >= frame_width
){
2381 fprintf(stderr
, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2384 frame_width
-= frame_rightBand
;
2387 static void opt_frame_size(const char *arg
)
2389 if (parse_image_size(&frame_width
, &frame_height
, arg
) < 0) {
2390 fprintf(stderr
, "Incorrect frame size\n");
2393 if ((frame_width
% 2) != 0 || (frame_height
% 2) != 0) {
2394 fprintf(stderr
, "Frame size must be a multiple of 2\n");
2400 #define SCALEBITS 10
2401 #define ONE_HALF (1 << (SCALEBITS - 1))
2402 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2404 #define RGB_TO_Y(r, g, b) \
2405 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2406 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2408 #define RGB_TO_U(r1, g1, b1, shift)\
2409 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2410 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2412 #define RGB_TO_V(r1, g1, b1, shift)\
2413 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2414 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2416 static void opt_pad_color(const char *arg
) {
2417 /* Input is expected to be six hex digits similar to
2418 how colors are expressed in html tags (but without the #) */
2419 int rgb
= strtol(arg
, NULL
, 16);
2423 g
= ((rgb
>> 8) & 255);
2426 padcolor
[0] = RGB_TO_Y(r
,g
,b
);
2427 padcolor
[1] = RGB_TO_U(r
,g
,b
,0);
2428 padcolor
[2] = RGB_TO_V(r
,g
,b
,0);
2431 static void opt_frame_pad_top(const char *arg
)
2433 frame_padtop
= atoi(arg
);
2434 if (frame_padtop
< 0) {
2435 fprintf(stderr
, "Incorrect top pad size\n");
2438 if ((frame_padtop
% 2) != 0) {
2439 fprintf(stderr
, "Top pad size must be a multiple of 2\n");
2444 static void opt_frame_pad_bottom(const char *arg
)
2446 frame_padbottom
= atoi(arg
);
2447 if (frame_padbottom
< 0) {
2448 fprintf(stderr
, "Incorrect bottom pad size\n");
2451 if ((frame_padbottom
% 2) != 0) {
2452 fprintf(stderr
, "Bottom pad size must be a multiple of 2\n");
2458 static void opt_frame_pad_left(const char *arg
)
2460 frame_padleft
= atoi(arg
);
2461 if (frame_padleft
< 0) {
2462 fprintf(stderr
, "Incorrect left pad size\n");
2465 if ((frame_padleft
% 2) != 0) {
2466 fprintf(stderr
, "Left pad size must be a multiple of 2\n");
2472 static void opt_frame_pad_right(const char *arg
)
2474 frame_padright
= atoi(arg
);
2475 if (frame_padright
< 0) {
2476 fprintf(stderr
, "Incorrect right pad size\n");
2479 if ((frame_padright
% 2) != 0) {
2480 fprintf(stderr
, "Right pad size must be a multiple of 2\n");
2486 static void opt_frame_pix_fmt(const char *arg
)
2488 frame_pix_fmt
= avcodec_get_pix_fmt(arg
);
2491 static void opt_frame_aspect_ratio(const char *arg
)
2497 p
= strchr(arg
, ':');
2499 x
= strtol(arg
, (char **)&arg
, 10);
2501 y
= strtol(arg
+1, (char **)&arg
, 10);
2503 ar
= (double)x
/ (double)y
;
2505 ar
= strtod(arg
, (char **)&arg
);
2508 fprintf(stderr
, "Incorrect aspect ratio specification.\n");
2511 frame_aspect_ratio
= ar
;
2514 static void opt_gop_size(const char *arg
)
2516 gop_size
= atoi(arg
);
2519 static void opt_b_frames(const char *arg
)
2521 b_frames
= atoi(arg
);
2522 if (b_frames
> FF_MAX_B_FRAMES
) {
2523 fprintf(stderr
, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES
);
2525 } else if (b_frames
< 1) {
2526 fprintf(stderr
, "\nNumber of B frames must be higher than 0\n");
2531 static void opt_mb_decision(const char *arg
)
2533 mb_decision
= atoi(arg
);
2536 static void opt_mb_cmp(const char *arg
)
2541 static void opt_ildct_cmp(const char *arg
)
2543 ildct_cmp
= atoi(arg
);
2546 static void opt_sub_cmp(const char *arg
)
2548 sub_cmp
= atoi(arg
);
2551 static void opt_cmp(const char *arg
)
2556 static void opt_pre_cmp(const char *arg
)
2558 pre_cmp
= atoi(arg
);
2561 static void opt_pre_me(const char *arg
)
2566 static void opt_lumi_mask(const char *arg
)
2568 lumi_mask
= atof(arg
);
2571 static void opt_dark_mask(const char *arg
)
2573 dark_mask
= atof(arg
);
2576 static void opt_scplx_mask(const char *arg
)
2578 scplx_mask
= atof(arg
);
2581 static void opt_tcplx_mask(const char *arg
)
2583 tcplx_mask
= atof(arg
);
2586 static void opt_p_mask(const char *arg
)
2591 static void opt_qscale(const char *arg
)
2593 video_qscale
= atof(arg
);
2594 if (video_qscale
< 0.01 ||
2595 video_qscale
> 255) {
2596 fprintf(stderr
, "qscale must be >= 0.01 and <= 255\n");
2601 static void opt_qsquish(const char *arg
)
2603 video_qsquish
= atof(arg
);
2604 if (video_qsquish
< 0.0 ||
2605 video_qsquish
> 99.0) {
2606 fprintf(stderr
, "qsquish must be >= 0.0 and <= 99.0\n");
2611 static void opt_lelim(const char *arg
)
2613 video_lelim
= atoi(arg
);
2614 if (video_lelim
< -99 ||
2616 fprintf(stderr
, "lelim must be >= -99 and <= 99\n");
2621 static void opt_celim(const char *arg
)
2623 video_celim
= atoi(arg
);
2624 if (video_celim
< -99 ||
2626 fprintf(stderr
, "celim must be >= -99 and <= 99\n");
2631 static void opt_lmax(const char *arg
)
2633 video_lmax
= atof(arg
)*FF_QP2LAMBDA
;
2636 static void opt_lmin(const char *arg
)
2638 video_lmin
= atof(arg
)*FF_QP2LAMBDA
;
2641 static void opt_qmin(const char *arg
)
2643 video_qmin
= atoi(arg
);
2644 if (video_qmin
< 1 ||
2646 fprintf(stderr
, "qmin must be >= 1 and <= 31\n");
2651 static void opt_qmax(const char *arg
)
2653 video_qmax
= atoi(arg
);
2654 if (video_qmax
< 1 ||
2656 fprintf(stderr
, "qmax must be >= 1 and <= 31\n");
2661 static void opt_mb_lmin(const char *arg
)
2663 video_mb_lmin
= atof(arg
)*FF_QP2LAMBDA
;
2664 if (video_mb_lmin
< 1 ||
2665 video_mb_lmin
> FF_LAMBDA_MAX
) {
2666 fprintf(stderr
, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX
/ FF_QP2LAMBDA
);
2671 static void opt_mb_lmax(const char *arg
)
2673 video_mb_lmax
= atof(arg
)*FF_QP2LAMBDA
;
2674 if (video_mb_lmax
< 1 ||
2675 video_mb_lmax
> FF_LAMBDA_MAX
) {
2676 fprintf(stderr
, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX
/ FF_QP2LAMBDA
);
2681 static void opt_qdiff(const char *arg
)
2683 video_qdiff
= atoi(arg
);
2684 if (video_qdiff
< 0 ||
2686 fprintf(stderr
, "qdiff must be >= 1 and <= 31\n");
2691 static void opt_qblur(const char *arg
)
2693 video_qblur
= atof(arg
);
2696 static void opt_qcomp(const char *arg
)
2698 video_qcomp
= atof(arg
);
2701 static void opt_rc_initial_cplx(const char *arg
)
2703 video_rc_initial_cplx
= atof(arg
);
2705 static void opt_b_qfactor(const char *arg
)
2707 video_b_qfactor
= atof(arg
);
2709 static void opt_i_qfactor(const char *arg
)
2711 video_i_qfactor
= atof(arg
);
2713 static void opt_b_qoffset(const char *arg
)
2715 video_b_qoffset
= atof(arg
);
2717 static void opt_i_qoffset(const char *arg
)
2719 video_i_qoffset
= atof(arg
);
2722 static void opt_ibias(const char *arg
)
2724 video_intra_quant_bias
= atoi(arg
);
2726 static void opt_pbias(const char *arg
)
2728 video_inter_quant_bias
= atoi(arg
);
2731 static void opt_packet_size(const char *arg
)
2733 packet_size
= atoi(arg
);
2736 static void opt_error_rate(const char *arg
)
2738 error_rate
= atoi(arg
);
2741 static void opt_strict(const char *arg
)
2746 static void opt_top_field_first(const char *arg
)
2748 top_field_first
= atoi(arg
);
2751 static void opt_noise_reduction(const char *arg
)
2753 noise_reduction
= atoi(arg
);
2756 static void opt_qns(const char *arg
)
2761 static void opt_sc_threshold(const char *arg
)
2763 sc_threshold
= atoi(arg
);
2766 static void opt_me_range(const char *arg
)
2768 me_range
= atoi(arg
);
2771 static void opt_thread_count(const char *arg
)
2773 thread_count
= atoi(arg
);
2774 #if !defined(HAVE_THREADS)
2776 fprintf(stderr
, "Warning: not compiled with thread support, using thread emulation\n");
2780 static void opt_audio_bitrate(const char *arg
)
2782 audio_bit_rate
= atoi(arg
) * 1000;
2785 static void opt_audio_rate(const char *arg
)
2787 audio_sample_rate
= atoi(arg
);
2790 static void opt_audio_channels(const char *arg
)
2792 audio_channels
= atoi(arg
);
2795 static void opt_video_device(const char *arg
)
2797 video_device
= av_strdup(arg
);
2800 static void opt_grab_device(const char *arg
)
2802 grab_device
= av_strdup(arg
);
2805 static void opt_video_channel(const char *arg
)
2807 video_channel
= strtol(arg
, NULL
, 0);
2810 static void opt_video_standard(const char *arg
)
2812 video_standard
= av_strdup(arg
);
2815 static void opt_audio_device(const char *arg
)
2817 audio_device
= av_strdup(arg
);
2820 static void opt_codec(int *pstream_copy
, int *pcodec_id
,
2821 int codec_type
, const char *arg
)
2825 if (!strcmp(arg
, "copy")) {
2830 if (!strcmp(p
->name
, arg
) && p
->type
== codec_type
)
2835 fprintf(stderr
, "Unknown codec '%s'\n", arg
);
2843 static void opt_audio_codec(const char *arg
)
2845 opt_codec(&audio_stream_copy
, &audio_codec_id
, CODEC_TYPE_AUDIO
, arg
);
2848 static void opt_audio_tag(const char *arg
)
2851 audio_codec_tag
= strtol(arg
, &tail
, 0);
2854 audio_codec_tag
= arg
[0] + (arg
[1]<<8) + (arg
[2]<<16) + (arg
[3]<<24);
2857 static void opt_video_tag(const char *arg
)
2860 video_codec_tag
= strtol(arg
, &tail
, 0);
2863 video_codec_tag
= arg
[0] + (arg
[1]<<8) + (arg
[2]<<16) + (arg
[3]<<24);
2866 static void add_frame_hooker(const char *arg
)
2871 char *args
= av_strdup(arg
);
2875 argv
[0] = strtok(args
, " ");
2876 while (argc
< 62 && (argv
[++argc
] = strtok(NULL
, " "))) {
2879 i
= frame_hook_add(argc
, argv
);
2882 fprintf(stderr
, "Failed to add video hook function: %s\n", arg
);
2887 const char *motion_str
[] = {
2897 static void opt_motion_estimation(const char *arg
)
2903 fprintf(stderr
, "Unknown motion estimation method '%s'\n", arg
);
2906 if (!strcmp(*p
, arg
))
2910 me_method
= (p
- motion_str
) + 1;
2913 static void opt_video_codec(const char *arg
)
2915 opt_codec(&video_stream_copy
, &video_codec_id
, CODEC_TYPE_VIDEO
, arg
);
2918 static void opt_subtitle_codec(const char *arg
)
2920 opt_codec(&subtitle_stream_copy
, &subtitle_codec_id
, CODEC_TYPE_SUBTITLE
, arg
);
2923 static void opt_map(const char *arg
)
2929 m
= &stream_maps
[nb_stream_maps
++];
2931 m
->file_index
= strtol(arg
, (char **)&p
, 0);
2935 m
->stream_index
= strtol(p
, (char **)&p
, 0);
2938 m
->sync_file_index
= strtol(p
, (char **)&p
, 0);
2941 m
->sync_stream_index
= strtol(p
, (char **)&p
, 0);
2943 m
->sync_file_index
= m
->file_index
;
2944 m
->sync_stream_index
= m
->stream_index
;
2948 static void opt_map_meta_data(const char *arg
)
2954 m
= &meta_data_maps
[nb_meta_data_maps
++];
2956 m
->out_file
= strtol(arg
, (char **)&p
, 0);
2960 m
->in_file
= strtol(p
, (char **)&p
, 0);
2963 static void opt_recording_time(const char *arg
)
2965 recording_time
= parse_date(arg
, 1);
2968 static void opt_start_time(const char *arg
)
2970 start_time
= parse_date(arg
, 1);
2973 static void opt_rec_timestamp(const char *arg
)
2975 rec_timestamp
= parse_date(arg
, 0) / 1000000;
2978 static void opt_input_ts_offset(const char *arg
)
2980 input_ts_offset
= parse_date(arg
, 1);
2983 static void opt_input_file(const char *filename
)
2985 AVFormatContext
*ic
;
2986 AVFormatParameters params
, *ap
= ¶ms
;
2987 int err
, i
, ret
, rfps
, rfps_base
;
2990 if (!strcmp(filename
, "-"))
2993 using_stdin
|= !strncmp(filename
, "pipe:", 5) ||
2994 !strcmp( filename
, "/dev/stdin" );
2996 /* get default parameters from command line */
2997 memset(ap
, 0, sizeof(*ap
));
2998 ap
->sample_rate
= audio_sample_rate
;
2999 ap
->channels
= audio_channels
;
3000 ap
->time_base
.den
= frame_rate
;
3001 ap
->time_base
.num
= frame_rate_base
;
3002 ap
->width
= frame_width
+ frame_padleft
+ frame_padright
;
3003 ap
->height
= frame_height
+ frame_padtop
+ frame_padbottom
;
3004 ap
->image_format
= image_format
;
3005 ap
->pix_fmt
= frame_pix_fmt
;
3006 ap
->device
= grab_device
;
3007 ap
->channel
= video_channel
;
3008 ap
->standard
= video_standard
;
3009 ap
->video_codec_id
= video_codec_id
;
3010 ap
->audio_codec_id
= audio_codec_id
;
3011 if(pgmyuv_compatibility_hack
)
3012 ap
->video_codec_id
= CODEC_ID_PGMYUV
;
3014 /* open the input file with generic libav function */
3015 err
= av_open_input_file(&ic
, filename
, file_iformat
, 0, ap
);
3017 print_error(filename
, err
);
3021 /* If not enough info to get the stream parameters, we decode the
3022 first frames to get it. (used in mpeg case for example) */
3023 ret
= av_find_stream_info(ic
);
3024 if (ret
< 0 && verbose
>= 0) {
3025 fprintf(stderr
, "%s: could not find codec parameters\n", filename
);
3029 timestamp
= start_time
;
3030 /* add the stream start time */
3031 if (ic
->start_time
!= AV_NOPTS_VALUE
)
3032 timestamp
+= ic
->start_time
;
3034 /* if seeking requested, we execute it */
3035 if (start_time
!= 0) {
3036 ret
= av_seek_frame(ic
, -1, timestamp
, AVSEEK_FLAG_BACKWARD
);
3038 fprintf(stderr
, "%s: could not seek to position %0.3f\n",
3039 filename
, (double)timestamp
/ AV_TIME_BASE
);
3041 /* reset seek info */
3045 /* update the current parameters so that they match the one of the input stream */
3046 for(i
=0;i
<ic
->nb_streams
;i
++) {
3047 AVCodecContext
*enc
= &ic
->streams
[i
]->codec
;
3048 #if defined(HAVE_THREADS)
3050 avcodec_thread_init(enc
, thread_count
);
3052 enc
->thread_count
= thread_count
;
3053 switch(enc
->codec_type
) {
3054 case CODEC_TYPE_AUDIO
:
3055 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
3056 audio_channels
= enc
->channels
;
3057 audio_sample_rate
= enc
->sample_rate
;
3059 ic
->streams
[i
]->discard
= AVDISCARD_ALL
;
3061 case CODEC_TYPE_VIDEO
:
3062 frame_height
= enc
->height
;
3063 frame_width
= enc
->width
;
3064 frame_aspect_ratio
= av_q2d(enc
->sample_aspect_ratio
) * enc
->width
/ enc
->height
;
3065 frame_pix_fmt
= enc
->pix_fmt
;
3066 rfps
= ic
->streams
[i
]->r_frame_rate
.num
;
3067 rfps_base
= ic
->streams
[i
]->r_frame_rate
.den
;
3068 enc
->workaround_bugs
= workaround_bugs
;
3069 enc
->error_resilience
= error_resilience
;
3070 enc
->error_concealment
= error_concealment
;
3071 enc
->idct_algo
= idct_algo
;
3073 enc
->debug_mv
= debug_mv
;
3074 enc
->lowres
= lowres
;
3075 if(lowres
) enc
->flags
|= CODEC_FLAG_EMU_EDGE
;
3077 enc
->flags
|= CODEC_FLAG_BITEXACT
;
3079 enc
->debug
|= FF_DEBUG_MV
;
3081 enc
->flags
|= CODEC_FLAG_GRAY
;
3083 if (enc
->time_base
.den
!= rfps
|| enc
->time_base
.num
!= rfps_base
) {
3086 fprintf(stderr
,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
3087 i
, (float)enc
->time_base
.den
/ enc
->time_base
.num
, enc
->time_base
.den
, enc
->time_base
.num
,
3089 (float)rfps
/ rfps_base
, rfps
, rfps_base
);
3091 /* update the current frame rate to match the stream frame rate */
3093 frame_rate_base
= rfps_base
;
3095 enc
->rate_emu
= rate_emu
;
3097 ic
->streams
[i
]->discard
= AVDISCARD_ALL
;
3098 else if(video_discard
)
3099 ic
->streams
[i
]->discard
= video_discard
;
3101 case CODEC_TYPE_DATA
:
3103 case CODEC_TYPE_SUBTITLE
:
3110 input_files
[nb_input_files
] = ic
;
3111 input_files_ts_offset
[nb_input_files
] = input_ts_offset
- (copy_ts ?
0 : timestamp
);
3112 /* dump the file content */
3114 dump_format(ic
, nb_input_files
, filename
, 0);
3117 file_iformat
= NULL
;
3118 file_oformat
= NULL
;
3119 image_format
= NULL
;
3127 static void opt_grab(const char *arg
)
3129 file_iformat
= av_find_input_format(arg
);
3133 static void check_audio_video_inputs(int *has_video_ptr
, int *has_audio_ptr
)
3135 int has_video
, has_audio
, i
, j
;
3136 AVFormatContext
*ic
;
3140 for(j
=0;j
<nb_input_files
;j
++) {
3141 ic
= input_files
[j
];
3142 for(i
=0;i
<ic
->nb_streams
;i
++) {
3143 AVCodecContext
*enc
= &ic
->streams
[i
]->codec
;
3144 switch(enc
->codec_type
) {
3145 case CODEC_TYPE_AUDIO
:
3148 case CODEC_TYPE_VIDEO
:
3151 case CODEC_TYPE_DATA
:
3152 case CODEC_TYPE_SUBTITLE
:
3159 *has_video_ptr
= has_video
;
3160 *has_audio_ptr
= has_audio
;
3163 static void new_video_stream(AVFormatContext
*oc
)
3166 AVCodecContext
*video_enc
;
3169 st
= av_new_stream(oc
, oc
->nb_streams
);
3171 fprintf(stderr
, "Could not alloc stream\n");
3174 #if defined(HAVE_THREADS)
3176 avcodec_thread_init(&st
->codec
, thread_count
);
3179 video_enc
= &st
->codec
;
3182 video_enc
->codec_tag
= video_codec_tag
;
3184 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
3185 video_enc
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
3186 if (video_stream_copy
) {
3187 st
->stream_copy
= 1;
3188 video_enc
->codec_type
= CODEC_TYPE_VIDEO
;
3194 codec_id
= av_guess_codec(oc
->oformat
, NULL
, oc
->filename
, NULL
, CODEC_TYPE_VIDEO
);
3195 if (video_codec_id
!= CODEC_ID_NONE
)
3196 codec_id
= video_codec_id
;
3198 video_enc
->codec_id
= codec_id
;
3199 codec
= avcodec_find_encoder(codec_id
);
3201 video_enc
->bit_rate
= video_bit_rate
;
3202 video_enc
->bit_rate_tolerance
= video_bit_rate_tolerance
;
3203 video_enc
->time_base
.den
= frame_rate
;
3204 video_enc
->time_base
.num
= frame_rate_base
;
3205 if(codec
&& codec
->supported_framerates
){
3206 const AVRational
*p
= codec
->supported_framerates
;
3207 AVRational req
= (AVRational
){frame_rate
, frame_rate_base
};
3208 const AVRational
*best
=NULL
;
3209 AVRational best_error
= (AVRational
){INT_MAX
, 1};
3210 for(; p
->den
!=0; p
++){
3211 AVRational error
= av_sub_q(req
, *p
);
3212 if(error
.num
<0) error
.num
*= -1;
3213 if(av_cmp_q(error
, best_error
) < 0){
3218 video_enc
->time_base
.den
= best
->num
;
3219 video_enc
->time_base
.num
= best
->den
;
3222 video_enc
->width
= frame_width
+ frame_padright
+ frame_padleft
;
3223 video_enc
->height
= frame_height
+ frame_padtop
+ frame_padbottom
;
3224 video_enc
->sample_aspect_ratio
= av_d2q(frame_aspect_ratio
*frame_height
/frame_width
, 255);
3225 video_enc
->pix_fmt
= frame_pix_fmt
;
3227 if(codec
&& codec
->pix_fmts
){
3228 const enum PixelFormat
*p
= codec
->pix_fmts
;
3230 if(*p
== video_enc
->pix_fmt
)
3234 video_enc
->pix_fmt
= codec
->pix_fmts
[0];
3238 video_enc
->gop_size
= gop_size
;
3240 video_enc
->gop_size
= 0;
3241 if (video_qscale
|| same_quality
) {
3242 video_enc
->flags
|= CODEC_FLAG_QSCALE
;
3243 video_enc
->global_quality
=
3244 st
->quality
= FF_QP2LAMBDA
* video_qscale
;
3248 video_enc
->intra_matrix
= intra_matrix
;
3250 video_enc
->inter_matrix
= inter_matrix
;
3253 video_enc
->flags
|= CODEC_FLAG_BITEXACT
;
3255 video_enc
->mb_decision
= mb_decision
;
3256 video_enc
->mb_cmp
= mb_cmp
;
3257 video_enc
->ildct_cmp
= ildct_cmp
;
3258 video_enc
->me_sub_cmp
= sub_cmp
;
3259 video_enc
->me_cmp
= cmp
;
3260 video_enc
->me_pre_cmp
= pre_cmp
;
3261 video_enc
->pre_me
= pre_me
;
3262 video_enc
->lumi_masking
= lumi_mask
;
3263 video_enc
->dark_masking
= dark_mask
;
3264 video_enc
->spatial_cplx_masking
= scplx_mask
;
3265 video_enc
->temporal_cplx_masking
= tcplx_mask
;
3266 video_enc
->p_masking
= p_mask
;
3267 video_enc
->quantizer_noise_shaping
= qns
;
3270 video_enc
->flags
|= CODEC_FLAG_H263P_UMV
;
3273 video_enc
->flags
|= CODEC_FLAG_H263P_SLICE_STRUCT
;
3276 video_enc
->flags
|= CODEC_FLAG_H263P_AIC
;
3279 video_enc
->flags
|= CODEC_FLAG_H263P_AIV
;
3282 video_enc
->flags
|= CODEC_FLAG_4MV
;
3285 video_enc
->flags
|= CODEC_FLAG_OBMC
;
3288 video_enc
->flags
|= CODEC_FLAG_LOOP_FILTER
;
3292 video_enc
->flags
|= CODEC_FLAG_PART
;
3295 video_enc
->flags
|= CODEC_FLAG_ALT_SCAN
;
3298 video_enc
->flags
|= CODEC_FLAG_TRELLIS_QUANT
;
3301 video_enc
->flags
|= CODEC_FLAG_MV0
;
3303 if (do_normalize_aqp
) {
3304 video_enc
->flags
|= CODEC_FLAG_NORMALIZE_AQP
;
3306 if (use_scan_offset
) {
3307 video_enc
->flags
|= CODEC_FLAG_SVCD_SCAN_OFFSET
;
3310 video_enc
->flags
|= CODEC_FLAG_CLOSED_GOP
;
3313 video_enc
->flags2
|= CODEC_FLAG2_STRICT_GOP
;
3316 video_enc
->flags
|= CODEC_FLAG_QPEL
;
3319 video_enc
->flags
|= CODEC_FLAG_QP_RD
;
3322 video_enc
->flags
|= CODEC_FLAG_CBP_RD
;
3325 video_enc
->max_b_frames
= b_frames
;
3326 video_enc
->b_frame_strategy
= b_strategy
;
3327 video_enc
->b_quant_factor
= 2.0;
3329 if (do_interlace_dct
) {
3330 video_enc
->flags
|= CODEC_FLAG_INTERLACED_DCT
;
3332 if (do_interlace_me
) {
3333 video_enc
->flags
|= CODEC_FLAG_INTERLACED_ME
;
3336 video_enc
->flags2
|= CODEC_FLAG2_NO_OUTPUT
;
3339 video_enc
->flags
|= CODEC_FLAG_GRAY
;
3341 video_enc
->qmin
= video_qmin
;
3342 video_enc
->qmax
= video_qmax
;
3343 video_enc
->lmin
= video_lmin
;
3344 video_enc
->lmax
= video_lmax
;
3345 video_enc
->rc_qsquish
= video_qsquish
;
3346 video_enc
->luma_elim_threshold
= video_lelim
;
3347 video_enc
->chroma_elim_threshold
= video_celim
;
3348 video_enc
->mb_lmin
= video_mb_lmin
;
3349 video_enc
->mb_lmax
= video_mb_lmax
;
3350 video_enc
->max_qdiff
= video_qdiff
;
3351 video_enc
->qblur
= video_qblur
;
3352 video_enc
->qcompress
= video_qcomp
;
3353 video_enc
->rc_eq
= video_rc_eq
;
3354 video_enc
->debug
= debug
;
3355 video_enc
->debug_mv
= debug_mv
;
3356 video_enc
->workaround_bugs
= workaround_bugs
;
3357 video_enc
->thread_count
= thread_count
;
3358 p
= video_rc_override_string
;
3361 int e
=sscanf(p
, "%d,%d,%d", &start
, &end
, &q
);
3363 fprintf(stderr
, "error parsing rc_override\n");
3366 video_enc
->rc_override
=
3367 av_realloc(video_enc
->rc_override
,
3368 sizeof(RcOverride
)*(i
+1));
3369 video_enc
->rc_override
[i
].start_frame
= start
;
3370 video_enc
->rc_override
[i
].end_frame
= end
;
3372 video_enc
->rc_override
[i
].qscale
= q
;
3373 video_enc
->rc_override
[i
].quality_factor
= 1.0;
3376 video_enc
->rc_override
[i
].qscale
= 0;
3377 video_enc
->rc_override
[i
].quality_factor
= -q
/100.0;
3382 video_enc
->rc_override_count
=i
;
3384 video_enc
->rc_max_rate
= video_rc_max_rate
;
3385 video_enc
->rc_min_rate
= video_rc_min_rate
;
3386 video_enc
->rc_buffer_size
= video_rc_buffer_size
;
3387 video_enc
->rc_initial_buffer_occupancy
= video_rc_buffer_size
*3/4;
3388 video_enc
->rc_buffer_aggressivity
= video_rc_buffer_aggressivity
;
3389 video_enc
->rc_initial_cplx
= video_rc_initial_cplx
;
3390 video_enc
->i_quant_factor
= video_i_qfactor
;
3391 video_enc
->b_quant_factor
= video_b_qfactor
;
3392 video_enc
->i_quant_offset
= video_i_qoffset
;
3393 video_enc
->b_quant_offset
= video_b_qoffset
;
3394 video_enc
->intra_quant_bias
= video_intra_quant_bias
;
3395 video_enc
->inter_quant_bias
= video_inter_quant_bias
;
3396 video_enc
->dct_algo
= dct_algo
;
3397 video_enc
->idct_algo
= idct_algo
;
3398 video_enc
->me_threshold
= me_threshold
;
3399 video_enc
->mb_threshold
= mb_threshold
;
3400 video_enc
->intra_dc_precision
= intra_dc_precision
- 8;
3401 video_enc
->strict_std_compliance
= strict
;
3402 video_enc
->error_rate
= error_rate
;
3403 video_enc
->noise_reduction
= noise_reduction
;
3404 video_enc
->scenechange_threshold
= sc_threshold
;
3405 video_enc
->me_range
= me_range
;
3406 video_enc
->coder_type
= coder
;
3407 video_enc
->context_model
= context
;
3408 video_enc
->prediction_method
= predictor
;
3409 video_enc
->profile
= video_profile
;
3410 video_enc
->level
= video_level
;
3411 video_enc
->nsse_weight
= nsse_weight
;
3412 video_enc
->me_subpel_quality
= subpel_quality
;
3413 video_enc
->me_penalty_compensation
= me_penalty_compensation
;
3414 video_enc
->frame_skip_threshold
= frame_skip_threshold
;
3415 video_enc
->frame_skip_factor
= frame_skip_factor
;
3416 video_enc
->frame_skip_exp
= frame_skip_exp
;
3417 video_enc
->frame_skip_cmp
= frame_skip_cmp
;
3420 video_enc
->rtp_mode
= 1;
3421 video_enc
->rtp_payload_size
= packet_size
;
3425 video_enc
->flags
|= CODEC_FLAG_PSNR
;
3427 video_enc
->me_method
= me_method
;
3432 video_enc
->flags
|= CODEC_FLAG_PASS1
;
3434 video_enc
->flags
|= CODEC_FLAG_PASS2
;
3439 /* reset some key parameters */
3441 video_codec_id
= CODEC_ID_NONE
;
3442 video_stream_copy
= 0;
3445 static void new_audio_stream(AVFormatContext
*oc
)
3448 AVCodecContext
*audio_enc
;
3451 st
= av_new_stream(oc
, oc
->nb_streams
);
3453 fprintf(stderr
, "Could not alloc stream\n");
3456 #if defined(HAVE_THREADS)
3458 avcodec_thread_init(&st
->codec
, thread_count
);
3461 audio_enc
= &st
->codec
;
3462 audio_enc
->codec_type
= CODEC_TYPE_AUDIO
;
3465 audio_enc
->codec_tag
= audio_codec_tag
;
3467 if (oc
->oformat
->flags
& AVFMT_GLOBALHEADER
)
3468 audio_enc
->flags
|= CODEC_FLAG_GLOBAL_HEADER
;
3469 if (audio_stream_copy
) {
3470 st
->stream_copy
= 1;
3471 audio_enc
->channels
= audio_channels
;
3473 codec_id
= av_guess_codec(oc
->oformat
, NULL
, oc
->filename
, NULL
, CODEC_TYPE_AUDIO
);
3474 if (audio_codec_id
!= CODEC_ID_NONE
)
3475 codec_id
= audio_codec_id
;
3476 audio_enc
->codec_id
= codec_id
;
3478 audio_enc
->bit_rate
= audio_bit_rate
;
3479 audio_enc
->strict_std_compliance
= strict
;
3480 audio_enc
->thread_count
= thread_count
;
3481 /* For audio codecs other than AC3 or DTS we limit */
3482 /* the number of coded channels to stereo */
3483 if (audio_channels
> 2 && codec_id
!= CODEC_ID_AC3
3484 && codec_id
!= CODEC_ID_DTS
) {
3485 audio_enc
->channels
= 2;
3487 audio_enc
->channels
= audio_channels
;
3489 audio_enc
->sample_rate
= audio_sample_rate
;
3490 if (audio_language
) {
3491 pstrcpy(st
->language
, sizeof(st
->language
), audio_language
);
3492 av_free(audio_language
);
3493 audio_language
= NULL
;
3496 /* reset some key parameters */
3498 audio_codec_id
= CODEC_ID_NONE
;
3499 audio_stream_copy
= 0;
3502 static void opt_new_subtitle_stream(void)
3504 AVFormatContext
*oc
;
3506 AVCodecContext
*subtitle_enc
;
3508 if (nb_output_files
<= 0) {
3509 fprintf(stderr
, "At least one output file must be specified\n");
3512 oc
= output_files
[nb_output_files
- 1];
3514 st
= av_new_stream(oc
, oc
->nb_streams
);
3516 fprintf(stderr
, "Could not alloc stream\n");
3520 subtitle_enc
= &st
->codec
;
3521 subtitle_enc
->codec_type
= CODEC_TYPE_SUBTITLE
;
3522 if (subtitle_stream_copy
) {
3523 st
->stream_copy
= 1;
3525 subtitle_enc
->codec_id
= subtitle_codec_id
;
3528 if (subtitle_language
) {
3529 pstrcpy(st
->language
, sizeof(st
->language
), subtitle_language
);
3530 av_free(subtitle_language
);
3531 subtitle_language
= NULL
;
3534 subtitle_codec_id
= CODEC_ID_NONE
;
3535 subtitle_stream_copy
= 0;
3538 static void opt_new_audio_stream(void)
3540 AVFormatContext
*oc
;
3541 if (nb_output_files
<= 0) {
3542 fprintf(stderr
, "At least one output file must be specified\n");
3545 oc
= output_files
[nb_output_files
- 1];
3546 new_audio_stream(oc
);
3549 static void opt_new_video_stream(void)
3551 AVFormatContext
*oc
;
3552 if (nb_output_files
<= 0) {
3553 fprintf(stderr
, "At least one output file must be specified\n");
3556 oc
= output_files
[nb_output_files
- 1];
3557 new_video_stream(oc
);
3560 static void opt_output_file(const char *filename
)
3562 AVFormatContext
*oc
;
3563 int use_video
, use_audio
, input_has_video
, input_has_audio
;
3564 AVFormatParameters params
, *ap
= ¶ms
;
3566 if (!strcmp(filename
, "-"))
3569 oc
= av_alloc_format_context();
3571 if (!file_oformat
) {
3572 file_oformat
= guess_format(NULL
, filename
, NULL
);
3573 if (!file_oformat
) {
3574 fprintf(stderr
, "Unable for find a suitable output format for '%s'\n",
3580 oc
->oformat
= file_oformat
;
3581 pstrcpy(oc
->filename
, sizeof(oc
->filename
), filename
);
3583 if (!strcmp(file_oformat
->name
, "ffm") &&
3584 strstart(filename
, "http:", NULL
)) {
3585 /* special case for files sent to ffserver: we get the stream
3586 parameters from ffserver */
3587 if (read_ffserver_streams(oc
, filename
) < 0) {
3588 fprintf(stderr
, "Could not read stream parameters from '%s'\n", filename
);
3592 use_video
= file_oformat
->video_codec
!= CODEC_ID_NONE
|| video_stream_copy
;
3593 use_audio
= file_oformat
->audio_codec
!= CODEC_ID_NONE
|| audio_stream_copy
;
3595 /* disable if no corresponding type found and at least one
3597 if (nb_input_files
> 0) {
3598 check_audio_video_inputs(&input_has_video
, &input_has_audio
);
3599 if (!input_has_video
)
3601 if (!input_has_audio
)
3605 /* manual disable */
3606 if (audio_disable
) {
3609 if (video_disable
) {
3614 new_video_stream(oc
);
3618 new_audio_stream(oc
);
3621 if (!oc
->nb_streams
) {
3622 fprintf(stderr
, "No audio or video streams available\n");
3626 oc
->timestamp
= rec_timestamp
;
3629 pstrcpy(oc
->title
, sizeof(oc
->title
), str_title
);
3631 pstrcpy(oc
->author
, sizeof(oc
->author
), str_author
);
3633 pstrcpy(oc
->copyright
, sizeof(oc
->copyright
), str_copyright
);
3635 pstrcpy(oc
->comment
, sizeof(oc
->comment
), str_comment
);
3638 output_files
[nb_output_files
++] = oc
;
3640 /* check filename in case of an image number is expected */
3641 if (oc
->oformat
->flags
& AVFMT_NEEDNUMBER
) {
3642 if (filename_number_test(oc
->filename
) < 0) {
3643 print_error(oc
->filename
, AVERROR_NUMEXPECTED
);
3648 if (!(oc
->oformat
->flags
& AVFMT_NOFILE
)) {
3649 /* test if it already exists to avoid loosing precious files */
3650 if (!file_overwrite
&&
3651 (strchr(filename
, ':') == NULL
||
3652 strstart(filename
, "file:", NULL
))) {
3653 if (url_exist(filename
)) {
3656 if ( !using_stdin
) {
3657 fprintf(stderr
,"File '%s' already exists. Overwrite ? [y/N] ", filename
);
3660 if (toupper(c
) != 'Y') {
3661 fprintf(stderr
, "Not overwriting - exiting\n");
3666 fprintf(stderr
,"File '%s' already exists. Exiting.\n", filename
);
3673 if (url_fopen(&oc
->pb
, filename
, URL_WRONLY
) < 0) {
3674 fprintf(stderr
, "Could not open '%s'\n", filename
);
3679 memset(ap
, 0, sizeof(*ap
));
3680 ap
->image_format
= image_format
;
3681 if (av_set_parameters(oc
, ap
) < 0) {
3682 fprintf(stderr
, "%s: Invalid encoding parameters\n",
3687 oc
->packet_size
= mux_packet_size
;
3688 oc
->mux_rate
= mux_rate
;
3689 oc
->preload
= (int)(mux_preload
*AV_TIME_BASE
);
3690 oc
->max_delay
= (int)(mux_max_delay
*AV_TIME_BASE
);
3692 /* reset some options */
3693 file_oformat
= NULL
;
3694 file_iformat
= NULL
;
3695 image_format
= NULL
;
3698 /* prepare dummy protocols for grab */
3699 static void prepare_grab(void)
3701 int has_video
, has_audio
, i
, j
;
3702 AVFormatContext
*oc
;
3703 AVFormatContext
*ic
;
3704 AVFormatParameters vp1
, *vp
= &vp1
;
3705 AVFormatParameters ap1
, *ap
= &ap1
;
3707 /* see if audio/video inputs are needed */
3710 memset(ap
, 0, sizeof(*ap
));
3711 memset(vp
, 0, sizeof(*vp
));
3712 vp
->time_base
.num
= 1;
3713 for(j
=0;j
<nb_output_files
;j
++) {
3714 oc
= output_files
[j
];
3715 for(i
=0;i
<oc
->nb_streams
;i
++) {
3716 AVCodecContext
*enc
= &oc
->streams
[i
]->codec
;
3717 switch(enc
->codec_type
) {
3718 case CODEC_TYPE_AUDIO
:
3719 if (enc
->sample_rate
> ap
->sample_rate
)
3720 ap
->sample_rate
= enc
->sample_rate
;
3721 if (enc
->channels
> ap
->channels
)
3722 ap
->channels
= enc
->channels
;
3725 case CODEC_TYPE_VIDEO
:
3726 if (enc
->width
> vp
->width
)
3727 vp
->width
= enc
->width
;
3728 if (enc
->height
> vp
->height
)
3729 vp
->height
= enc
->height
;
3731 if (vp
->time_base
.num
*(int64_t)enc
->time_base
.den
> enc
->time_base
.num
*(int64_t)vp
->time_base
.den
){
3732 vp
->time_base
= enc
->time_base
;
3742 if (has_video
== 0 && has_audio
== 0) {
3743 fprintf(stderr
, "Output file must have at least one audio or video stream\n");
3748 AVInputFormat
*fmt1
;
3749 fmt1
= av_find_input_format(video_grab_format
);
3750 vp
->device
= video_device
;
3751 vp
->channel
= video_channel
;
3752 vp
->standard
= video_standard
;
3753 if (av_open_input_file(&ic
, "", fmt1
, 0, vp
) < 0) {
3754 fprintf(stderr
, "Could not find video grab device\n");
3757 /* If not enough info to get the stream parameters, we decode the
3758 first frames to get it. */
3759 if ((ic
->ctx_flags
& AVFMTCTX_NOHEADER
) && av_find_stream_info(ic
) < 0) {
3760 fprintf(stderr
, "Could not find video grab parameters\n");
3763 /* by now video grab has one stream */
3764 ic
->streams
[0]->r_frame_rate
.num
= vp
->time_base
.den
;
3765 ic
->streams
[0]->r_frame_rate
.den
= vp
->time_base
.num
;
3766 input_files
[nb_input_files
] = ic
;
3769 dump_format(ic
, nb_input_files
, "", 0);
3773 if (has_audio
&& audio_grab_format
) {
3774 AVInputFormat
*fmt1
;
3775 fmt1
= av_find_input_format(audio_grab_format
);
3776 ap
->device
= audio_device
;
3777 if (av_open_input_file(&ic
, "", fmt1
, 0, ap
) < 0) {
3778 fprintf(stderr
, "Could not find audio grab device\n");
3781 input_files
[nb_input_files
] = ic
;
3784 dump_format(ic
, nb_input_files
, "", 0);
3790 /* same option as mencoder */
3791 static void opt_pass(const char *pass_str
)
3794 pass
= atoi(pass_str
);
3795 if (pass
!= 1 && pass
!= 2) {
3796 fprintf(stderr
, "pass number can be only 1 or 2\n");
3802 #if defined(CONFIG_WIN32) || defined(CONFIG_OS2)
3803 static int64_t getutime(void)
3805 return av_gettime();
3808 static int64_t getutime(void)
3810 struct rusage rusage
;
3812 getrusage(RUSAGE_SELF
, &rusage
);
3813 return (rusage
.ru_utime
.tv_sec
* 1000000LL) + rusage
.ru_utime
.tv_usec
;
3817 extern int ffm_nopts
;
3819 static void opt_bitexact(void)
3822 /* disable generate of real time pts in ffm (need to be supressed anyway) */
3826 static void show_formats(void)
3828 AVInputFormat
*ifmt
;
3829 AVOutputFormat
*ofmt
;
3830 AVImageFormat
*image_fmt
;
3833 const char **pp
, *last_name
;
3835 printf("File formats:\n");
3840 const char *name
=NULL
;
3841 const char *long_name
=NULL
;
3843 for(ofmt
= first_oformat
; ofmt
!= NULL
; ofmt
= ofmt