Fix neverending loop which might happen when sending high-bitrate MPEG2
[ffmpeg-lucabe.git] / ffmpeg.c
blob8cfa7b348ed6faa979c3eaafec25a5a13dae1215
1 /*
2 * FFmpeg main
3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include "libavformat/avformat.h"
31 #include "libavdevice/avdevice.h"
32 #include "libswscale/swscale.h"
33 #include "libavformat/framehook.h"
34 #include "libavcodec/opt.h"
35 #include "libavutil/fifo.h"
36 #include "libavutil/avstring.h"
37 #include "libavformat/os_support.h"
39 #ifdef HAVE_SYS_RESOURCE_H
40 #include <sys/types.h>
41 #include <sys/resource.h>
42 #elif defined(HAVE_GETPROCESSTIMES)
43 #include <windows.h>
44 #endif
46 #if defined(HAVE_TERMIOS_H)
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include <sys/ioctl.h>
50 #include <sys/time.h>
51 #include <termios.h>
52 #elif defined(HAVE_CONIO_H)
53 #include <conio.h>
54 #endif
55 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
56 #include <time.h>
58 #include "cmdutils.h"
60 #undef NDEBUG
61 #include <assert.h>
63 #undef exit
65 const char program_name[] = "FFmpeg";
66 const int program_birth_year = 2000;
68 /* select an input stream for an output stream */
69 typedef struct AVStreamMap {
70 int file_index;
71 int stream_index;
72 int sync_file_index;
73 int sync_stream_index;
74 } AVStreamMap;
76 /** select an input file for an output file */
77 typedef struct AVMetaDataMap {
78 int out_file;
79 int in_file;
80 } AVMetaDataMap;
82 static const OptionDef options[];
84 #define MAX_FILES 20
86 static AVFormatContext *input_files[MAX_FILES];
87 static int64_t input_files_ts_offset[MAX_FILES];
88 static int nb_input_files = 0;
90 static AVFormatContext *output_files[MAX_FILES];
91 static int nb_output_files = 0;
93 static AVStreamMap stream_maps[MAX_FILES];
94 static int nb_stream_maps;
96 static AVMetaDataMap meta_data_maps[MAX_FILES];
97 static int nb_meta_data_maps;
99 static AVInputFormat *file_iformat;
100 static AVOutputFormat *file_oformat;
101 static int frame_width = 0;
102 static int frame_height = 0;
103 static float frame_aspect_ratio = 0;
104 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
105 static int frame_padtop = 0;
106 static int frame_padbottom = 0;
107 static int frame_padleft = 0;
108 static int frame_padright = 0;
109 static int padcolor[3] = {16,128,128}; /* default to black */
110 static int frame_topBand = 0;
111 static int frame_bottomBand = 0;
112 static int frame_leftBand = 0;
113 static int frame_rightBand = 0;
114 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
115 static AVRational frame_rate = (AVRational) {0,0};
116 static float video_qscale = 0;
117 static int video_qdiff = 3;
118 static uint16_t *intra_matrix = NULL;
119 static uint16_t *inter_matrix = NULL;
120 #if 0 //experimental, (can be removed)
121 static float video_rc_qsquish=1.0;
122 static float video_rc_qmod_amp=0;
123 static int video_rc_qmod_freq=0;
124 #endif
125 static const char *video_rc_override_string=NULL;
126 static int video_disable = 0;
127 static int video_discard = 0;
128 static char *video_codec_name = NULL;
129 static int video_codec_tag = 0;
130 static int same_quality = 0;
131 static int do_deinterlace = 0;
132 static int strict = 0;
133 static int top_field_first = -1;
134 static int me_threshold = 0;
135 static int intra_dc_precision = 8;
136 static int loop_input = 0;
137 static int loop_output = AVFMT_NOOUTPUTLOOP;
138 static int qp_hist = 0;
140 static int intra_only = 0;
141 static int audio_sample_rate = 44100;
142 #define QSCALE_NONE -99999
143 static float audio_qscale = QSCALE_NONE;
144 static int audio_disable = 0;
145 static int audio_channels = 1;
146 static char *audio_codec_name = NULL;
147 static int audio_codec_tag = 0;
148 static char *audio_language = NULL;
150 static int subtitle_disable = 0;
151 static char *subtitle_codec_name = NULL;
152 static char *subtitle_language = NULL;
154 static float mux_preload= 0.5;
155 static float mux_max_delay= 0.7;
157 static int64_t recording_time = 0;
158 static int64_t start_time = 0;
159 static int64_t rec_timestamp = 0;
160 static int64_t input_ts_offset = 0;
161 static int file_overwrite = 0;
162 static char *str_title = NULL;
163 static char *str_author = NULL;
164 static char *str_copyright = NULL;
165 static char *str_comment = NULL;
166 static char *str_genre = NULL;
167 static char *str_album = NULL;
168 static int do_benchmark = 0;
169 static int do_hex_dump = 0;
170 static int do_pkt_dump = 0;
171 static int do_psnr = 0;
172 static int do_pass = 0;
173 static char *pass_logfilename = NULL;
174 static int audio_stream_copy = 0;
175 static int video_stream_copy = 0;
176 static int subtitle_stream_copy = 0;
177 static int video_sync_method= 1;
178 static int audio_sync_method= 0;
179 static float audio_drift_threshold= 0.1;
180 static int copy_ts= 0;
181 static int opt_shortest = 0; //
182 static int video_global_header = 0;
183 static char *vstats_filename;
184 static FILE *vstats_file;
185 static int opt_programid = 0;
187 static int rate_emu = 0;
189 static int video_channel = 0;
190 static char *video_standard;
192 static int audio_volume = 256;
194 static int using_stdin = 0;
195 static int using_vhook = 0;
196 static int verbose = 1;
197 static int thread_count= 1;
198 static int q_pressed = 0;
199 static int64_t video_size = 0;
200 static int64_t audio_size = 0;
201 static int64_t extra_size = 0;
202 static int nb_frames_dup = 0;
203 static int nb_frames_drop = 0;
204 static int input_sync;
205 static uint64_t limit_filesize = 0; //
207 static int pgmyuv_compatibility_hack=0;
208 static float dts_delta_threshold = 10;
210 static unsigned int sws_flags = SWS_BICUBIC;
212 static const char **opt_names;
213 static int opt_name_count;
214 static AVCodecContext *avctx_opts[CODEC_TYPE_NB];
215 static AVFormatContext *avformat_opts;
216 static struct SwsContext *sws_opts;
217 static int64_t timer_start;
219 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
220 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
221 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
222 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
224 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
226 struct AVInputStream;
228 typedef struct AVOutputStream {
229 int file_index; /* file index */
230 int index; /* stream index in the output file */
231 int source_index; /* AVInputStream index */
232 AVStream *st; /* stream in the output file */
233 int encoding_needed; /* true if encoding needed for this stream */
234 int frame_number;
235 /* input pts and corresponding output pts
236 for A/V sync */
237 //double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
238 struct AVInputStream *sync_ist; /* input stream to sync against */
239 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
240 /* video only */
241 int video_resample;
242 AVFrame pict_tmp; /* temporary image for resampling */
243 struct SwsContext *img_resample_ctx; /* for image resampling */
244 int resample_height;
246 int video_crop;
247 int topBand; /* cropping area sizes */
248 int leftBand;
250 int video_pad;
251 int padtop; /* padding area sizes */
252 int padbottom;
253 int padleft;
254 int padright;
256 /* audio only */
257 int audio_resample;
258 ReSampleContext *resample; /* for audio resampling */
259 AVFifoBuffer fifo; /* for compression: one audio fifo per codec */
260 FILE *logfile;
261 } AVOutputStream;
263 typedef struct AVInputStream {
264 int file_index;
265 int index;
266 AVStream *st;
267 int discard; /* true if stream data should be discarded */
268 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
269 int64_t sample_index; /* current sample */
271 int64_t start; /* time when read started */
272 unsigned long frame; /* current frame */
273 int64_t next_pts; /* synthetic pts for cases where pkt.pts
274 is not defined */
275 int64_t pts; /* current pts */
276 int is_start; /* is 1 at the start and after a discontinuity */
277 } AVInputStream;
279 typedef struct AVInputFile {
280 int eof_reached; /* true if eof reached */
281 int ist_index; /* index of first stream in ist_table */
282 int buffer_size; /* current total buffer size */
283 int nb_streams; /* nb streams we are aware of */
284 } AVInputFile;
286 #ifdef HAVE_TERMIOS_H
288 /* init terminal so that we can grab keys */
289 static struct termios oldtty;
290 #endif
292 static void term_exit(void)
294 #ifdef HAVE_TERMIOS_H
295 tcsetattr (0, TCSANOW, &oldtty);
296 #endif
299 static volatile sig_atomic_t received_sigterm = 0;
301 static void
302 sigterm_handler(int sig)
304 received_sigterm = sig;
305 term_exit();
308 static void term_init(void)
310 #ifdef HAVE_TERMIOS_H
311 struct termios tty;
313 tcgetattr (0, &tty);
314 oldtty = tty;
316 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
317 |INLCR|IGNCR|ICRNL|IXON);
318 tty.c_oflag |= OPOST;
319 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
320 tty.c_cflag &= ~(CSIZE|PARENB);
321 tty.c_cflag |= CS8;
322 tty.c_cc[VMIN] = 1;
323 tty.c_cc[VTIME] = 0;
325 tcsetattr (0, TCSANOW, &tty);
326 signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
327 #endif
329 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
330 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
332 register a function to be called at normal program termination
334 atexit(term_exit);
335 #ifdef CONFIG_BEOS_NETSERVER
336 fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
337 #endif
340 /* read a key without blocking */
341 static int read_key(void)
343 #if defined(HAVE_TERMIOS_H)
344 int n = 1;
345 unsigned char ch;
346 #ifndef CONFIG_BEOS_NETSERVER
347 struct timeval tv;
348 fd_set rfds;
350 FD_ZERO(&rfds);
351 FD_SET(0, &rfds);
352 tv.tv_sec = 0;
353 tv.tv_usec = 0;
354 n = select(1, &rfds, NULL, NULL, &tv);
355 #endif
356 if (n > 0) {
357 n = read(0, &ch, 1);
358 if (n == 1)
359 return ch;
361 return n;
363 #elif defined(HAVE_CONIO_H)
364 if(kbhit())
365 return(getch());
366 #endif
367 return -1;
370 static int decode_interrupt_cb(void)
372 return q_pressed || (q_pressed = read_key() == 'q');
375 static int av_exit(int ret)
377 int i;
379 /* close files */
380 for(i=0;i<nb_output_files;i++) {
381 /* maybe av_close_output_file ??? */
382 AVFormatContext *s = output_files[i];
383 int j;
384 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
385 url_fclose(s->pb);
386 for(j=0;j<s->nb_streams;j++) {
387 av_free(s->streams[j]->codec);
388 av_free(s->streams[j]);
390 av_free(s);
392 for(i=0;i<nb_input_files;i++)
393 av_close_input_file(input_files[i]);
395 av_free(intra_matrix);
396 av_free(inter_matrix);
398 if (vstats_file)
399 fclose(vstats_file);
400 av_free(vstats_filename);
402 av_free(opt_names);
404 av_free(video_codec_name);
405 av_free(audio_codec_name);
406 av_free(subtitle_codec_name);
408 av_free(video_standard);
410 #ifdef CONFIG_POWERPC_PERF
411 extern void powerpc_display_perf_report(void);
412 powerpc_display_perf_report();
413 #endif /* CONFIG_POWERPC_PERF */
415 if (received_sigterm) {
416 fprintf(stderr,
417 "Received signal %d: terminating.\n",
418 (int) received_sigterm);
419 exit (255);
422 exit(ret); /* not all OS-es handle main() return value */
423 return ret;
426 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
428 int i, err;
429 AVFormatContext *ic;
430 int nopts = 0;
432 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
433 if (err < 0)
434 return err;
435 /* copy stream format */
436 s->nb_streams = ic->nb_streams;
437 for(i=0;i<ic->nb_streams;i++) {
438 AVStream *st;
440 // FIXME: a more elegant solution is needed
441 st = av_mallocz(sizeof(AVStream));
442 memcpy(st, ic->streams[i], sizeof(AVStream));
443 st->codec = avcodec_alloc_context();
444 memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
445 s->streams[i] = st;
447 if (st->codec->codec_type == CODEC_TYPE_AUDIO && audio_stream_copy)
448 st->stream_copy = 1;
449 else if (st->codec->codec_type == CODEC_TYPE_VIDEO && video_stream_copy)
450 st->stream_copy = 1;
452 if(st->codec->flags & CODEC_FLAG_BITEXACT)
453 nopts = 1;
456 if (!nopts)
457 s->timestamp = av_gettime();
459 av_close_input_file(ic);
460 return 0;
463 static double
464 get_sync_ipts(const AVOutputStream *ost)
466 const AVInputStream *ist = ost->sync_ist;
467 return (double)(ist->pts - start_time)/AV_TIME_BASE;
470 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
471 int ret;
473 while(bsfc){
474 AVPacket new_pkt= *pkt;
475 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
476 &new_pkt.data, &new_pkt.size,
477 pkt->data, pkt->size,
478 pkt->flags & PKT_FLAG_KEY);
479 if(a>0){
480 av_free_packet(pkt);
481 new_pkt.destruct= av_destruct_packet;
482 } else if(a<0){
483 fprintf(stderr, "%s failed for stream %d, codec %s",
484 bsfc->filter->name, pkt->stream_index,
485 avctx->codec ? avctx->codec->name : "copy");
486 print_error("", a);
488 *pkt= new_pkt;
490 bsfc= bsfc->next;
493 ret= av_interleaved_write_frame(s, pkt);
494 if(ret < 0){
495 print_error("av_interleaved_write_frame()", ret);
496 av_exit(1);
500 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
502 static void do_audio_out(AVFormatContext *s,
503 AVOutputStream *ost,
504 AVInputStream *ist,
505 unsigned char *buf, int size)
507 uint8_t *buftmp;
508 static uint8_t *audio_buf = NULL;
509 static uint8_t *audio_out = NULL;
510 const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
512 int size_out, frame_bytes, ret;
513 AVCodecContext *enc= ost->st->codec;
514 AVCodecContext *dec= ist->st->codec;
516 /* SC: dynamic allocation of buffers */
517 if (!audio_buf)
518 audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
519 if (!audio_out)
520 audio_out = av_malloc(audio_out_size);
521 if (!audio_buf || !audio_out)
522 return; /* Should signal an error ! */
524 if (enc->channels != dec->channels)
525 ost->audio_resample = 1;
527 if (ost->audio_resample && !ost->resample) {
528 ost->resample = audio_resample_init(enc->channels, dec->channels,
529 enc->sample_rate, dec->sample_rate);
530 if (!ost->resample) {
531 fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
532 dec->channels, dec->sample_rate,
533 enc->channels, enc->sample_rate);
534 av_exit(1);
538 if(audio_sync_method){
539 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
540 - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);
541 double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
542 int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
544 //FIXME resample delay
545 if(fabs(delta) > 50){
546 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
547 if(byte_delta < 0){
548 byte_delta= FFMAX(byte_delta, -size);
549 size += byte_delta;
550 buf -= byte_delta;
551 if(verbose > 2)
552 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
553 if(!size)
554 return;
555 ist->is_start=0;
556 }else{
557 static uint8_t *input_tmp= NULL;
558 input_tmp= av_realloc(input_tmp, byte_delta + size);
560 if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
561 ist->is_start=0;
562 else
563 byte_delta= MAX_AUDIO_PACKET_SIZE - size;
565 memset(input_tmp, 0, byte_delta);
566 memcpy(input_tmp + byte_delta, buf, size);
567 buf= input_tmp;
568 size += byte_delta;
569 if(verbose > 2)
570 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
572 }else if(audio_sync_method>1){
573 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
574 assert(ost->audio_resample);
575 if(verbose > 2)
576 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
577 // fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2));
578 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
581 }else
582 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
583 - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong
585 if (ost->audio_resample) {
586 buftmp = audio_buf;
587 size_out = audio_resample(ost->resample,
588 (short *)buftmp, (short *)buf,
589 size / (ist->st->codec->channels * 2));
590 size_out = size_out * enc->channels * 2;
591 } else {
592 buftmp = buf;
593 size_out = size;
596 /* now encode as many frames as possible */
597 if (enc->frame_size > 1) {
598 /* output resampled raw samples */
599 av_fifo_realloc(&ost->fifo, av_fifo_size(&ost->fifo) + size_out);
600 av_fifo_generic_write(&ost->fifo, buftmp, size_out, NULL);
602 frame_bytes = enc->frame_size * 2 * enc->channels;
604 while (av_fifo_size(&ost->fifo) >= frame_bytes) {
605 AVPacket pkt;
606 av_init_packet(&pkt);
608 av_fifo_read(&ost->fifo, audio_buf, frame_bytes);
610 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
612 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
613 (short *)audio_buf);
614 audio_size += ret;
615 pkt.stream_index= ost->index;
616 pkt.data= audio_out;
617 pkt.size= ret;
618 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
619 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
620 pkt.flags |= PKT_FLAG_KEY;
621 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
623 ost->sync_opts += enc->frame_size;
625 } else {
626 AVPacket pkt;
627 av_init_packet(&pkt);
629 ost->sync_opts += size_out / (2 * enc->channels);
631 /* output a pcm frame */
632 /* XXX: change encoding codec API to avoid this ? */
633 switch(enc->codec->id) {
634 case CODEC_ID_PCM_S32LE:
635 case CODEC_ID_PCM_S32BE:
636 case CODEC_ID_PCM_U32LE:
637 case CODEC_ID_PCM_U32BE:
638 size_out = size_out << 1;
639 break;
640 case CODEC_ID_PCM_S24LE:
641 case CODEC_ID_PCM_S24BE:
642 case CODEC_ID_PCM_U24LE:
643 case CODEC_ID_PCM_U24BE:
644 case CODEC_ID_PCM_S24DAUD:
645 size_out = size_out / 2 * 3;
646 break;
647 case CODEC_ID_PCM_S16LE:
648 case CODEC_ID_PCM_S16BE:
649 case CODEC_ID_PCM_U16LE:
650 case CODEC_ID_PCM_U16BE:
651 break;
652 default:
653 size_out = size_out >> 1;
654 break;
656 //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
657 ret = avcodec_encode_audio(enc, audio_out, size_out,
658 (short *)buftmp);
659 audio_size += ret;
660 pkt.stream_index= ost->index;
661 pkt.data= audio_out;
662 pkt.size= ret;
663 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
664 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
665 pkt.flags |= PKT_FLAG_KEY;
666 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
670 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
672 AVCodecContext *dec;
673 AVPicture *picture2;
674 AVPicture picture_tmp;
675 uint8_t *buf = 0;
677 dec = ist->st->codec;
679 /* deinterlace : must be done before any resize */
680 if (do_deinterlace || using_vhook) {
681 int size;
683 /* create temporary picture */
684 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
685 buf = av_malloc(size);
686 if (!buf)
687 return;
689 picture2 = &picture_tmp;
690 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
692 if (do_deinterlace){
693 if(avpicture_deinterlace(picture2, picture,
694 dec->pix_fmt, dec->width, dec->height) < 0) {
695 /* if error, do not deinterlace */
696 av_free(buf);
697 buf = NULL;
698 picture2 = picture;
700 } else {
701 av_picture_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
703 } else {
704 picture2 = picture;
707 if (ENABLE_VHOOK)
708 frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height,
709 1000000 * ist->pts / AV_TIME_BASE);
711 if (picture != picture2)
712 *picture = *picture2;
713 *bufp = buf;
716 /* we begin to correct av delay at this threshold */
717 #define AV_DELAY_MAX 0.100
719 static void do_subtitle_out(AVFormatContext *s,
720 AVOutputStream *ost,
721 AVInputStream *ist,
722 AVSubtitle *sub,
723 int64_t pts)
725 static uint8_t *subtitle_out = NULL;
726 int subtitle_out_max_size = 65536;
727 int subtitle_out_size, nb, i;
728 AVCodecContext *enc;
729 AVPacket pkt;
731 if (pts == AV_NOPTS_VALUE) {
732 fprintf(stderr, "Subtitle packets must have a pts\n");
733 return;
736 enc = ost->st->codec;
738 if (!subtitle_out) {
739 subtitle_out = av_malloc(subtitle_out_max_size);
742 /* Note: DVB subtitle need one packet to draw them and one other
743 packet to clear them */
744 /* XXX: signal it in the codec context ? */
745 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
746 nb = 2;
747 else
748 nb = 1;
750 for(i = 0; i < nb; i++) {
751 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
752 subtitle_out_max_size, sub);
754 av_init_packet(&pkt);
755 pkt.stream_index = ost->index;
756 pkt.data = subtitle_out;
757 pkt.size = subtitle_out_size;
758 pkt.pts = av_rescale_q(pts, ist->st->time_base, ost->st->time_base);
759 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
760 /* XXX: the pts correction is handled here. Maybe handling
761 it in the codec would be better */
762 if (i == 0)
763 pkt.pts += 90 * sub->start_display_time;
764 else
765 pkt.pts += 90 * sub->end_display_time;
767 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
771 static int bit_buffer_size= 1024*256;
772 static uint8_t *bit_buffer= NULL;
774 static void do_video_out(AVFormatContext *s,
775 AVOutputStream *ost,
776 AVInputStream *ist,
777 AVFrame *in_picture,
778 int *frame_size)
780 int nb_frames, i, ret;
781 AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
782 AVFrame picture_crop_temp, picture_pad_temp;
783 AVCodecContext *enc, *dec;
785 avcodec_get_frame_defaults(&picture_crop_temp);
786 avcodec_get_frame_defaults(&picture_pad_temp);
788 enc = ost->st->codec;
789 dec = ist->st->codec;
791 /* by default, we output a single frame */
792 nb_frames = 1;
794 *frame_size = 0;
796 if(video_sync_method){
797 double vdelta;
798 vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
799 //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
800 if (vdelta < -1.1)
801 nb_frames = 0;
802 else if (video_sync_method == 2)
803 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
804 else if (vdelta > 1.1)
805 nb_frames = lrintf(vdelta);
806 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
807 if (nb_frames == 0){
808 ++nb_frames_drop;
809 if (verbose>2)
810 fprintf(stderr, "*** drop!\n");
811 }else if (nb_frames > 1) {
812 nb_frames_dup += nb_frames;
813 if (verbose>2)
814 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
816 }else
817 ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
819 nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
820 if (nb_frames <= 0)
821 return;
823 if (ost->video_crop) {
824 if (av_picture_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
825 av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
826 return;
828 formatted_picture = &picture_crop_temp;
829 } else {
830 formatted_picture = in_picture;
833 final_picture = formatted_picture;
834 padding_src = formatted_picture;
835 resampling_dst = &ost->pict_tmp;
836 if (ost->video_pad) {
837 final_picture = &ost->pict_tmp;
838 if (ost->video_resample) {
839 if (av_picture_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
840 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
841 return;
843 resampling_dst = &picture_pad_temp;
847 if (ost->video_resample) {
848 padding_src = NULL;
849 final_picture = &ost->pict_tmp;
850 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
851 0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
854 if (ost->video_pad) {
855 av_picture_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
856 enc->height, enc->width, enc->pix_fmt,
857 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
860 /* duplicates frame if needed */
861 for(i=0;i<nb_frames;i++) {
862 AVPacket pkt;
863 av_init_packet(&pkt);
864 pkt.stream_index= ost->index;
866 if (s->oformat->flags & AVFMT_RAWPICTURE) {
867 /* raw pictures are written as AVPicture structure to
868 avoid any copies. We support temorarily the older
869 method. */
870 AVFrame* old_frame = enc->coded_frame;
871 enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
872 pkt.data= (uint8_t *)final_picture;
873 pkt.size= sizeof(AVPicture);
874 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
875 pkt.flags |= PKT_FLAG_KEY;
877 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
878 enc->coded_frame = old_frame;
879 } else {
880 AVFrame big_picture;
882 big_picture= *final_picture;
883 /* better than nothing: use input picture interlaced
884 settings */
885 big_picture.interlaced_frame = in_picture->interlaced_frame;
886 if(avctx_opts[CODEC_TYPE_VIDEO]->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
887 if(top_field_first == -1)
888 big_picture.top_field_first = in_picture->top_field_first;
889 else
890 big_picture.top_field_first = top_field_first;
893 /* handles sameq here. This is not correct because it may
894 not be a global option */
895 if (same_quality) {
896 big_picture.quality = ist->st->quality;
897 }else
898 big_picture.quality = ost->st->quality;
899 if(!me_threshold)
900 big_picture.pict_type = 0;
901 // big_picture.pts = AV_NOPTS_VALUE;
902 big_picture.pts= ost->sync_opts;
903 // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
904 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
905 ret = avcodec_encode_video(enc,
906 bit_buffer, bit_buffer_size,
907 &big_picture);
908 if (ret == -1) {
909 fprintf(stderr, "Video encoding failed\n");
910 av_exit(1);
912 //enc->frame_number = enc->real_pict_num;
913 if(ret>0){
914 pkt.data= bit_buffer;
915 pkt.size= ret;
916 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
917 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
918 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
919 pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
920 pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
922 if(enc->coded_frame->key_frame)
923 pkt.flags |= PKT_FLAG_KEY;
924 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
925 *frame_size = ret;
926 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
927 // enc->frame_number-1, enc->real_pict_num, ret,
928 // enc->pict_type);
929 /* if two pass, output log */
930 if (ost->logfile && enc->stats_out) {
931 fprintf(ost->logfile, "%s", enc->stats_out);
935 ost->sync_opts++;
936 ost->frame_number++;
940 static double psnr(double d){
941 return -10.0*log(d)/log(10.0);
944 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
945 int frame_size)
947 AVCodecContext *enc;
948 int frame_number;
949 double ti1, bitrate, avg_bitrate;
951 /* this is executed just the first time do_video_stats is called */
952 if (!vstats_file) {
953 vstats_file = fopen(vstats_filename, "w");
954 if (!vstats_file) {
955 perror("fopen");
956 av_exit(1);
960 enc = ost->st->codec;
961 if (enc->codec_type == CODEC_TYPE_VIDEO) {
962 frame_number = ost->frame_number;
963 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
964 if (enc->flags&CODEC_FLAG_PSNR)
965 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
967 fprintf(vstats_file,"f_size= %6d ", frame_size);
968 /* compute pts value */
969 ti1 = ost->sync_opts * av_q2d(enc->time_base);
970 if (ti1 < 0.01)
971 ti1 = 0.01;
973 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
974 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
975 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
976 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
977 fprintf(vstats_file,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
981 static void print_report(AVFormatContext **output_files,
982 AVOutputStream **ost_table, int nb_ostreams,
983 int is_last_report)
985 char buf[1024];
986 AVOutputStream *ost;
987 AVFormatContext *oc, *os;
988 int64_t total_size;
989 AVCodecContext *enc;
990 int frame_number, vid, i;
991 double bitrate, ti1, pts;
992 static int64_t last_time = -1;
993 static int qp_histogram[52];
995 if (!is_last_report) {
996 int64_t cur_time;
997 /* display the report every 0.5 seconds */
998 cur_time = av_gettime();
999 if (last_time == -1) {
1000 last_time = cur_time;
1001 return;
1003 if ((cur_time - last_time) < 500000)
1004 return;
1005 last_time = cur_time;
1009 oc = output_files[0];
1011 total_size = url_fsize(oc->pb);
1012 if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too
1013 total_size= url_ftell(oc->pb);
1015 buf[0] = '\0';
1016 ti1 = 1e10;
1017 vid = 0;
1018 for(i=0;i<nb_ostreams;i++) {
1019 ost = ost_table[i];
1020 os = output_files[ost->file_index];
1021 enc = ost->st->codec;
1022 if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1023 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
1024 !ost->st->stream_copy ?
1025 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1027 if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1028 float t = (av_gettime()-timer_start) / 1000000.0;
1030 frame_number = ost->frame_number;
1031 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1032 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,
1033 !ost->st->stream_copy ?
1034 enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
1035 if(is_last_report)
1036 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1037 if(qp_hist){
1038 int j;
1039 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1040 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
1041 qp_histogram[qp]++;
1042 for(j=0; j<32; j++)
1043 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1045 if (enc->flags&CODEC_FLAG_PSNR){
1046 int j;
1047 double error, error_sum=0;
1048 double scale, scale_sum=0;
1049 char type[3]= {'Y','U','V'};
1050 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1051 for(j=0; j<3; j++){
1052 if(is_last_report){
1053 error= enc->error[j];
1054 scale= enc->width*enc->height*255.0*255.0*frame_number;
1055 }else{
1056 error= enc->coded_frame->error[j];
1057 scale= enc->width*enc->height*255.0*255.0;
1059 if(j) scale/=4;
1060 error_sum += error;
1061 scale_sum += scale;
1062 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1064 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1066 vid = 1;
1068 /* compute min output value */
1069 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1070 if ((pts < ti1) && (pts > 0))
1071 ti1 = pts;
1073 if (ti1 < 0.01)
1074 ti1 = 0.01;
1076 if (verbose || is_last_report) {
1077 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1079 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1080 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1081 (double)total_size / 1024, ti1, bitrate);
1083 if (verbose > 1)
1084 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1085 nb_frames_dup, nb_frames_drop);
1087 if (verbose >= 0)
1088 fprintf(stderr, "%s \r", buf);
1090 fflush(stderr);
1093 if (is_last_report && verbose >= 0){
1094 int64_t raw= audio_size + video_size + extra_size;
1095 fprintf(stderr, "\n");
1096 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1097 video_size/1024.0,
1098 audio_size/1024.0,
1099 extra_size/1024.0,
1100 100.0*(total_size - raw)/raw
1105 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1106 static int output_packet(AVInputStream *ist, int ist_index,
1107 AVOutputStream **ost_table, int nb_ostreams,
1108 const AVPacket *pkt)
1110 AVFormatContext *os;
1111 AVOutputStream *ost;
1112 uint8_t *ptr;
1113 int len, ret, i;
1114 uint8_t *data_buf;
1115 int data_size, got_picture;
1116 AVFrame picture;
1117 void *buffer_to_free;
1118 static unsigned int samples_size= 0;
1119 static short *samples= NULL;
1120 AVSubtitle subtitle, *subtitle_to_free;
1121 int got_subtitle;
1123 if(ist->next_pts == AV_NOPTS_VALUE)
1124 ist->next_pts= ist->pts;
1126 if (pkt == NULL) {
1127 /* EOF handling */
1128 ptr = NULL;
1129 len = 0;
1130 goto handle_eof;
1133 if(pkt->dts != AV_NOPTS_VALUE)
1134 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1136 len = pkt->size;
1137 ptr = pkt->data;
1138 while (len > 0) {
1139 handle_eof:
1140 ist->pts= ist->next_pts;
1142 if(len && len != pkt->size && verbose>0)
1143 fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1145 /* decode the packet if needed */
1146 data_buf = NULL; /* fail safe */
1147 data_size = 0;
1148 subtitle_to_free = NULL;
1149 if (ist->decoding_needed) {
1150 switch(ist->st->codec->codec_type) {
1151 case CODEC_TYPE_AUDIO:{
1152 if(pkt)
1153 samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE));
1154 data_size= samples_size;
1155 /* XXX: could avoid copy if PCM 16 bits with same
1156 endianness as CPU */
1157 ret = avcodec_decode_audio2(ist->st->codec, samples, &data_size,
1158 ptr, len);
1159 if (ret < 0)
1160 goto fail_decode;
1161 ptr += ret;
1162 len -= ret;
1163 /* Some bug in mpeg audio decoder gives */
1164 /* data_size < 0, it seems they are overflows */
1165 if (data_size <= 0) {
1166 /* no audio frame */
1167 continue;
1169 data_buf = (uint8_t *)samples;
1170 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1171 (ist->st->codec->sample_rate * ist->st->codec->channels);
1172 break;}
1173 case CODEC_TYPE_VIDEO:
1174 data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1175 /* XXX: allocate picture correctly */
1176 avcodec_get_frame_defaults(&picture);
1178 ret = avcodec_decode_video(ist->st->codec,
1179 &picture, &got_picture, ptr, len);
1180 ist->st->quality= picture.quality;
1181 if (ret < 0)
1182 goto fail_decode;
1183 if (!got_picture) {
1184 /* no picture yet */
1185 goto discard_packet;
1187 if (ist->st->codec->time_base.num != 0) {
1188 ist->next_pts += ((int64_t)AV_TIME_BASE *
1189 ist->st->codec->time_base.num) /
1190 ist->st->codec->time_base.den;
1192 len = 0;
1193 break;
1194 case CODEC_TYPE_SUBTITLE:
1195 ret = avcodec_decode_subtitle(ist->st->codec,
1196 &subtitle, &got_subtitle, ptr, len);
1197 if (ret < 0)
1198 goto fail_decode;
1199 if (!got_subtitle) {
1200 goto discard_packet;
1202 subtitle_to_free = &subtitle;
1203 len = 0;
1204 break;
1205 default:
1206 goto fail_decode;
1208 } else {
1209 switch(ist->st->codec->codec_type) {
1210 case CODEC_TYPE_AUDIO:
1211 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1212 ist->st->codec->sample_rate;
1213 break;
1214 case CODEC_TYPE_VIDEO:
1215 if (ist->st->codec->time_base.num != 0) {
1216 ist->next_pts += ((int64_t)AV_TIME_BASE *
1217 ist->st->codec->time_base.num) /
1218 ist->st->codec->time_base.den;
1220 break;
1222 data_buf = ptr;
1223 data_size = len;
1224 ret = len;
1225 len = 0;
1228 buffer_to_free = NULL;
1229 if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1230 pre_process_video_frame(ist, (AVPicture *)&picture,
1231 &buffer_to_free);
1234 // preprocess audio (volume)
1235 if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1236 if (audio_volume != 256) {
1237 short *volp;
1238 volp = samples;
1239 for(i=0;i<(data_size / sizeof(short));i++) {
1240 int v = ((*volp) * audio_volume + 128) >> 8;
1241 if (v < -32768) v = -32768;
1242 if (v > 32767) v = 32767;
1243 *volp++ = v;
1248 /* frame rate emulation */
1249 if (ist->st->codec->rate_emu) {
1250 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1251 int64_t now = av_gettime() - ist->start;
1252 if (pts > now)
1253 usleep(pts - now);
1255 ist->frame++;
1258 #if 0
1259 /* mpeg PTS deordering : if it is a P or I frame, the PTS
1260 is the one of the next displayed one */
1261 /* XXX: add mpeg4 too ? */
1262 if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1263 if (ist->st->codec->pict_type != B_TYPE) {
1264 int64_t tmp;
1265 tmp = ist->last_ip_pts;
1266 ist->last_ip_pts = ist->frac_pts.val;
1267 ist->frac_pts.val = tmp;
1270 #endif
1271 /* if output time reached then transcode raw format,
1272 encode packets and output them */
1273 if (start_time == 0 || ist->pts >= start_time)
1274 for(i=0;i<nb_ostreams;i++) {
1275 int frame_size;
1277 ost = ost_table[i];
1278 if (ost->source_index == ist_index) {
1279 os = output_files[ost->file_index];
1281 #if 0
1282 printf("%d: got pts=%0.3f %0.3f\n", i,
1283 (double)pkt->pts / AV_TIME_BASE,
1284 ((double)ist->pts / AV_TIME_BASE) -
1285 ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1286 #endif
1287 /* set the input output pts pairs */
1288 //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1290 if (ost->encoding_needed) {
1291 switch(ost->st->codec->codec_type) {
1292 case CODEC_TYPE_AUDIO:
1293 do_audio_out(os, ost, ist, data_buf, data_size);
1294 break;
1295 case CODEC_TYPE_VIDEO:
1296 do_video_out(os, ost, ist, &picture, &frame_size);
1297 video_size += frame_size;
1298 if (vstats_filename && frame_size)
1299 do_video_stats(os, ost, frame_size);
1300 break;
1301 case CODEC_TYPE_SUBTITLE:
1302 do_subtitle_out(os, ost, ist, &subtitle,
1303 pkt->pts);
1304 break;
1305 default:
1306 abort();
1308 } else {
1309 AVFrame avframe; //FIXME/XXX remove this
1310 AVPacket opkt;
1311 av_init_packet(&opkt);
1313 if (!ost->frame_number && !(pkt->flags & PKT_FLAG_KEY))
1314 continue;
1316 /* no reencoding needed : output the packet directly */
1317 /* force the input stream PTS */
1319 avcodec_get_frame_defaults(&avframe);
1320 ost->st->codec->coded_frame= &avframe;
1321 avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1323 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1324 audio_size += data_size;
1325 else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1326 video_size += data_size;
1327 ost->sync_opts++;
1330 opkt.stream_index= ost->index;
1331 if(pkt->pts != AV_NOPTS_VALUE)
1332 opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base);
1333 else
1334 opkt.pts= AV_NOPTS_VALUE;
1336 if (pkt->dts == AV_NOPTS_VALUE)
1337 opkt.dts = av_rescale_q(ist->next_pts, AV_TIME_BASE_Q, ost->st->time_base);
1338 else
1339 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1341 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1342 opkt.flags= pkt->flags;
1344 //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1345 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1346 opkt.destruct= av_destruct_packet;
1348 write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][opkt.stream_index]);
1349 ost->st->codec->frame_number++;
1350 ost->frame_number++;
1351 av_free_packet(&opkt);
1355 av_free(buffer_to_free);
1356 /* XXX: allocate the subtitles in the codec ? */
1357 if (subtitle_to_free) {
1358 if (subtitle_to_free->rects != NULL) {
1359 for (i = 0; i < subtitle_to_free->num_rects; i++) {
1360 av_free(subtitle_to_free->rects[i].bitmap);
1361 av_free(subtitle_to_free->rects[i].rgba_palette);
1363 av_freep(&subtitle_to_free->rects);
1365 subtitle_to_free->num_rects = 0;
1366 subtitle_to_free = NULL;
1369 discard_packet:
1370 if (pkt == NULL) {
1371 /* EOF handling */
1373 for(i=0;i<nb_ostreams;i++) {
1374 ost = ost_table[i];
1375 if (ost->source_index == ist_index) {
1376 AVCodecContext *enc= ost->st->codec;
1377 os = output_files[ost->file_index];
1379 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1380 continue;
1381 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1382 continue;
1384 if (ost->encoding_needed) {
1385 for(;;) {
1386 AVPacket pkt;
1387 int fifo_bytes;
1388 av_init_packet(&pkt);
1389 pkt.stream_index= ost->index;
1391 switch(ost->st->codec->codec_type) {
1392 case CODEC_TYPE_AUDIO:
1393 fifo_bytes = av_fifo_size(&ost->fifo);
1394 ret = 0;
1395 /* encode any samples remaining in fifo */
1396 if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1397 int fs_tmp = enc->frame_size;
1398 enc->frame_size = fifo_bytes / (2 * enc->channels);
1399 av_fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes);
1400 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1401 enc->frame_size = fs_tmp;
1403 if(ret <= 0) {
1404 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1406 audio_size += ret;
1407 pkt.flags |= PKT_FLAG_KEY;
1408 break;
1409 case CODEC_TYPE_VIDEO:
1410 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1411 video_size += ret;
1412 if(enc->coded_frame && enc->coded_frame->key_frame)
1413 pkt.flags |= PKT_FLAG_KEY;
1414 if (ost->logfile && enc->stats_out) {
1415 fprintf(ost->logfile, "%s", enc->stats_out);
1417 break;
1418 default:
1419 ret=-1;
1422 if(ret<=0)
1423 break;
1424 pkt.data= bit_buffer;
1425 pkt.size= ret;
1426 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1427 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1428 write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1435 return 0;
1436 fail_decode:
1437 return -1;
1440 static void print_sdp(AVFormatContext **avc, int n)
1442 char sdp[2048];
1444 avf_sdp_create(avc, n, sdp, sizeof(sdp));
1445 printf("SDP:\n%s\n", sdp);
1448 static int stream_index_from_inputs(AVFormatContext **input_files,
1449 int nb_input_files,
1450 AVInputFile *file_table,
1451 AVInputStream **ist_table,
1452 enum CodecType type,
1453 int programid)
1455 int p, q, z;
1456 for(z=0; z<nb_input_files; z++) {
1457 AVFormatContext *ic = input_files[z];
1458 for(p=0; p<ic->nb_programs; p++) {
1459 AVProgram *program = ic->programs[p];
1460 if(program->id != programid)
1461 continue;
1462 for(q=0; q<program->nb_stream_indexes; q++) {
1463 int sidx = program->stream_index[q];
1464 int ris = file_table[z].ist_index + sidx;
1465 if(ist_table[ris]->discard && ic->streams[sidx]->codec->codec_type == type)
1466 return ris;
1471 return -1;
1475 * The following code is the main loop of the file converter
1477 static int av_encode(AVFormatContext **output_files,
1478 int nb_output_files,
1479 AVFormatContext **input_files,
1480 int nb_input_files,
1481 AVStreamMap *stream_maps, int nb_stream_maps)
1483 int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1484 AVFormatContext *is, *os;
1485 AVCodecContext *codec, *icodec;
1486 AVOutputStream *ost, **ost_table = NULL;
1487 AVInputStream *ist, **ist_table = NULL;
1488 AVInputFile *file_table;
1489 int key;
1490 int want_sdp = 1;
1492 file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));
1493 if (!file_table)
1494 goto fail;
1496 /* input stream init */
1497 j = 0;
1498 for(i=0;i<nb_input_files;i++) {
1499 is = input_files[i];
1500 file_table[i].ist_index = j;
1501 file_table[i].nb_streams = is->nb_streams;
1502 j += is->nb_streams;
1504 nb_istreams = j;
1506 ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1507 if (!ist_table)
1508 goto fail;
1510 for(i=0;i<nb_istreams;i++) {
1511 ist = av_mallocz(sizeof(AVInputStream));
1512 if (!ist)
1513 goto fail;
1514 ist_table[i] = ist;
1516 j = 0;
1517 for(i=0;i<nb_input_files;i++) {
1518 is = input_files[i];
1519 for(k=0;k<is->nb_streams;k++) {
1520 ist = ist_table[j++];
1521 ist->st = is->streams[k];
1522 ist->file_index = i;
1523 ist->index = k;
1524 ist->discard = 1; /* the stream is discarded by default
1525 (changed later) */
1527 if (ist->st->codec->rate_emu) {
1528 ist->start = av_gettime();
1529 ist->frame = 0;
1534 /* output stream init */
1535 nb_ostreams = 0;
1536 for(i=0;i<nb_output_files;i++) {
1537 os = output_files[i];
1538 if (!os->nb_streams) {
1539 fprintf(stderr, "Output file does not contain any stream\n");
1540 av_exit(1);
1542 nb_ostreams += os->nb_streams;
1544 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1545 fprintf(stderr, "Number of stream maps must match number of output streams\n");
1546 av_exit(1);
1549 /* Sanity check the mapping args -- do the input files & streams exist? */
1550 for(i=0;i<nb_stream_maps;i++) {
1551 int fi = stream_maps[i].file_index;
1552 int si = stream_maps[i].stream_index;
1554 if (fi < 0 || fi > nb_input_files - 1 ||
1555 si < 0 || si > file_table[fi].nb_streams - 1) {
1556 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1557 av_exit(1);
1559 fi = stream_maps[i].sync_file_index;
1560 si = stream_maps[i].sync_stream_index;
1561 if (fi < 0 || fi > nb_input_files - 1 ||
1562 si < 0 || si > file_table[fi].nb_streams - 1) {
1563 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1564 av_exit(1);
1568 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1569 if (!ost_table)
1570 goto fail;
1571 for(i=0;i<nb_ostreams;i++) {
1572 ost = av_mallocz(sizeof(AVOutputStream));
1573 if (!ost)
1574 goto fail;
1575 ost_table[i] = ost;
1578 n = 0;
1579 for(k=0;k<nb_output_files;k++) {
1580 os = output_files[k];
1581 for(i=0;i<os->nb_streams;i++) {
1582 int found;
1583 ost = ost_table[n++];
1584 ost->file_index = k;
1585 ost->index = i;
1586 ost->st = os->streams[i];
1587 if (nb_stream_maps > 0) {
1588 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1589 stream_maps[n-1].stream_index;
1591 /* Sanity check that the stream types match */
1592 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1593 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1594 stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1595 ost->file_index, ost->index);
1596 av_exit(1);
1599 } else {
1600 if(opt_programid) {
1601 found = 0;
1602 j = stream_index_from_inputs(input_files, nb_input_files, file_table, ist_table, ost->st->codec->codec_type, opt_programid);
1603 if(j != -1) {
1604 ost->source_index = j;
1605 found = 1;
1607 } else {
1608 /* get corresponding input stream index : we select the first one with the right type */
1609 found = 0;
1610 for(j=0;j<nb_istreams;j++) {
1611 ist = ist_table[j];
1612 if (ist->discard &&
1613 ist->st->codec->codec_type == ost->st->codec->codec_type) {
1614 ost->source_index = j;
1615 found = 1;
1616 break;
1621 if (!found) {
1622 if(! opt_programid) {
1623 /* try again and reuse existing stream */
1624 for(j=0;j<nb_istreams;j++) {
1625 ist = ist_table[j];
1626 if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1627 ost->source_index = j;
1628 found = 1;
1632 if (!found) {
1633 int i= ost->file_index;
1634 dump_format(output_files[i], i, output_files[i]->filename, 1);
1635 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1636 ost->file_index, ost->index);
1637 av_exit(1);
1641 ist = ist_table[ost->source_index];
1642 ist->discard = 0;
1643 ost->sync_ist = (nb_stream_maps > 0) ?
1644 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1645 stream_maps[n-1].sync_stream_index] : ist;
1649 /* for each output stream, we compute the right encoding parameters */
1650 for(i=0;i<nb_ostreams;i++) {
1651 ost = ost_table[i];
1652 os = output_files[ost->file_index];
1653 ist = ist_table[ost->source_index];
1655 codec = ost->st->codec;
1656 icodec = ist->st->codec;
1658 if (!ost->st->language[0])
1659 av_strlcpy(ost->st->language, ist->st->language,
1660 sizeof(ost->st->language));
1662 ost->st->disposition = ist->st->disposition;
1664 if (ost->st->stream_copy) {
1665 /* if stream_copy is selected, no need to decode or encode */
1666 codec->codec_id = icodec->codec_id;
1667 codec->codec_type = icodec->codec_type;
1669 if(!codec->codec_tag){
1670 if( !os->oformat->codec_tag
1671 || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) > 0
1672 || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
1673 codec->codec_tag = icodec->codec_tag;
1676 codec->bit_rate = icodec->bit_rate;
1677 codec->extradata= icodec->extradata;
1678 codec->extradata_size= icodec->extradata_size;
1679 if(av_q2d(icodec->time_base) > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000)
1680 codec->time_base = icodec->time_base;
1681 else
1682 codec->time_base = ist->st->time_base;
1683 switch(codec->codec_type) {
1684 case CODEC_TYPE_AUDIO:
1685 codec->sample_rate = icodec->sample_rate;
1686 codec->channels = icodec->channels;
1687 codec->frame_size = icodec->frame_size;
1688 codec->block_align= icodec->block_align;
1689 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
1690 codec->block_align= 0;
1691 if(codec->codec_id == CODEC_ID_AC3)
1692 codec->block_align= 0;
1693 break;
1694 case CODEC_TYPE_VIDEO:
1695 if(using_vhook) {
1696 fprintf(stderr,"-vcodec copy and -vhook are incompatible (frames are not decoded)\n");
1697 av_exit(1);
1699 codec->pix_fmt = icodec->pix_fmt;
1700 codec->width = icodec->width;
1701 codec->height = icodec->height;
1702 codec->has_b_frames = icodec->has_b_frames;
1703 break;
1704 case CODEC_TYPE_SUBTITLE:
1705 break;
1706 default:
1707 abort();
1709 } else {
1710 switch(codec->codec_type) {
1711 case CODEC_TYPE_AUDIO:
1712 if (av_fifo_init(&ost->fifo, 1024))
1713 goto fail;
1714 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
1715 icodec->request_channels = codec->channels;
1716 ist->decoding_needed = 1;
1717 ost->encoding_needed = 1;
1718 break;
1719 case CODEC_TYPE_VIDEO:
1720 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1721 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1722 ost->video_resample = ((codec->width != icodec->width -
1723 (frame_leftBand + frame_rightBand) +
1724 (frame_padleft + frame_padright)) ||
1725 (codec->height != icodec->height -
1726 (frame_topBand + frame_bottomBand) +
1727 (frame_padtop + frame_padbottom)) ||
1728 (codec->pix_fmt != icodec->pix_fmt));
1729 if (ost->video_crop) {
1730 ost->topBand = frame_topBand;
1731 ost->leftBand = frame_leftBand;
1733 if (ost->video_pad) {
1734 ost->padtop = frame_padtop;
1735 ost->padleft = frame_padleft;
1736 ost->padbottom = frame_padbottom;
1737 ost->padright = frame_padright;
1738 if (!ost->video_resample) {
1739 avcodec_get_frame_defaults(&ost->pict_tmp);
1740 if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1741 codec->width, codec->height))
1742 goto fail;
1745 if (ost->video_resample) {
1746 avcodec_get_frame_defaults(&ost->pict_tmp);
1747 if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1748 codec->width, codec->height)) {
1749 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1750 av_exit(1);
1752 sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
1753 ost->img_resample_ctx = sws_getContext(
1754 icodec->width - (frame_leftBand + frame_rightBand),
1755 icodec->height - (frame_topBand + frame_bottomBand),
1756 icodec->pix_fmt,
1757 codec->width - (frame_padleft + frame_padright),
1758 codec->height - (frame_padtop + frame_padbottom),
1759 codec->pix_fmt,
1760 sws_flags, NULL, NULL, NULL);
1761 if (ost->img_resample_ctx == NULL) {
1762 fprintf(stderr, "Cannot get resampling context\n");
1763 av_exit(1);
1765 ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1767 ost->encoding_needed = 1;
1768 ist->decoding_needed = 1;
1769 break;
1770 case CODEC_TYPE_SUBTITLE:
1771 ost->encoding_needed = 1;
1772 ist->decoding_needed = 1;
1773 break;
1774 default:
1775 abort();
1776 break;
1778 /* two pass mode */
1779 if (ost->encoding_needed &&
1780 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1781 char logfilename[1024];
1782 FILE *f;
1783 int size;
1784 char *logbuffer;
1786 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1787 pass_logfilename ?
1788 pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1789 if (codec->flags & CODEC_FLAG_PASS1) {
1790 f = fopen(logfilename, "w");
1791 if (!f) {
1792 perror(logfilename);
1793 av_exit(1);
1795 ost->logfile = f;
1796 } else {
1797 /* read the log file */
1798 f = fopen(logfilename, "r");
1799 if (!f) {
1800 perror(logfilename);
1801 av_exit(1);
1803 fseek(f, 0, SEEK_END);
1804 size = ftell(f);
1805 fseek(f, 0, SEEK_SET);
1806 logbuffer = av_malloc(size + 1);
1807 if (!logbuffer) {
1808 fprintf(stderr, "Could not allocate log buffer\n");
1809 av_exit(1);
1811 size = fread(logbuffer, 1, size, f);
1812 fclose(f);
1813 logbuffer[size] = '\0';
1814 codec->stats_in = logbuffer;
1818 if(codec->codec_type == CODEC_TYPE_VIDEO){
1819 int size= codec->width * codec->height;
1820 bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1824 if (!bit_buffer)
1825 bit_buffer = av_malloc(bit_buffer_size);
1826 if (!bit_buffer)
1827 goto fail;
1829 /* dump the file output parameters - cannot be done before in case
1830 of stream copy */
1831 for(i=0;i<nb_output_files;i++) {
1832 dump_format(output_files[i], i, output_files[i]->filename, 1);
1835 /* dump the stream mapping */
1836 if (verbose >= 0) {
1837 fprintf(stderr, "Stream mapping:\n");
1838 for(i=0;i<nb_ostreams;i++) {
1839 ost = ost_table[i];
1840 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
1841 ist_table[ost->source_index]->file_index,
1842 ist_table[ost->source_index]->index,
1843 ost->file_index,
1844 ost->index);
1845 if (ost->sync_ist != ist_table[ost->source_index])
1846 fprintf(stderr, " [sync #%d.%d]",
1847 ost->sync_ist->file_index,
1848 ost->sync_ist->index);
1849 fprintf(stderr, "\n");
1853 /* open each encoder */
1854 for(i=0;i<nb_ostreams;i++) {
1855 ost = ost_table[i];
1856 if (ost->encoding_needed) {
1857 AVCodec *codec;
1858 codec = avcodec_find_encoder(ost->st->codec->codec_id);
1859 if (!codec) {
1860 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1861 ost->file_index, ost->index);
1862 av_exit(1);
1864 if (avcodec_open(ost->st->codec, codec) < 0) {
1865 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1866 ost->file_index, ost->index);
1867 av_exit(1);
1869 extra_size += ost->st->codec->extradata_size;
1873 /* open each decoder */
1874 for(i=0;i<nb_istreams;i++) {
1875 ist = ist_table[i];
1876 if (ist->decoding_needed) {
1877 AVCodec *codec;
1878 codec = avcodec_find_decoder(ist->st->codec->codec_id);
1879 if (!codec) {
1880 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1881 ist->st->codec->codec_id, ist->file_index, ist->index);
1882 av_exit(1);
1884 if (avcodec_open(ist->st->codec, codec) < 0) {
1885 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1886 ist->file_index, ist->index);
1887 av_exit(1);
1889 //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1890 // ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1894 /* init pts */
1895 for(i=0;i<nb_istreams;i++) {
1896 ist = ist_table[i];
1897 is = input_files[ist->file_index];
1898 ist->pts = 0;
1899 ist->next_pts = AV_NOPTS_VALUE;
1900 ist->is_start = 1;
1903 /* set meta data information from input file if required */
1904 for (i=0;i<nb_meta_data_maps;i++) {
1905 AVFormatContext *out_file;
1906 AVFormatContext *in_file;
1908 int out_file_index = meta_data_maps[i].out_file;
1909 int in_file_index = meta_data_maps[i].in_file;
1910 if (out_file_index < 0 || out_file_index >= nb_output_files) {
1911 fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1912 ret = AVERROR(EINVAL);
1913 goto fail;
1915 if (in_file_index < 0 || in_file_index >= nb_input_files) {
1916 fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1917 ret = AVERROR(EINVAL);
1918 goto fail;
1921 out_file = output_files[out_file_index];
1922 in_file = input_files[in_file_index];
1924 strcpy(out_file->title, in_file->title);
1925 strcpy(out_file->author, in_file->author);
1926 strcpy(out_file->copyright, in_file->copyright);
1927 strcpy(out_file->comment, in_file->comment);
1928 strcpy(out_file->album, in_file->album);
1929 out_file->year = in_file->year;
1930 out_file->track = in_file->track;
1931 strcpy(out_file->genre, in_file->genre);
1934 /* open files and write file headers */
1935 for(i=0;i<nb_output_files;i++) {
1936 os = output_files[i];
1937 if (av_write_header(os) < 0) {
1938 fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1939 ret = AVERROR(EINVAL);
1940 goto fail;
1942 if (strcmp(output_files[i]->oformat->name, "rtp")) {
1943 want_sdp = 0;
1946 if (want_sdp) {
1947 print_sdp(output_files, nb_output_files);
1950 if (!using_stdin && verbose >= 0) {
1951 fprintf(stderr, "Press [q] to stop encoding\n");
1952 url_set_interrupt_cb(decode_interrupt_cb);
1954 term_init();
1956 key = -1;
1957 timer_start = av_gettime();
1959 for(; received_sigterm == 0;) {
1960 int file_index, ist_index;
1961 AVPacket pkt;
1962 double ipts_min;
1963 double opts_min;
1965 redo:
1966 ipts_min= 1e100;
1967 opts_min= 1e100;
1968 /* if 'q' pressed, exits */
1969 if (!using_stdin) {
1970 if (q_pressed)
1971 break;
1972 /* read_key() returns 0 on EOF */
1973 key = read_key();
1974 if (key == 'q')
1975 break;
1978 /* select the stream that we must read now by looking at the
1979 smallest output pts */
1980 file_index = -1;
1981 for(i=0;i<nb_ostreams;i++) {
1982 double ipts, opts;
1983 ost = ost_table[i];
1984 os = output_files[ost->file_index];
1985 ist = ist_table[ost->source_index];
1986 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1987 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1988 else
1989 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1990 ipts = (double)ist->pts;
1991 if (!file_table[ist->file_index].eof_reached){
1992 if(ipts < ipts_min) {
1993 ipts_min = ipts;
1994 if(input_sync ) file_index = ist->file_index;
1996 if(opts < opts_min) {
1997 opts_min = opts;
1998 if(!input_sync) file_index = ist->file_index;
2001 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
2002 file_index= -1;
2003 break;
2006 /* if none, if is finished */
2007 if (file_index < 0) {
2008 break;
2011 /* finish if recording time exhausted */
2012 if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
2013 break;
2015 /* finish if limit size exhausted */
2016 if (limit_filesize != 0 && limit_filesize < url_ftell(output_files[0]->pb))
2017 break;
2019 /* read a frame from it and output it in the fifo */
2020 is = input_files[file_index];
2021 if (av_read_frame(is, &pkt) < 0) {
2022 file_table[file_index].eof_reached = 1;
2023 if (opt_shortest)
2024 break;
2025 else
2026 continue;
2029 if (do_pkt_dump) {
2030 av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);
2032 /* the following test is needed in case new streams appear
2033 dynamically in stream : we ignore them */
2034 if (pkt.stream_index >= file_table[file_index].nb_streams)
2035 goto discard_packet;
2036 ist_index = file_table[file_index].ist_index + pkt.stream_index;
2037 ist = ist_table[ist_index];
2038 if (ist->discard)
2039 goto discard_packet;
2041 if (pkt.dts != AV_NOPTS_VALUE)
2042 pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2043 if (pkt.pts != AV_NOPTS_VALUE)
2044 pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
2046 // fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
2047 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
2048 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2049 int64_t delta= pkt_dts - ist->next_pts;
2050 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
2051 input_files_ts_offset[ist->file_index]-= delta;
2052 if (verbose > 2)
2053 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
2054 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2055 if(pkt.pts != AV_NOPTS_VALUE)
2056 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2060 //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
2061 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
2063 if (verbose >= 0)
2064 fprintf(stderr, "Error while decoding stream #%d.%d\n",
2065 ist->file_index, ist->index);
2067 av_free_packet(&pkt);
2068 goto redo;
2071 discard_packet:
2072 av_free_packet(&pkt);
2074 /* dump report by using the output first video and audio streams */
2075 print_report(output_files, ost_table, nb_ostreams, 0);
2078 /* at the end of stream, we must flush the decoder buffers */
2079 for(i=0;i<nb_istreams;i++) {
2080 ist = ist_table[i];
2081 if (ist->decoding_needed) {
2082 output_packet(ist, i, ost_table, nb_ostreams, NULL);
2086 term_exit();
2088 /* write the trailer if needed and close file */
2089 for(i=0;i<nb_output_files;i++) {
2090 os = output_files[i];
2091 av_write_trailer(os);
2094 /* dump report by using the first video and audio streams */
2095 print_report(output_files, ost_table, nb_ostreams, 1);
2097 /* close each encoder */
2098 for(i=0;i<nb_ostreams;i++) {
2099 ost = ost_table[i];
2100 if (ost->encoding_needed) {
2101 av_freep(&ost->st->codec->stats_in);
2102 avcodec_close(ost->st->codec);
2106 /* close each decoder */
2107 for(i=0;i<nb_istreams;i++) {
2108 ist = ist_table[i];
2109 if (ist->decoding_needed) {
2110 avcodec_close(ist->st->codec);
2114 /* finished ! */
2116 ret = 0;
2117 fail1:
2118 av_freep(&bit_buffer);
2119 av_free(file_table);
2121 if (ist_table) {
2122 for(i=0;i<nb_istreams;i++) {
2123 ist = ist_table[i];
2124 av_free(ist);
2126 av_free(ist_table);
2128 if (ost_table) {
2129 for(i=0;i<nb_ostreams;i++) {
2130 ost = ost_table[i];
2131 if (ost) {
2132 if (ost->logfile) {
2133 fclose(ost->logfile);
2134 ost->logfile = NULL;
2136 av_fifo_free(&ost->fifo); /* works even if fifo is not
2137 initialized but set to zero */
2138 av_free(ost->pict_tmp.data[0]);
2139 if (ost->video_resample)
2140 sws_freeContext(ost->img_resample_ctx);
2141 if (ost->resample)
2142 audio_resample_close(ost->resample);
2143 av_free(ost);
2146 av_free(ost_table);
2148 return ret;
2149 fail:
2150 ret = AVERROR(ENOMEM);
2151 goto fail1;
2154 #if 0
2155 int file_read(const char *filename)
2157 URLContext *h;
2158 unsigned char buffer[1024];
2159 int len, i;
2161 if (url_open(&h, filename, O_RDONLY) < 0) {
2162 printf("could not open '%s'\n", filename);
2163 return -1;
2165 for(;;) {
2166 len = url_read(h, buffer, sizeof(buffer));
2167 if (len <= 0)
2168 break;
2169 for(i=0;i<len;i++) putchar(buffer[i]);
2171 url_close(h);
2172 return 0;
2174 #endif
2176 static void opt_format(const char *arg)
2178 /* compatibility stuff for pgmyuv */
2179 if (!strcmp(arg, "pgmyuv")) {
2180 pgmyuv_compatibility_hack=1;
2181 // opt_image_format(arg);
2182 arg = "image2";
2183 fprintf(stderr, "pgmyuv format is deprecated, use image2\n");
2186 file_iformat = av_find_input_format(arg);
2187 file_oformat = guess_format(arg, NULL, NULL);
2188 if (!file_iformat && !file_oformat) {
2189 fprintf(stderr, "Unknown input or output format: %s\n", arg);
2190 av_exit(1);
2194 static int opt_default(const char *opt, const char *arg){
2195 int type;
2196 const AVOption *o= NULL;
2197 int opt_types[]={AV_OPT_FLAG_VIDEO_PARAM, AV_OPT_FLAG_AUDIO_PARAM, 0, AV_OPT_FLAG_SUBTITLE_PARAM, 0};
2199 for(type=0; type<CODEC_TYPE_NB; type++){
2200 const AVOption *o2 = av_find_opt(avctx_opts[0], opt, NULL, opt_types[type], opt_types[type]);
2201 if(o2)
2202 o = av_set_string(avctx_opts[type], opt, arg);
2204 if(!o)
2205 o = av_set_string(avformat_opts, opt, arg);
2206 if(!o)
2207 o = av_set_string(sws_opts, opt, arg);
2208 if(!o){
2209 if(opt[0] == 'a')
2210 o = av_set_string(avctx_opts[CODEC_TYPE_AUDIO], opt+1, arg);
2211 else if(opt[0] == 'v')
2212 o = av_set_string(avctx_opts[CODEC_TYPE_VIDEO], opt+1, arg);
2213 else if(opt[0] == 's')
2214 o = av_set_string(avctx_opts[CODEC_TYPE_SUBTITLE], opt+1, arg);
2216 if(!o)
2217 return -1;
2219 // av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
2221 //FIXME we should always use avctx_opts, ... for storing options so there wont be any need to keep track of whats set over this
2222 opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
2223 opt_names[opt_name_count++]= o->name;
2225 if(avctx_opts[0]->debug || avformat_opts->debug)
2226 av_log_set_level(AV_LOG_DEBUG);
2227 return 0;
2230 static void opt_video_rc_override_string(const char *arg)
2232 video_rc_override_string = arg;
2235 static int opt_me_threshold(const char *opt, const char *arg)
2237 me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2238 return 0;
2241 static int opt_verbose(const char *opt, const char *arg)
2243 verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
2244 av_log_set_level(verbose);
2245 return 0;
2248 static void opt_frame_rate(const char *arg)
2250 if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
2251 fprintf(stderr, "Incorrect frame rate\n");
2252 av_exit(1);
2256 static int opt_bitrate(const char *opt, const char *arg)
2258 int codec_type = opt[0]=='a' ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
2260 opt_default(opt, arg);
2262 if (av_get_int(avctx_opts[codec_type], "b", NULL) < 1000)
2263 fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
2265 return 0;
2268 static void opt_frame_crop_top(const char *arg)
2270 frame_topBand = atoi(arg);
2271 if (frame_topBand < 0) {
2272 fprintf(stderr, "Incorrect top crop size\n");
2273 av_exit(1);
2275 if ((frame_topBand % 2) != 0) {
2276 fprintf(stderr, "Top crop size must be a multiple of 2\n");
2277 av_exit(1);
2279 if ((frame_topBand) >= frame_height){
2280 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2281 av_exit(1);
2283 frame_height -= frame_topBand;
2286 static void opt_frame_crop_bottom(const char *arg)
2288 frame_bottomBand = atoi(arg);
2289 if (frame_bottomBand < 0) {
2290 fprintf(stderr, "Incorrect bottom crop size\n");
2291 av_exit(1);
2293 if ((frame_bottomBand % 2) != 0) {
2294 fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2295 av_exit(1);
2297 if ((frame_bottomBand) >= frame_height){
2298 fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2299 av_exit(1);
2301 frame_height -= frame_bottomBand;
2304 static void opt_frame_crop_left(const char *arg)
2306 frame_leftBand = atoi(arg);
2307 if (frame_leftBand < 0) {
2308 fprintf(stderr, "Incorrect left crop size\n");
2309 av_exit(1);
2311 if ((frame_leftBand % 2) != 0) {
2312 fprintf(stderr, "Left crop size must be a multiple of 2\n");
2313 av_exit(1);
2315 if ((frame_leftBand) >= frame_width){
2316 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2317 av_exit(1);
2319 frame_width -= frame_leftBand;
2322 static void opt_frame_crop_right(const char *arg)
2324 frame_rightBand = atoi(arg);
2325 if (frame_rightBand < 0) {
2326 fprintf(stderr, "Incorrect right crop size\n");
2327 av_exit(1);
2329 if ((frame_rightBand % 2) != 0) {
2330 fprintf(stderr, "Right crop size must be a multiple of 2\n");
2331 av_exit(1);
2333 if ((frame_rightBand) >= frame_width){
2334 fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2335 av_exit(1);
2337 frame_width -= frame_rightBand;
2340 static void opt_frame_size(const char *arg)
2342 if (av_parse_video_frame_size(&frame_width, &frame_height, arg) < 0) {
2343 fprintf(stderr, "Incorrect frame size\n");
2344 av_exit(1);
2346 if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2347 fprintf(stderr, "Frame size must be a multiple of 2\n");
2348 av_exit(1);
2353 #define SCALEBITS 10
2354 #define ONE_HALF (1 << (SCALEBITS - 1))
2355 #define FIX(x) ((int) ((x) * (1<<SCALEBITS) + 0.5))
2357 #define RGB_TO_Y(r, g, b) \
2358 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2359 FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2361 #define RGB_TO_U(r1, g1, b1, shift)\
2362 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 + \
2363 FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2365 #define RGB_TO_V(r1, g1, b1, shift)\
2366 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 - \
2367 FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2369 static void opt_pad_color(const char *arg) {
2370 /* Input is expected to be six hex digits similar to
2371 how colors are expressed in html tags (but without the #) */
2372 int rgb = strtol(arg, NULL, 16);
2373 int r,g,b;
2375 r = (rgb >> 16);
2376 g = ((rgb >> 8) & 255);
2377 b = (rgb & 255);
2379 padcolor[0] = RGB_TO_Y(r,g,b);
2380 padcolor[1] = RGB_TO_U(r,g,b,0);
2381 padcolor[2] = RGB_TO_V(r,g,b,0);
2384 static void opt_frame_pad_top(const char *arg)
2386 frame_padtop = atoi(arg);
2387 if (frame_padtop < 0) {
2388 fprintf(stderr, "Incorrect top pad size\n");
2389 av_exit(1);
2391 if ((frame_padtop % 2) != 0) {
2392 fprintf(stderr, "Top pad size must be a multiple of 2\n");
2393 av_exit(1);
2397 static void opt_frame_pad_bottom(const char *arg)
2399 frame_padbottom = atoi(arg);
2400 if (frame_padbottom < 0) {
2401 fprintf(stderr, "Incorrect bottom pad size\n");
2402 av_exit(1);
2404 if ((frame_padbottom % 2) != 0) {
2405 fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2406 av_exit(1);
2411 static void opt_frame_pad_left(const char *arg)
2413 frame_padleft = atoi(arg);
2414 if (frame_padleft < 0) {
2415 fprintf(stderr, "Incorrect left pad size\n");
2416 av_exit(1);
2418 if ((frame_padleft % 2) != 0) {
2419 fprintf(stderr, "Left pad size must be a multiple of 2\n");
2420 av_exit(1);
2425 static void opt_frame_pad_right(const char *arg)
2427 frame_padright = atoi(arg);
2428 if (frame_padright < 0) {
2429 fprintf(stderr, "Incorrect right pad size\n");
2430 av_exit(1);
2432 if ((frame_padright % 2) != 0) {
2433 fprintf(stderr, "Right pad size must be a multiple of 2\n");
2434 av_exit(1);
2438 static void list_pix_fmts(void)
2440 int i;
2441 char pix_fmt_str[128];
2442 for (i=-1; i < PIX_FMT_NB; i++) {
2443 avcodec_pix_fmt_string (pix_fmt_str, sizeof(pix_fmt_str), i);
2444 fprintf(stdout, "%s\n", pix_fmt_str);
2448 static void opt_frame_pix_fmt(const char *arg)
2450 if (strcmp(arg, "list"))
2451 frame_pix_fmt = avcodec_get_pix_fmt(arg);
2452 else {
2453 list_pix_fmts();
2454 av_exit(0);
2458 static void opt_frame_aspect_ratio(const char *arg)
2460 int x = 0, y = 0;
2461 double ar = 0;
2462 const char *p;
2463 char *end;
2465 p = strchr(arg, ':');
2466 if (p) {
2467 x = strtol(arg, &end, 10);
2468 if (end == p)
2469 y = strtol(end+1, &end, 10);
2470 if (x > 0 && y > 0)
2471 ar = (double)x / (double)y;
2472 } else
2473 ar = strtod(arg, NULL);
2475 if (!ar) {
2476 fprintf(stderr, "Incorrect aspect ratio specification.\n");
2477 av_exit(1);
2479 frame_aspect_ratio = ar;
2482 static void opt_qscale(const char *arg)
2484 video_qscale = atof(arg);
2485 if (video_qscale <= 0 ||
2486 video_qscale > 255) {
2487 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2488 av_exit(1);
2492 static void opt_qdiff(const char *arg)
2494 video_qdiff = atoi(arg);
2495 if (video_qdiff < 0 ||
2496 video_qdiff > 31) {
2497 fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2498 av_exit(1);
2502 static void opt_strict(const char *arg)
2504 strict= atoi(arg);
2507 static void opt_top_field_first(const char *arg)
2509 top_field_first= atoi(arg);
2512 static int opt_thread_count(const char *opt, const char *arg)
2514 thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2515 #if !defined(HAVE_THREADS)
2516 if (verbose >= 0)
2517 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2518 #endif
2519 return 0;
2522 static int opt_audio_rate(const char *opt, const char *arg)
2524 audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2525 return 0;
2528 static int opt_audio_channels(const char *opt, const char *arg)
2530 audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
2531 return 0;
2534 static void opt_video_channel(const char *arg)
2536 video_channel = strtol(arg, NULL, 0);
2539 static void opt_video_standard(const char *arg)
2541 video_standard = av_strdup(arg);
2544 static void opt_codec(int *pstream_copy, char **pcodec_name,
2545 int codec_type, const char *arg)
2547 av_freep(pcodec_name);
2548 if (!strcmp(arg, "copy")) {
2549 *pstream_copy = 1;
2550 } else {
2551 *pcodec_name = av_strdup(arg);
2555 static void opt_audio_codec(const char *arg)
2557 opt_codec(&audio_stream_copy, &audio_codec_name, CODEC_TYPE_AUDIO, arg);
2560 static void opt_audio_tag(const char *arg)
2562 char *tail;
2563 audio_codec_tag= strtol(arg, &tail, 0);
2565 if(!tail || *tail)
2566 audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2569 static void opt_video_tag(const char *arg)
2571 char *tail;
2572 video_codec_tag= strtol(arg, &tail, 0);
2574 if(!tail || *tail)
2575 video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2578 #ifdef CONFIG_VHOOK
2579 static void add_frame_hooker(const char *arg)
2581 int argc = 0;
2582 char *argv[64];
2583 int i;
2584 char *args = av_strdup(arg);
2586 using_vhook = 1;
2588 argv[0] = strtok(args, " ");
2589 while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2592 i = frame_hook_add(argc, argv);
2594 if (i != 0) {
2595 fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2596 av_exit(1);
2599 #endif
2601 static void opt_video_codec(const char *arg)
2603 opt_codec(&video_stream_copy, &video_codec_name, CODEC_TYPE_VIDEO, arg);
2606 static void opt_subtitle_codec(const char *arg)
2608 opt_codec(&subtitle_stream_copy, &subtitle_codec_name, CODEC_TYPE_SUBTITLE, arg);
2611 static void opt_map(const char *arg)
2613 AVStreamMap *m;
2614 char *p;
2616 m = &stream_maps[nb_stream_maps++];
2618 m->file_index = strtol(arg, &p, 0);
2619 if (*p)
2620 p++;
2622 m->stream_index = strtol(p, &p, 0);
2623 if (*p) {
2624 p++;
2625 m->sync_file_index = strtol(p, &p, 0);
2626 if (*p)
2627 p++;
2628 m->sync_stream_index = strtol(p, &p, 0);
2629 } else {
2630 m->sync_file_index = m->file_index;
2631 m->sync_stream_index = m->stream_index;
2635 static void opt_map_meta_data(const char *arg)
2637 AVMetaDataMap *m;
2638 char *p;
2640 m = &meta_data_maps[nb_meta_data_maps++];
2642 m->out_file = strtol(arg, &p, 0);
2643 if (*p)
2644 p++;
2646 m->in_file = strtol(p, &p, 0);
2649 static int opt_recording_time(const char *opt, const char *arg)
2651 recording_time = parse_time_or_die(opt, arg, 1);
2652 return 0;
2655 static int opt_start_time(const char *opt, const char *arg)
2657 start_time = parse_time_or_die(opt, arg, 1);
2658 return 0;
2661 static int opt_rec_timestamp(const char *opt, const char *arg)
2663 rec_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
2664 return 0;
2667 static int opt_input_ts_offset(const char *opt, const char *arg)
2669 input_ts_offset = parse_time_or_die(opt, arg, 1);
2670 return 0;
2673 static enum CodecID find_codec_or_die(const char *name, int type, int encoder)
2675 const char *codec_string = encoder ? "encoder" : "decoder";
2676 AVCodec *codec;
2678 if(!name)
2679 return CODEC_ID_NONE;
2680 codec = encoder ?
2681 avcodec_find_encoder_by_name(name) :
2682 avcodec_find_decoder_by_name(name);
2683 if(!codec) {
2684 av_log(NULL, AV_LOG_ERROR, "Unknown %s '%s'\n", codec_string, name);
2685 av_exit(1);
2687 if(codec->type != type) {
2688 av_log(NULL, AV_LOG_ERROR, "Invalid %s type '%s'\n", codec_string, name);
2689 av_exit(1);
2691 return codec->id;
2694 static void set_context_opts(void *ctx, void *opts_ctx, int flags)
2696 int i;
2697 for(i=0; i<opt_name_count; i++){
2698 char buf[256];
2699 const AVOption *opt;
2700 const char *str= av_get_string(opts_ctx, opt_names[i], &opt, buf, sizeof(buf));
2701 /* if an option with name opt_names[i] is present in opts_ctx then str is non-NULL */
2702 if(str && ((opt->flags & flags) == flags))
2703 av_set_string(ctx, opt_names[i], str);
2707 static void opt_input_file(const char *filename)
2709 AVFormatContext *ic;
2710 AVFormatParameters params, *ap = &params;
2711 int err, i, ret, rfps, rfps_base;
2712 int64_t timestamp;
2714 if (!strcmp(filename, "-"))
2715 filename = "pipe:";
2717 using_stdin |= !strncmp(filename, "pipe:", 5) ||
2718 !strcmp(filename, "/dev/stdin");
2720 /* get default parameters from command line */
2721 ic = av_alloc_format_context();
2723 memset(ap, 0, sizeof(*ap));
2724 ap->prealloced_context = 1;
2725 ap->sample_rate = audio_sample_rate;
2726 ap->channels = audio_channels;
2727 ap->time_base.den = frame_rate.num;
2728 ap->time_base.num = frame_rate.den;
2729 ap->width = frame_width + frame_padleft + frame_padright;
2730 ap->height = frame_height + frame_padtop + frame_padbottom;
2731 ap->pix_fmt = frame_pix_fmt;
2732 ap->channel = video_channel;
2733 ap->standard = video_standard;
2734 ap->video_codec_id = find_codec_or_die(video_codec_name, CODEC_TYPE_VIDEO, 0);
2735 ap->audio_codec_id = find_codec_or_die(audio_codec_name, CODEC_TYPE_AUDIO, 0);
2736 if(pgmyuv_compatibility_hack)
2737 ap->video_codec_id= CODEC_ID_PGMYUV;
2739 set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM);
2741 ic->video_codec_id = find_codec_or_die(video_codec_name , CODEC_TYPE_VIDEO , 0);
2742 ic->audio_codec_id = find_codec_or_die(audio_codec_name , CODEC_TYPE_AUDIO , 0);
2743 ic->subtitle_codec_id= find_codec_or_die(subtitle_codec_name, CODEC_TYPE_SUBTITLE, 0);
2745 /* open the input file with generic libav function */
2746 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2747 if (err < 0) {
2748 print_error(filename, err);
2749 av_exit(1);
2751 if(opt_programid) {
2752 int i;
2753 for(i=0; i<ic->nb_programs; i++)
2754 if(ic->programs[i]->id != opt_programid)
2755 ic->programs[i]->discard = AVDISCARD_ALL;
2758 ic->loop_input = loop_input;
2760 /* If not enough info to get the stream parameters, we decode the
2761 first frames to get it. (used in mpeg case for example) */
2762 ret = av_find_stream_info(ic);
2763 if (ret < 0 && verbose >= 0) {
2764 fprintf(stderr, "%s: could not find codec parameters\n", filename);
2765 av_exit(1);
2768 timestamp = start_time;
2769 /* add the stream start time */
2770 if (ic->start_time != AV_NOPTS_VALUE)
2771 timestamp += ic->start_time;
2773 /* if seeking requested, we execute it */
2774 if (start_time != 0) {
2775 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2776 if (ret < 0) {
2777 fprintf(stderr, "%s: could not seek to position %0.3f\n",
2778 filename, (double)timestamp / AV_TIME_BASE);
2780 /* reset seek info */
2781 start_time = 0;
2784 /* update the current parameters so that they match the one of the input stream */
2785 for(i=0;i<ic->nb_streams;i++) {
2786 AVCodecContext *enc = ic->streams[i]->codec;
2787 if(thread_count>1)
2788 avcodec_thread_init(enc, thread_count);
2789 enc->thread_count= thread_count;
2790 switch(enc->codec_type) {
2791 case CODEC_TYPE_AUDIO:
2792 set_context_opts(enc, avctx_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
2793 //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2794 audio_channels = enc->channels;
2795 audio_sample_rate = enc->sample_rate;
2796 if(audio_disable)
2797 ic->streams[i]->discard= AVDISCARD_ALL;
2798 break;
2799 case CODEC_TYPE_VIDEO:
2800 set_context_opts(enc, avctx_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM);
2801 frame_height = enc->height;
2802 frame_width = enc->width;
2803 frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2804 frame_pix_fmt = enc->pix_fmt;
2805 rfps = ic->streams[i]->r_frame_rate.num;
2806 rfps_base = ic->streams[i]->r_frame_rate.den;
2807 if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2808 if(me_threshold)
2809 enc->debug |= FF_DEBUG_MV;
2811 if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2813 if (verbose >= 0)
2814 fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2815 i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2817 (float)rfps / rfps_base, rfps, rfps_base);
2819 /* update the current frame rate to match the stream frame rate */
2820 frame_rate.num = rfps;
2821 frame_rate.den = rfps_base;
2823 enc->rate_emu = rate_emu;
2824 if(video_disable)
2825 ic->streams[i]->discard= AVDISCARD_ALL;
2826 else if(video_discard)
2827 ic->streams[i]->discard= video_discard;
2828 break;
2829 case CODEC_TYPE_DATA:
2830 break;
2831 case CODEC_TYPE_SUBTITLE:
2832 if(subtitle_disable)
2833 ic->streams[i]->discard = AVDISCARD_ALL;
2834 break;
2835 case CODEC_TYPE_ATTACHMENT:
2836 case CODEC_TYPE_UNKNOWN:
2837 break;
2838 default:
2839 abort();
2843 input_files[nb_input_files] = ic;
2844 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2845 /* dump the file content */
2846 if (verbose >= 0)
2847 dump_format(ic, nb_input_files, filename, 0);
2849 nb_input_files++;
2850 file_iformat = NULL;
2851 file_oformat = NULL;
2853 video_channel = 0;
2855 rate_emu = 0;
2856 av_freep(&video_codec_name);
2857 av_freep(&audio_codec_name);
2858 av_freep(&subtitle_codec_name);
2861 static void check_audio_video_sub_inputs(int *has_video_ptr, int *has_audio_ptr,
2862 int *has_subtitle_ptr)
2864 int has_video, has_audio, has_subtitle, i, j;
2865 AVFormatContext *ic;
2867 has_video = 0;
2868 has_audio = 0;
2869 has_subtitle = 0;
2870 for(j=0;j<nb_input_files;j++) {
2871 ic = input_files[j];
2872 for(i=0;i<ic->nb_streams;i++) {
2873 AVCodecContext *enc = ic->streams[i]->codec;
2874 switch(enc->codec_type) {
2875 case CODEC_TYPE_AUDIO:
2876 has_audio = 1;
2877 break;
2878 case CODEC_TYPE_VIDEO:
2879 has_video = 1;
2880 break;
2881 case CODEC_TYPE_SUBTITLE:
2882 has_subtitle = 1;
2883 break;
2884 case CODEC_TYPE_DATA:
2885 case CODEC_TYPE_ATTACHMENT:
2886 case CODEC_TYPE_UNKNOWN:
2887 break;
2888 default:
2889 abort();
2893 *has_video_ptr = has_video;
2894 *has_audio_ptr = has_audio;
2895 *has_subtitle_ptr = has_subtitle;
2898 static void new_video_stream(AVFormatContext *oc)
2900 AVStream *st;
2901 AVCodecContext *video_enc;
2902 int codec_id;
2904 st = av_new_stream(oc, oc->nb_streams);
2905 if (!st) {
2906 fprintf(stderr, "Could not alloc stream\n");
2907 av_exit(1);
2909 avcodec_get_context_defaults2(st->codec, CODEC_TYPE_VIDEO);
2910 bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2911 video_bitstream_filters= NULL;
2913 if(thread_count>1)
2914 avcodec_thread_init(st->codec, thread_count);
2916 video_enc = st->codec;
2918 if(video_codec_tag)
2919 video_enc->codec_tag= video_codec_tag;
2921 if( (video_global_header&1)
2922 || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2923 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2924 avctx_opts[CODEC_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
2926 if(video_global_header&2){
2927 video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2928 avctx_opts[CODEC_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2931 if (video_stream_copy) {
2932 st->stream_copy = 1;
2933 video_enc->codec_type = CODEC_TYPE_VIDEO;
2934 } else {
2935 const char *p;
2936 int i;
2937 AVCodec *codec;
2938 AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};
2940 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2941 if (video_codec_name)
2942 codec_id = find_codec_or_die(video_codec_name, CODEC_TYPE_VIDEO, 1);
2944 video_enc->codec_id = codec_id;
2945 codec = avcodec_find_encoder(codec_id);
2947 set_context_opts(video_enc, avctx_opts[CODEC_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
2949 video_enc->time_base.den = fps.num;
2950 video_enc->time_base.num = fps.den;
2951 if(codec && codec->supported_framerates){
2952 const AVRational *p= codec->supported_framerates;
2953 const AVRational *best=NULL;
2954 AVRational best_error= (AVRational){INT_MAX, 1};
2955 for(; p->den!=0; p++){
2956 AVRational error= av_sub_q(fps, *p);
2957 if(error.num <0) error.num *= -1;
2958 if(av_cmp_q(error, best_error) < 0){
2959 best_error= error;
2960 best= p;
2963 video_enc->time_base.den= best->num;
2964 video_enc->time_base.num= best->den;
2967 video_enc->width = frame_width + frame_padright + frame_padleft;
2968 video_enc->height = frame_height + frame_padtop + frame_padbottom;
2969 video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
2970 video_enc->pix_fmt = frame_pix_fmt;
2972 if(codec && codec->pix_fmts){
2973 const enum PixelFormat *p= codec->pix_fmts;
2974 for(; *p!=-1; p++){
2975 if(*p == video_enc->pix_fmt)
2976 break;
2978 if(*p == -1)
2979 video_enc->pix_fmt = codec->pix_fmts[0];
2982 if (intra_only)
2983 video_enc->gop_size = 0;
2984 if (video_qscale || same_quality) {
2985 video_enc->flags |= CODEC_FLAG_QSCALE;
2986 video_enc->global_quality=
2987 st->quality = FF_QP2LAMBDA * video_qscale;
2990 if(intra_matrix)
2991 video_enc->intra_matrix = intra_matrix;
2992 if(inter_matrix)
2993 video_enc->inter_matrix = inter_matrix;
2995 video_enc->max_qdiff = video_qdiff;
2996 video_enc->thread_count = thread_count;
2997 p= video_rc_override_string;
2998 for(i=0; p; i++){
2999 int start, end, q;
3000 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3001 if(e!=3){
3002 fprintf(stderr, "error parsing rc_override\n");
3003 av_exit(1);
3005 video_enc->rc_override=
3006 av_realloc(video_enc->rc_override,
3007 sizeof(RcOverride)*(i+1));
3008 video_enc->rc_override[i].start_frame= start;
3009 video_enc->rc_override[i].end_frame = end;
3010 if(q>0){
3011 video_enc->rc_override[i].qscale= q;
3012 video_enc->rc_override[i].quality_factor= 1.0;
3014 else{
3015 video_enc->rc_override[i].qscale= 0;
3016 video_enc->rc_override[i].quality_factor= -q/100.0;
3018 p= strchr(p, '/');
3019 if(p) p++;
3021 video_enc->rc_override_count=i;
3022 if (!video_enc->rc_initial_buffer_occupancy)
3023 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
3024 video_enc->me_threshold= me_threshold;
3025 video_enc->intra_dc_precision= intra_dc_precision - 8;
3026 video_enc->strict_std_compliance = strict;
3028 if (do_psnr)
3029 video_enc->flags|= CODEC_FLAG_PSNR;
3031 /* two pass mode */
3032 if (do_pass) {
3033 if (do_pass == 1) {
3034 video_enc->flags |= CODEC_FLAG_PASS1;
3035 } else {
3036 video_enc->flags |= CODEC_FLAG_PASS2;
3041 /* reset some key parameters */
3042 video_disable = 0;
3043 av_freep(&video_codec_name);
3044 video_stream_copy = 0;
3047 static void new_audio_stream(AVFormatContext *oc)
3049 AVStream *st;
3050 AVCodecContext *audio_enc;
3051 int codec_id;
3053 st = av_new_stream(oc, oc->nb_streams);
3054 if (!st) {
3055 fprintf(stderr, "Could not alloc stream\n");
3056 av_exit(1);
3058 avcodec_get_context_defaults2(st->codec, CODEC_TYPE_AUDIO);
3060 bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3061 audio_bitstream_filters= NULL;
3063 if(thread_count>1)
3064 avcodec_thread_init(st->codec, thread_count);
3066 audio_enc = st->codec;
3067 audio_enc->codec_type = CODEC_TYPE_AUDIO;
3068 audio_enc->strict_std_compliance = strict;
3070 if(audio_codec_tag)
3071 audio_enc->codec_tag= audio_codec_tag;
3073 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3074 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3075 avctx_opts[CODEC_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
3077 if (audio_stream_copy) {
3078 st->stream_copy = 1;
3079 audio_enc->channels = audio_channels;
3080 } else {
3081 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3083 set_context_opts(audio_enc, avctx_opts[CODEC_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
3085 if (audio_codec_name)
3086 codec_id = find_codec_or_die(audio_codec_name, CODEC_TYPE_AUDIO, 1);
3087 audio_enc->codec_id = codec_id;
3089 if (audio_qscale > QSCALE_NONE) {
3090 audio_enc->flags |= CODEC_FLAG_QSCALE;
3091 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3093 audio_enc->thread_count = thread_count;
3094 audio_enc->channels = audio_channels;
3096 audio_enc->sample_rate = audio_sample_rate;
3097 audio_enc->time_base= (AVRational){1, audio_sample_rate};
3098 if (audio_language) {
3099 av_strlcpy(st->language, audio_language, sizeof(st->language));
3100 av_free(audio_language);
3101 audio_language = NULL;
3104 /* reset some key parameters */
3105 audio_disable = 0;
3106 av_freep(&audio_codec_name);
3107 audio_stream_copy = 0;
3110 static void new_subtitle_stream(AVFormatContext *oc)
3112 AVStream *st;
3113 AVCodecContext *subtitle_enc;
3115 st = av_new_stream(oc, oc->nb_streams);
3116 if (!st) {
3117 fprintf(stderr, "Could not alloc stream\n");
3118 av_exit(1);
3120 avcodec_get_context_defaults2(st->codec, CODEC_TYPE_SUBTITLE);
3122 bitstream_filters[nb_output_files][oc->nb_streams - 1]= subtitle_bitstream_filters;
3123 subtitle_bitstream_filters= NULL;
3125 subtitle_enc = st->codec;
3126 subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3127 if (subtitle_stream_copy) {
3128 st->stream_copy = 1;
3129 } else {
3130 set_context_opts(avctx_opts[CODEC_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM);
3131 subtitle_enc->codec_id = find_codec_or_die(subtitle_codec_name, CODEC_TYPE_SUBTITLE, 1);
3134 if (subtitle_language) {
3135 av_strlcpy(st->language, subtitle_language, sizeof(st->language));
3136 av_free(subtitle_language);
3137 subtitle_language = NULL;
3140 subtitle_disable = 0;
3141 av_freep(&subtitle_codec_name);
3142 subtitle_stream_copy = 0;
3145 static void opt_new_audio_stream(void)
3147 AVFormatContext *oc;
3148 if (nb_output_files <= 0) {
3149 fprintf(stderr, "At least one output file must be specified\n");
3150 av_exit(1);
3152 oc = output_files[nb_output_files - 1];
3153 new_audio_stream(oc);
3156 static void opt_new_video_stream(void)
3158 AVFormatContext *oc;
3159 if (nb_output_files <= 0) {
3160 fprintf(stderr, "At least one output file must be specified\n");
3161 av_exit(1);
3163 oc = output_files[nb_output_files - 1];
3164 new_video_stream(oc);
3167 static void opt_new_subtitle_stream(void)
3169 AVFormatContext *oc;
3170 if (nb_output_files <= 0) {
3171 fprintf(stderr, "At least one output file must be specified\n");
3172 av_exit(1);
3174 oc = output_files[nb_output_files - 1];
3175 new_subtitle_stream(oc);
3178 static void opt_output_file(const char *filename)
3180 AVFormatContext *oc;
3181 int use_video, use_audio, use_subtitle;
3182 int input_has_video, input_has_audio, input_has_subtitle;
3183 AVFormatParameters params, *ap = &params;
3185 if (!strcmp(filename, "-"))
3186 filename = "pipe:";
3188 oc = av_alloc_format_context();
3190 if (!file_oformat) {
3191 file_oformat = guess_format(NULL, filename, NULL);
3192 if (!file_oformat) {
3193 fprintf(stderr, "Unable to find a suitable output format for '%s'\n",
3194 filename);
3195 av_exit(1);
3199 oc->oformat = file_oformat;
3200 av_strlcpy(oc->filename, filename, sizeof(oc->filename));
3202 if (!strcmp(file_oformat->name, "ffm") &&
3203 av_strstart(filename, "http:", NULL)) {
3204 /* special case for files sent to ffserver: we get the stream
3205 parameters from ffserver */
3206 int err = read_ffserver_streams(oc, filename);
3207 if (err < 0) {
3208 print_error(filename, err);
3209 av_exit(1);
3211 } else {
3212 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
3213 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
3214 use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
3216 /* disable if no corresponding type found and at least one
3217 input file */
3218 if (nb_input_files > 0) {
3219 check_audio_video_sub_inputs(&input_has_video, &input_has_audio,
3220 &input_has_subtitle);
3221 if (!input_has_video)
3222 use_video = 0;
3223 if (!input_has_audio)
3224 use_audio = 0;
3225 if (!input_has_subtitle)
3226 use_subtitle = 0;
3229 /* manual disable */
3230 if (audio_disable) {
3231 use_audio = 0;
3233 if (video_disable) {
3234 use_video = 0;
3236 if (subtitle_disable) {
3237 use_subtitle = 0;
3240 if (use_video) {
3241 new_video_stream(oc);
3244 if (use_audio) {
3245 new_audio_stream(oc);
3248 if (use_subtitle) {
3249 new_subtitle_stream(oc);
3252 oc->timestamp = rec_timestamp;
3254 if (str_title)
3255 av_strlcpy(oc->title, str_title, sizeof(oc->title));
3256 if (str_author)
3257 av_strlcpy(oc->author, str_author, sizeof(oc->author));
3258 if (str_copyright)
3259 av_strlcpy(oc->copyright, str_copyright, sizeof(oc->copyright));
3260 if (str_comment)
3261 av_strlcpy(oc->comment, str_comment, sizeof(oc->comment));
3262 if (str_album)
3263 av_strlcpy(oc->album, str_album, sizeof(oc->album));
3264 if (str_genre)
3265 av_strlcpy(oc->genre, str_genre, sizeof(oc->genre));
3268 output_files[nb_output_files++] = oc;
3270 /* check filename in case of an image number is expected */
3271 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3272 if (!av_filename_number_test(oc->filename)) {
3273 print_error(oc->filename, AVERROR_NUMEXPECTED);
3274 av_exit(1);
3278 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3279 /* test if it already exists to avoid loosing precious files */
3280 if (!file_overwrite &&
3281 (strchr(filename, ':') == NULL ||
3282 filename[1] == ':' ||
3283 av_strstart(filename, "file:", NULL))) {
3284 if (url_exist(filename)) {
3285 int c;
3287 if (!using_stdin) {
3288 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3289 fflush(stderr);
3290 c = getchar();
3291 if (toupper(c) != 'Y') {
3292 fprintf(stderr, "Not overwriting - exiting\n");
3293 av_exit(1);
3296 else {
3297 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3298 av_exit(1);
3303 /* open the file */
3304 if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3305 fprintf(stderr, "Could not open '%s'\n", filename);
3306 av_exit(1);
3310 memset(ap, 0, sizeof(*ap));
3311 if (av_set_parameters(oc, ap) < 0) {
3312 fprintf(stderr, "%s: Invalid encoding parameters\n",
3313 oc->filename);
3314 av_exit(1);
3317 oc->preload= (int)(mux_preload*AV_TIME_BASE);
3318 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3319 oc->loop_output = loop_output;
3321 set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM);
3323 /* reset some options */
3324 file_oformat = NULL;
3325 file_iformat = NULL;
3328 /* same option as mencoder */
3329 static void opt_pass(const char *pass_str)
3331 int pass;
3332 pass = atoi(pass_str);
3333 if (pass != 1 && pass != 2) {
3334 fprintf(stderr, "pass number can be only 1 or 2\n");
3335 av_exit(1);
3337 do_pass = pass;
3340 static int64_t getutime(void)
3342 #ifdef HAVE_GETRUSAGE
3343 struct rusage rusage;
3345 getrusage(RUSAGE_SELF, &rusage);
3346 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3347 #elif defined(HAVE_GETPROCESSTIMES)
3348 HANDLE proc;
3349 FILETIME c, e, k, u;
3350 proc = GetCurrentProcess();
3351 GetProcessTimes(proc, &c, &e, &k, &u);
3352 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3353 #else
3354 return av_gettime();
3355 #endif
3358 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3360 int i;
3361 const char *p = str;
3362 for(i = 0;; i++) {
3363 dest[i] = atoi(p);
3364 if(i == 63)
3365 break;
3366 p = strchr(p, ',');
3367 if(!p) {
3368 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3369 av_exit(1);
3371 p++;
3375 static void opt_inter_matrix(const char *arg)
3377 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3378 parse_matrix_coeffs(inter_matrix, arg);
3381 static void opt_intra_matrix(const char *arg)
3383 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3384 parse_matrix_coeffs(intra_matrix, arg);
3388 * Trivial log callback.
3389 * Only suitable for show_help and similar since it lacks prefix handling.
3391 static void log_callback_help(void* ptr, int level, const char* fmt, va_list vl)
3393 vfprintf(stdout, fmt, vl);
3396 static void show_help(void)
3398 av_log_set_callback(log_callback_help);
3399 printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
3400 "Hyper fast Audio and Video encoder\n");
3401 printf("\n");
3402 show_help_options(options, "Main options:\n",
3403 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
3404 show_help_options(options, "\nAdvanced options:\n",
3405 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
3406 OPT_EXPERT);
3407 show_help_options(options, "\nVideo options:\n",
3408 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3409 OPT_VIDEO);
3410 show_help_options(options, "\nAdvanced Video options:\n",
3411 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3412 OPT_VIDEO | OPT_EXPERT);
3413 show_help_options(options, "\nAudio options:\n",
3414 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3415 OPT_AUDIO);
3416 show_help_options(options, "\nAdvanced Audio options:\n",
3417 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
3418 OPT_AUDIO | OPT_EXPERT);
3419 show_help_options(options, "\nSubtitle options:\n",
3420 OPT_SUBTITLE | OPT_GRAB,
3421 OPT_SUBTITLE);
3422 show_help_options(options, "\nAudio/Video grab options:\n",
3423 OPT_GRAB,
3424 OPT_GRAB);
3425 printf("\n");
3426 av_opt_show(avctx_opts[0], NULL);
3427 printf("\n");
3428 av_opt_show(avformat_opts, NULL);
3429 printf("\n");
3430 av_opt_show(sws_opts, NULL);
3433 static void opt_target(const char *arg)
3435 int norm = -1;
3436 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3438 if(!strncmp(arg, "pal-", 4)) {
3439 norm = 0;
3440 arg += 4;
3441 } else if(!strncmp(arg, "ntsc-", 5)) {
3442 norm = 1;
3443 arg += 5;
3444 } else if(!strncmp(arg, "film-", 5)) {
3445 norm = 2;
3446 arg += 5;
3447 } else {
3448 int fr;
3449 /* Calculate FR via float to avoid int overflow */
3450 fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
3451 if(fr == 25000) {
3452 norm = 0;
3453 } else if((fr == 29970) || (fr == 23976)) {
3454 norm = 1;
3455 } else {
3456 /* Try to determine PAL/NTSC by peeking in the input files */
3457 if(nb_input_files) {
3458 int i, j;
3459 for(j = 0; j < nb_input_files; j++) {
3460 for(i = 0; i < input_files[j]->nb_streams; i++) {
3461 AVCodecContext *c = input_files[j]->streams[i]->codec;
3462 if(c->codec_type != CODEC_TYPE_VIDEO)
3463 continue;
3464 fr = c->time_base.den * 1000 / c->time_base.num;
3465 if(fr == 25000) {
3466 norm = 0;
3467 break;
3468 } else if((fr == 29970) || (fr == 23976)) {
3469 norm = 1;
3470 break;
3473 if(norm >= 0)
3474 break;
3478 if(verbose && norm >= 0)
3479 fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3482 if(norm < 0) {
3483 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3484 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3485 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3486 av_exit(1);
3489 if(!strcmp(arg, "vcd")) {
3491 opt_video_codec("mpeg1video");
3492 opt_audio_codec("mp2");
3493 opt_format("vcd");
3495 opt_frame_size(norm ? "352x240" : "352x288");
3496 opt_frame_rate(frame_rates[norm]);
3497 opt_default("gop", norm ? "18" : "15");
3499 opt_default("b", "1150000");
3500 opt_default("maxrate", "1150000");
3501 opt_default("minrate", "1150000");
3502 opt_default("bufsize", "327680"); // 40*1024*8;
3504 opt_default("ab", "224000");
3505 audio_sample_rate = 44100;
3506 audio_channels = 2;
3508 opt_default("packetsize", "2324");
3509 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
3511 /* We have to offset the PTS, so that it is consistent with the SCR.
3512 SCR starts at 36000, but the first two packs contain only padding
3513 and the first pack from the other stream, respectively, may also have
3514 been written before.
3515 So the real data starts at SCR 36000+3*1200. */
3516 mux_preload= (36000+3*1200) / 90000.0; //0.44
3517 } else if(!strcmp(arg, "svcd")) {
3519 opt_video_codec("mpeg2video");
3520 opt_audio_codec("mp2");
3521 opt_format("svcd");
3523 opt_frame_size(norm ? "480x480" : "480x576");
3524 opt_frame_rate(frame_rates[norm]);
3525 opt_default("gop", norm ? "18" : "15");
3527 opt_default("b", "2040000");
3528 opt_default("maxrate", "2516000");
3529 opt_default("minrate", "0"); //1145000;
3530 opt_default("bufsize", "1835008"); //224*1024*8;
3531 opt_default("flags", "+SCAN_OFFSET");
3534 opt_default("ab", "224000");
3535 audio_sample_rate = 44100;
3537 opt_default("packetsize", "2324");
3539 } else if(!strcmp(arg, "dvd")) {
3541 opt_video_codec("mpeg2video");
3542 opt_audio_codec("ac3");
3543 opt_format("dvd");
3545 opt_frame_size(norm ? "720x480" : "720x576");
3546 opt_frame_rate(frame_rates[norm]);
3547 opt_default("gop", norm ? "18" : "15");
3549 opt_default("b", "6000000");
3550 opt_default("maxrate", "9000000");
3551 opt_default("minrate", "0"); //1500000;
3552 opt_default("bufsize", "1835008"); //224*1024*8;
3554 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3555 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3557 opt_default("ab", "448000");
3558 audio_sample_rate = 48000;
3560 } else if(!strncmp(arg, "dv", 2)) {
3562 opt_format("dv");
3564 opt_frame_size(norm ? "720x480" : "720x576");
3565 opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3566 (norm ? "yuv411p" : "yuv420p"));
3567 opt_frame_rate(frame_rates[norm]);
3569 audio_sample_rate = 48000;
3570 audio_channels = 2;
3572 } else {
3573 fprintf(stderr, "Unknown target: %s\n", arg);
3574 av_exit(1);
3578 static void opt_vstats_file (const char *arg)
3580 av_free (vstats_filename);
3581 vstats_filename=av_strdup (arg);
3584 static void opt_vstats (void)
3586 char filename[40];
3587 time_t today2 = time(NULL);
3588 struct tm *today = localtime(&today2);
3590 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
3591 today->tm_sec);
3592 opt_vstats_file(filename);
3595 static int opt_bsf(const char *opt, const char *arg)
3597 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3598 AVBitStreamFilterContext **bsfp;
3600 if(!bsfc){
3601 fprintf(stderr, "Unknown bitstream filter %s\n", arg);
3602 av_exit(1);
3605 bsfp= *opt == 'v' ? &video_bitstream_filters :
3606 *opt == 'a' ? &audio_bitstream_filters :
3607 &subtitle_bitstream_filters;
3608 while(*bsfp)
3609 bsfp= &(*bsfp)->next;
3611 *bsfp= bsfc;
3613 return 0;
3616 static int opt_preset(const char *opt, const char *arg)
3618 FILE *f=NULL;
3619 char tmp[1000], tmp2[1000];
3620 int i;
3621 const char *base[3]= { getenv("HOME"),
3622 "/usr/local/share",
3623 "/usr/share",
3626 for(i=!base[0]; i<3 && !f; i++){
3627 snprintf(tmp, sizeof(tmp), "%s/%sffmpeg/%s.ffpreset", base[i], i ? "" : ".", arg);
3628 f= fopen(tmp, "r");
3629 if(!f){
3630 char *codec_name= *opt == 'v' ? video_codec_name :
3631 *opt == 'a' ? audio_codec_name :
3632 subtitle_codec_name;
3633 snprintf(tmp, sizeof(tmp), "%s/%sffmpeg/%s-%s.ffpreset", base[i], i ? "" : ".", codec_name, arg);
3634 f= fopen(tmp, "r");
3638 if(!f){
3639 fprintf(stderr, "Preset file not found\n");
3640 av_exit(1);
3643 while(!feof(f)){
3644 int e= fscanf(f, "%999[^=]=%999[^\n]\n", tmp, tmp2);
3645 if(e!=2){
3646 fprintf(stderr, "Preset file invalid\n");
3647 av_exit(1);
3649 opt_default(tmp, tmp2);
3652 fclose(f);
3654 return 0;
3657 static const OptionDef options[] = {
3658 /* main options */
3659 { "L", OPT_EXIT, {(void*)show_license}, "show license" },
3660 { "h", OPT_EXIT, {(void*)show_help}, "show help" },
3661 { "version", OPT_EXIT, {(void*)show_version}, "show version" },
3662 { "formats", OPT_EXIT, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3663 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3664 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3665 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3666 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3667 { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3668 { "t", OPT_FUNC2 | HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
3669 { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
3670 { "ss", OPT_FUNC2 | HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3671 { "itsoffset", OPT_FUNC2 | HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3672 { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3673 { "timestamp", OPT_FUNC2 | HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3674 { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3675 { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3676 { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3677 { "genre", HAS_ARG | OPT_STRING, {(void*)&str_genre}, "set the genre", "string" },
3678 { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3679 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3680 "add timings for benchmarking" },
3681 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3682 "dump each input packet" },
3683 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3684 "when dumping packets, also dump the payload" },
3685 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3686 { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3687 { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "number of times to loop output in formats that support looping (0 loops forever)", "" },
3688 { "v", HAS_ARG | OPT_FUNC2, {(void*)opt_verbose}, "set the logging verbosity level", "number" },
3689 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3690 { "threads", OPT_FUNC2 | HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3691 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3692 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3693 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
3694 { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3695 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3696 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3697 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
3698 { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
3700 /* video options */
3701 { "b", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3702 { "vb", OPT_FUNC2 | HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3703 { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3704 { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3705 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3706 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3707 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3708 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
3709 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3710 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3711 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3712 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3713 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3714 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3715 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3716 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3717 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
3718 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
3719 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
3720 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
3721 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
3722 { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantizer scale (VBR)", "q" },
3723 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
3724 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
3725 { "me_threshold", HAS_ARG | OPT_FUNC2 | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold", "threshold" },
3726 { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
3727 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
3728 "use same video quality as source (implies VBR)" },
3729 { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
3730 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
3731 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
3732 "deinterlace pictures" },
3733 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
3734 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
3735 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
3736 #ifdef CONFIG_VHOOK
3737 { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
3738 #endif
3739 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
3740 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
3741 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
3742 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
3743 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
3744 { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
3745 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
3747 /* audio options */
3748 { "ab", OPT_FUNC2 | HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
3749 { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3750 { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
3751 { "ar", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
3752 { "ac", HAS_ARG | OPT_FUNC2 | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
3753 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
3754 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
3755 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
3756 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
3757 { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
3758 { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
3760 /* subtitle options */
3761 { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
3762 { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
3763 { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
3764 { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
3766 /* grab options */
3767 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
3768 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
3769 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
3771 /* muxer options */
3772 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
3773 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
3775 { "absf", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
3776 { "vbsf", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
3777 { "sbsf", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
3779 { "apre", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "", "preset" },
3780 { "vpre", OPT_FUNC2 | HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "", "preset" },
3781 { "spre", OPT_FUNC2 | HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "", "preset" },
3783 { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
3784 { NULL, },
3787 int main(int argc, char **argv)
3789 int i;
3790 int64_t ti;
3792 avcodec_register_all();
3793 avdevice_register_all();
3794 av_register_all();
3796 for(i=0; i<CODEC_TYPE_NB; i++){
3797 avctx_opts[i]= avcodec_alloc_context2(i);
3799 avformat_opts = av_alloc_format_context();
3800 sws_opts = sws_getContext(16,16,0, 16,16,0, sws_flags, NULL,NULL,NULL);
3802 show_banner();
3803 if (argc <= 1) {
3804 show_help();
3805 av_exit(1);
3808 /* parse options */
3809 parse_options(argc, argv, options, opt_output_file);
3811 /* file converter / grab */
3812 if (nb_output_files <= 0) {
3813 fprintf(stderr, "Must supply at least one output file\n");
3814 av_exit(1);
3817 if (nb_input_files == 0) {
3818 fprintf(stderr, "Must supply at least one input file\n");
3819 av_exit(1);
3822 ti = getutime();
3823 av_encode(output_files, nb_output_files, input_files, nb_input_files,
3824 stream_maps, nb_stream_maps);
3825 ti = getutime() - ti;
3826 if (do_benchmark) {
3827 printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3830 return av_exit(0);