00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "config.h"
00023 #include <ctype.h>
00024 #include <string.h>
00025 #include <math.h>
00026 #include <stdlib.h>
00027 #include <errno.h>
00028 #include <signal.h>
00029 #include <limits.h>
00030 #include <unistd.h>
00031 #include "libavformat/avformat.h"
00032 #include "libavdevice/avdevice.h"
00033 #include "libswscale/swscale.h"
00034 #include "libavutil/opt.h"
00035 #include "libavcodec/audioconvert.h"
00036 #include "libavutil/audioconvert.h"
00037 #include "libavutil/parseutils.h"
00038 #include "libavutil/samplefmt.h"
00039 #include "libavutil/colorspace.h"
00040 #include "libavutil/fifo.h"
00041 #include "libavutil/intreadwrite.h"
00042 #include "libavutil/dict.h"
00043 #include "libavutil/pixdesc.h"
00044 #include "libavutil/avstring.h"
00045 #include "libavutil/libm.h"
00046 #include "libavformat/os_support.h"
00047
00048 #include "libavformat/ffm.h"
00049
00050 #if CONFIG_AVFILTER
00051 # include "libavfilter/avcodec.h"
00052 # include "libavfilter/avfilter.h"
00053 # include "libavfilter/avfiltergraph.h"
00054 # include "libavfilter/vsink_buffer.h"
00055 # include "libavfilter/vsrc_buffer.h"
00056 #endif
00057
00058 #if HAVE_SYS_RESOURCE_H
00059 #include <sys/types.h>
00060 #include <sys/time.h>
00061 #include <sys/resource.h>
00062 #elif HAVE_GETPROCESSTIMES
00063 #include <windows.h>
00064 #endif
00065 #if HAVE_GETPROCESSMEMORYINFO
00066 #include <windows.h>
00067 #include <psapi.h>
00068 #endif
00069
00070 #if HAVE_SYS_SELECT_H
00071 #include <sys/select.h>
00072 #endif
00073
00074 #if HAVE_TERMIOS_H
00075 #include <fcntl.h>
00076 #include <sys/ioctl.h>
00077 #include <sys/time.h>
00078 #include <termios.h>
00079 #elif HAVE_KBHIT
00080 #include <conio.h>
00081 #endif
00082 #include <time.h>
00083
00084 #include "cmdutils.h"
00085
00086 #include "libavutil/avassert.h"
00087
00088 const char program_name[] = "ffmpeg";
00089 const int program_birth_year = 2000;
00090
00091
00092 typedef struct AVStreamMap {
00093 int file_index;
00094 int stream_index;
00095 int sync_file_index;
00096 int sync_stream_index;
00097 } AVStreamMap;
00098
00102 typedef struct AVMetaDataMap {
00103 int file;
00104 char type;
00105 int index;
00106 } AVMetaDataMap;
00107
00108 typedef struct AVChapterMap {
00109 int in_file;
00110 int out_file;
00111 } AVChapterMap;
00112
00113 static const OptionDef options[];
00114
00115 #define MAX_FILES 100
00116 #define MAX_STREAMS 1024
00117
00118 static const char *last_asked_format = NULL;
00119 static int64_t input_files_ts_offset[MAX_FILES];
00120 static double *input_files_ts_scale[MAX_FILES] = {NULL};
00121 static AVCodec **input_codecs = NULL;
00122 static int nb_input_codecs = 0;
00123 static int nb_input_files_ts_scale[MAX_FILES] = {0};
00124
00125 static AVFormatContext *output_files[MAX_FILES];
00126 static int nb_output_files = 0;
00127
00128 static AVStreamMap *stream_maps = NULL;
00129 static int nb_stream_maps;
00130
00131
00132 static AVMetaDataMap (*meta_data_maps)[2] = NULL;
00133 static int nb_meta_data_maps;
00134 static int metadata_global_autocopy = 1;
00135 static int metadata_streams_autocopy = 1;
00136 static int metadata_chapters_autocopy = 1;
00137
00138 static AVChapterMap *chapter_maps = NULL;
00139 static int nb_chapter_maps;
00140
00141
00142 static int *streamid_map = NULL;
00143 static int nb_streamid_map = 0;
00144
00145 static int frame_width = 0;
00146 static int frame_height = 0;
00147 static float frame_aspect_ratio = 0;
00148 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
00149 static int frame_bits_per_raw_sample = 0;
00150 static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
00151 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
00152 static AVRational frame_rate;
00153 static float video_qscale = 0;
00154 static uint16_t *intra_matrix = NULL;
00155 static uint16_t *inter_matrix = NULL;
00156 static const char *video_rc_override_string=NULL;
00157 static int video_disable = 0;
00158 static int video_discard = 0;
00159 static char *video_codec_name = NULL;
00160 static unsigned int video_codec_tag = 0;
00161 static char *video_language = NULL;
00162 static int same_quality = 0;
00163 static int do_deinterlace = 0;
00164 static int top_field_first = -1;
00165 static int me_threshold = 0;
00166 static int intra_dc_precision = 8;
00167 static int loop_input = 0;
00168 static int loop_output = AVFMT_NOOUTPUTLOOP;
00169 static int qp_hist = 0;
00170 #if CONFIG_AVFILTER
00171 static char *vfilters = NULL;
00172 #endif
00173
00174 static int intra_only = 0;
00175 static int audio_sample_rate = 0;
00176 static int64_t channel_layout = 0;
00177 #define QSCALE_NONE -99999
00178 static float audio_qscale = QSCALE_NONE;
00179 static int audio_disable = 0;
00180 static int audio_channels = 0;
00181 static char *audio_codec_name = NULL;
00182 static unsigned int audio_codec_tag = 0;
00183 static char *audio_language = NULL;
00184
00185 static int subtitle_disable = 0;
00186 static char *subtitle_codec_name = NULL;
00187 static char *subtitle_language = NULL;
00188 static unsigned int subtitle_codec_tag = 0;
00189
00190 static int data_disable = 0;
00191 static char *data_codec_name = NULL;
00192 static unsigned int data_codec_tag = 0;
00193
00194 static float mux_preload= 0.5;
00195 static float mux_max_delay= 0.7;
00196
00197 static int64_t recording_time = INT64_MAX;
00198 static int64_t start_time = 0;
00199 static int64_t recording_timestamp = 0;
00200 static int64_t input_ts_offset = 0;
00201 static int file_overwrite = 0;
00202 static AVDictionary *metadata;
00203 static int do_benchmark = 0;
00204 static int do_hex_dump = 0;
00205 static int do_pkt_dump = 0;
00206 static int do_psnr = 0;
00207 static int do_pass = 0;
00208 static const char *pass_logfilename_prefix;
00209 static int audio_stream_copy = 0;
00210 static int video_stream_copy = 0;
00211 static int subtitle_stream_copy = 0;
00212 static int data_stream_copy = 0;
00213 static int video_sync_method= -1;
00214 static int audio_sync_method= 0;
00215 static float audio_drift_threshold= 0.1;
00216 static int copy_ts= 0;
00217 static int copy_tb= 0;
00218 static int opt_shortest = 0;
00219 static char *vstats_filename;
00220 static FILE *vstats_file;
00221 static int opt_programid = 0;
00222 static int copy_initial_nonkeyframes = 0;
00223
00224 static int rate_emu = 0;
00225
00226 static int video_channel = 0;
00227 static char *video_standard;
00228
00229 static int audio_volume = 256;
00230
00231 static int exit_on_error = 0;
00232 static int using_stdin = 0;
00233 static int verbose = 1;
00234 static int run_as_daemon = 0;
00235 static int thread_count= 1;
00236 static int q_pressed = 0;
00237 static int64_t video_size = 0;
00238 static int64_t audio_size = 0;
00239 static int64_t extra_size = 0;
00240 static int nb_frames_dup = 0;
00241 static int nb_frames_drop = 0;
00242 static int input_sync;
00243 static uint64_t limit_filesize = 0;
00244 static int force_fps = 0;
00245 static char *forced_key_frames = NULL;
00246
00247 static float dts_delta_threshold = 10;
00248
00249 static int64_t timer_start;
00250
00251 static uint8_t *audio_buf;
00252 static uint8_t *audio_out;
00253 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
00254
00255 static short *samples;
00256
00257 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
00258 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
00259 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
00260
00261 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
00262
00263 struct AVInputStream;
00264
00265 typedef struct AVOutputStream {
00266 int file_index;
00267 int index;
00268 int source_index;
00269 AVStream *st;
00270 int encoding_needed;
00271 int frame_number;
00272
00273
00274
00275 struct AVInputStream *sync_ist;
00276 int64_t sync_opts;
00277 AVBitStreamFilterContext *bitstream_filters;
00278 AVCodec *enc;
00279
00280
00281 int video_resample;
00282 AVFrame resample_frame;
00283 struct SwsContext *img_resample_ctx;
00284 int resample_height;
00285 int resample_width;
00286 int resample_pix_fmt;
00287 AVRational frame_rate;
00288
00289 float frame_aspect_ratio;
00290
00291
00292 int64_t *forced_kf_pts;
00293 int forced_kf_count;
00294 int forced_kf_index;
00295
00296
00297 int audio_resample;
00298 ReSampleContext *resample;
00299 int resample_sample_fmt;
00300 int resample_channels;
00301 int resample_sample_rate;
00302 int reformat_pair;
00303 AVAudioConvert *reformat_ctx;
00304 AVFifoBuffer *fifo;
00305 FILE *logfile;
00306
00307 #if CONFIG_AVFILTER
00308 AVFilterContext *output_video_filter;
00309 AVFilterContext *input_video_filter;
00310 AVFilterBufferRef *picref;
00311 char *avfilter;
00312 AVFilterGraph *graph;
00313 #endif
00314
00315 int sws_flags;
00316 char *forced_key_frames;
00317 } AVOutputStream;
00318
00319 static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
00320 static int nb_output_streams_for_file[MAX_FILES] = { 0 };
00321
00322 typedef struct AVInputStream {
00323 int file_index;
00324 AVStream *st;
00325 int discard;
00326 int decoding_needed;
00327 int64_t sample_index;
00328
00329 int64_t start;
00330 int64_t next_pts;
00331
00332 int64_t pts;
00333 int is_start;
00334 int showed_multi_packet_warning;
00335 int is_past_recording_time;
00336 #if CONFIG_AVFILTER
00337 AVFrame *filter_frame;
00338 int has_filter_frame;
00339 #endif
00340 } AVInputStream;
00341
00342 typedef struct AVInputFile {
00343 AVFormatContext *ctx;
00344 int eof_reached;
00345 int ist_index;
00346 int buffer_size;
00347 int nb_streams;
00348 } AVInputFile;
00349
00350 #if HAVE_TERMIOS_H
00351
00352
00353 static struct termios oldtty;
00354 #endif
00355
00356 static AVInputStream *input_streams = NULL;
00357 static int nb_input_streams = 0;
00358 static AVInputFile *input_files = NULL;
00359 static int nb_input_files = 0;
00360
00361 #if CONFIG_AVFILTER
00362
00363 static int configure_video_filters(AVInputStream *ist, AVOutputStream *ost)
00364 {
00365 AVFilterContext *last_filter, *filter;
00367 AVCodecContext *codec = ost->st->codec;
00368 AVCodecContext *icodec = ist->st->codec;
00369 enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
00370 AVRational sample_aspect_ratio;
00371 char args[255];
00372 int ret;
00373
00374 ost->graph = avfilter_graph_alloc();
00375
00376 if (ist->st->sample_aspect_ratio.num){
00377 sample_aspect_ratio = ist->st->sample_aspect_ratio;
00378 }else
00379 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
00380
00381 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
00382 ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
00383 sample_aspect_ratio.num, sample_aspect_ratio.den);
00384
00385 ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
00386 "src", args, NULL, ost->graph);
00387 if (ret < 0)
00388 return ret;
00389 ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
00390 "out", NULL, pix_fmts, ost->graph);
00391 if (ret < 0)
00392 return ret;
00393 last_filter = ost->input_video_filter;
00394
00395 if (codec->width != icodec->width || codec->height != icodec->height) {
00396 snprintf(args, 255, "%d:%d:flags=0x%X",
00397 codec->width,
00398 codec->height,
00399 ost->sws_flags);
00400 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
00401 NULL, args, NULL, ost->graph)) < 0)
00402 return ret;
00403 if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
00404 return ret;
00405 last_filter = filter;
00406 }
00407
00408 snprintf(args, sizeof(args), "flags=0x%X", ost->sws_flags);
00409 ost->graph->scale_sws_opts = av_strdup(args);
00410
00411 if (ost->avfilter) {
00412 AVFilterInOut *outputs = avfilter_inout_alloc();
00413 AVFilterInOut *inputs = avfilter_inout_alloc();
00414
00415 outputs->name = av_strdup("in");
00416 outputs->filter_ctx = last_filter;
00417 outputs->pad_idx = 0;
00418 outputs->next = NULL;
00419
00420 inputs->name = av_strdup("out");
00421 inputs->filter_ctx = ost->output_video_filter;
00422 inputs->pad_idx = 0;
00423 inputs->next = NULL;
00424
00425 if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
00426 return ret;
00427 av_freep(&ost->avfilter);
00428 } else {
00429 if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
00430 return ret;
00431 }
00432
00433 if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
00434 return ret;
00435
00436 codec->width = ost->output_video_filter->inputs[0]->w;
00437 codec->height = ost->output_video_filter->inputs[0]->h;
00438 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
00439 ost->frame_aspect_ratio ?
00440 av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
00441 ost->output_video_filter->inputs[0]->sample_aspect_ratio;
00442
00443 return 0;
00444 }
00445 #endif
00446
00447 static void term_exit(void)
00448 {
00449 av_log(NULL, AV_LOG_QUIET, "%s", "");
00450 #if HAVE_TERMIOS_H
00451 if(!run_as_daemon)
00452 tcsetattr (0, TCSANOW, &oldtty);
00453 #endif
00454 }
00455
00456 static volatile int received_sigterm = 0;
00457
00458 static void
00459 sigterm_handler(int sig)
00460 {
00461 received_sigterm = sig;
00462 q_pressed++;
00463 term_exit();
00464 }
00465
00466 static void term_init(void)
00467 {
00468 #if HAVE_TERMIOS_H
00469 if(!run_as_daemon){
00470 struct termios tty;
00471
00472 tcgetattr (0, &tty);
00473 oldtty = tty;
00474 atexit(term_exit);
00475
00476 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
00477 |INLCR|IGNCR|ICRNL|IXON);
00478 tty.c_oflag |= OPOST;
00479 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
00480 tty.c_cflag &= ~(CSIZE|PARENB);
00481 tty.c_cflag |= CS8;
00482 tty.c_cc[VMIN] = 1;
00483 tty.c_cc[VTIME] = 0;
00484
00485 tcsetattr (0, TCSANOW, &tty);
00486 signal(SIGQUIT, sigterm_handler);
00487 }
00488 #endif
00489
00490 signal(SIGINT , sigterm_handler);
00491 signal(SIGTERM, sigterm_handler);
00492 #ifdef SIGXCPU
00493 signal(SIGXCPU, sigterm_handler);
00494 #endif
00495 }
00496
00497
00498 static int read_key(void)
00499 {
00500 #if HAVE_TERMIOS_H
00501 int n = 1;
00502 unsigned char ch;
00503 struct timeval tv;
00504 fd_set rfds;
00505
00506 if(run_as_daemon)
00507 return -1;
00508
00509 FD_ZERO(&rfds);
00510 FD_SET(0, &rfds);
00511 tv.tv_sec = 0;
00512 tv.tv_usec = 0;
00513 n = select(1, &rfds, NULL, NULL, &tv);
00514 if (n > 0) {
00515 n = read(0, &ch, 1);
00516 if (n == 1)
00517 return ch;
00518
00519 return n;
00520 }
00521 #elif HAVE_KBHIT
00522 if(kbhit())
00523 return(getch());
00524 #endif
00525 return -1;
00526 }
00527
00528 static int decode_interrupt_cb(void)
00529 {
00530 q_pressed += read_key() == 'q';
00531 return q_pressed > 1;
00532 }
00533
00534 static int ffmpeg_exit(int ret)
00535 {
00536 int i;
00537
00538
00539 for(i=0;i<nb_output_files;i++) {
00540 AVFormatContext *s = output_files[i];
00541 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
00542 avio_close(s->pb);
00543 avformat_free_context(s);
00544 av_free(output_streams_for_file[i]);
00545 }
00546 for(i=0;i<nb_input_files;i++) {
00547 av_close_input_file(input_files[i].ctx);
00548 av_free(input_files_ts_scale[i]);
00549 }
00550
00551 av_free(intra_matrix);
00552 av_free(inter_matrix);
00553
00554 if (vstats_file)
00555 fclose(vstats_file);
00556 av_free(vstats_filename);
00557
00558 av_free(streamid_map);
00559 av_free(input_codecs);
00560 av_free(stream_maps);
00561 av_free(meta_data_maps);
00562
00563 av_freep(&input_streams);
00564 av_freep(&input_files);
00565
00566 av_free(video_codec_name);
00567 av_free(audio_codec_name);
00568 av_free(subtitle_codec_name);
00569 av_free(data_codec_name);
00570
00571 av_free(video_standard);
00572
00573 uninit_opts();
00574 av_free(audio_buf);
00575 av_free(audio_out);
00576 allocated_audio_buf_size= allocated_audio_out_size= 0;
00577 av_free(samples);
00578
00579 #if CONFIG_AVFILTER
00580 avfilter_uninit();
00581 #endif
00582
00583 if (received_sigterm) {
00584 fprintf(stderr,
00585 "Received signal %d: terminating.\n",
00586 (int) received_sigterm);
00587 exit (255);
00588 }
00589
00590 exit(ret);
00591 return ret;
00592 }
00593
00594
00595 static void *grow_array(void *array, int elem_size, int *size, int new_size)
00596 {
00597 if (new_size >= INT_MAX / elem_size) {
00598 fprintf(stderr, "Array too big.\n");
00599 ffmpeg_exit(1);
00600 }
00601 if (*size < new_size) {
00602 uint8_t *tmp = av_realloc(array, new_size*elem_size);
00603 if (!tmp) {
00604 fprintf(stderr, "Could not alloc buffer.\n");
00605 ffmpeg_exit(1);
00606 }
00607 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
00608 *size = new_size;
00609 return tmp;
00610 }
00611 return array;
00612 }
00613
00614 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
00615 {
00616 if(codec && codec->sample_fmts){
00617 const enum AVSampleFormat *p= codec->sample_fmts;
00618 for(; *p!=-1; p++){
00619 if(*p == st->codec->sample_fmt)
00620 break;
00621 }
00622 if (*p == -1) {
00623 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
00624 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
00625 av_log(NULL, AV_LOG_WARNING,
00626 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
00627 av_get_sample_fmt_name(st->codec->sample_fmt),
00628 codec->name,
00629 av_get_sample_fmt_name(codec->sample_fmts[0]));
00630 st->codec->sample_fmt = codec->sample_fmts[0];
00631 }
00632 }
00633 }
00634
00635 static void choose_sample_rate(AVStream *st, AVCodec *codec)
00636 {
00637 if(codec && codec->supported_samplerates){
00638 const int *p= codec->supported_samplerates;
00639 int best=0;
00640 int best_dist=INT_MAX;
00641 for(; *p; p++){
00642 int dist= abs(st->codec->sample_rate - *p);
00643 if(dist < best_dist){
00644 best_dist= dist;
00645 best= *p;
00646 }
00647 }
00648 if(best_dist){
00649 av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
00650 }
00651 st->codec->sample_rate= best;
00652 }
00653 }
00654
00655 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
00656 {
00657 if(codec && codec->pix_fmts){
00658 const enum PixelFormat *p= codec->pix_fmts;
00659 if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
00660 if(st->codec->codec_id==CODEC_ID_MJPEG){
00661 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
00662 }else if(st->codec->codec_id==CODEC_ID_LJPEG){
00663 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
00664 }
00665 }
00666 for(; *p!=-1; p++){
00667 if(*p == st->codec->pix_fmt)
00668 break;
00669 }
00670 if (*p == -1) {
00671 if(st->codec->pix_fmt != PIX_FMT_NONE)
00672 av_log(NULL, AV_LOG_WARNING,
00673 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
00674 av_pix_fmt_descriptors[st->codec->pix_fmt].name,
00675 codec->name,
00676 av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
00677 st->codec->pix_fmt = codec->pix_fmts[0];
00678 }
00679 }
00680 }
00681
00682 static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
00683 {
00684 int idx = oc->nb_streams - 1;
00685 AVOutputStream *ost;
00686
00687 output_streams_for_file[file_idx] =
00688 grow_array(output_streams_for_file[file_idx],
00689 sizeof(*output_streams_for_file[file_idx]),
00690 &nb_output_streams_for_file[file_idx],
00691 oc->nb_streams);
00692 ost = output_streams_for_file[file_idx][idx] =
00693 av_mallocz(sizeof(AVOutputStream));
00694 if (!ost) {
00695 fprintf(stderr, "Could not alloc output stream\n");
00696 ffmpeg_exit(1);
00697 }
00698 ost->file_index = file_idx;
00699 ost->index = idx;
00700
00701 ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
00702 return ost;
00703 }
00704
00705 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
00706 {
00707 int i, err;
00708 AVFormatContext *ic;
00709 int nopts = 0;
00710
00711 err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
00712 if (err < 0)
00713 return err;
00714
00715 s->nb_streams = 0;
00716 s->streams = av_mallocz(sizeof(AVStream *) * ic->nb_streams);
00717 for(i=0;i<ic->nb_streams;i++) {
00718 AVStream *st;
00719 AVCodec *codec;
00720
00721 s->nb_streams++;
00722
00723
00724 st = av_mallocz(sizeof(AVStream));
00725 memcpy(st, ic->streams[i], sizeof(AVStream));
00726 st->info = av_malloc(sizeof(*st->info));
00727 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
00728 st->codec = avcodec_alloc_context();
00729 if (!st->codec) {
00730 print_error(filename, AVERROR(ENOMEM));
00731 ffmpeg_exit(1);
00732 }
00733 avcodec_copy_context(st->codec, ic->streams[i]->codec);
00734 s->streams[i] = st;
00735
00736 codec = avcodec_find_encoder(st->codec->codec_id);
00737 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00738 if (audio_stream_copy) {
00739 st->stream_copy = 1;
00740 } else
00741 choose_sample_fmt(st, codec);
00742 } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00743 if (video_stream_copy) {
00744 st->stream_copy = 1;
00745 } else
00746 choose_pixel_fmt(st, codec);
00747 }
00748
00749 if(st->codec->flags & CODEC_FLAG_BITEXACT)
00750 nopts = 1;
00751
00752 new_output_stream(s, nb_output_files);
00753 }
00754
00755 if (!nopts)
00756 s->timestamp = av_gettime();
00757
00758 av_close_input_file(ic);
00759 return 0;
00760 }
00761
00762 static double
00763 get_sync_ipts(const AVOutputStream *ost)
00764 {
00765 const AVInputStream *ist = ost->sync_ist;
00766 return (double)(ist->pts - start_time)/AV_TIME_BASE;
00767 }
00768
00769 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
00770 int ret;
00771
00772 while(bsfc){
00773 AVPacket new_pkt= *pkt;
00774 int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
00775 &new_pkt.data, &new_pkt.size,
00776 pkt->data, pkt->size,
00777 pkt->flags & AV_PKT_FLAG_KEY);
00778 if(a>0){
00779 av_free_packet(pkt);
00780 new_pkt.destruct= av_destruct_packet;
00781 } else if(a<0){
00782 fprintf(stderr, "%s failed for stream %d, codec %s",
00783 bsfc->filter->name, pkt->stream_index,
00784 avctx->codec ? avctx->codec->name : "copy");
00785 print_error("", a);
00786 if (exit_on_error)
00787 ffmpeg_exit(1);
00788 }
00789 *pkt= new_pkt;
00790
00791 bsfc= bsfc->next;
00792 }
00793
00794 ret= av_interleaved_write_frame(s, pkt);
00795 if(ret < 0){
00796 print_error("av_interleaved_write_frame()", ret);
00797 ffmpeg_exit(1);
00798 }
00799 }
00800
00801 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
00802
00803 static void do_audio_out(AVFormatContext *s,
00804 AVOutputStream *ost,
00805 AVInputStream *ist,
00806 unsigned char *buf, int size)
00807 {
00808 uint8_t *buftmp;
00809 int64_t audio_out_size, audio_buf_size;
00810 int64_t allocated_for_size= size;
00811
00812 int size_out, frame_bytes, ret, resample_changed;
00813 AVCodecContext *enc= ost->st->codec;
00814 AVCodecContext *dec= ist->st->codec;
00815 int osize = av_get_bytes_per_sample(enc->sample_fmt);
00816 int isize = av_get_bytes_per_sample(dec->sample_fmt);
00817 const int coded_bps = av_get_bits_per_sample(enc->codec->id);
00818
00819 need_realloc:
00820 audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
00821 audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
00822 audio_buf_size= audio_buf_size*2 + 10000;
00823 audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
00824 audio_buf_size*= osize*enc->channels;
00825
00826 audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
00827 if(coded_bps > 8*osize)
00828 audio_out_size= audio_out_size * coded_bps / (8*osize);
00829 audio_out_size += FF_MIN_BUFFER_SIZE;
00830
00831 if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
00832 fprintf(stderr, "Buffer sizes too large\n");
00833 ffmpeg_exit(1);
00834 }
00835
00836 av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
00837 av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
00838 if (!audio_buf || !audio_out){
00839 fprintf(stderr, "Out of memory in do_audio_out\n");
00840 ffmpeg_exit(1);
00841 }
00842
00843 if (enc->channels != dec->channels)
00844 ost->audio_resample = 1;
00845
00846 resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
00847 ost->resample_channels != dec->channels ||
00848 ost->resample_sample_rate != dec->sample_rate;
00849
00850 if ((ost->audio_resample && !ost->resample) || resample_changed) {
00851 if (resample_changed) {
00852 av_log(NULL, AV_LOG_INFO, "Input stream #%d.%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
00853 ist->file_index, ist->st->index,
00854 ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
00855 dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
00856 ost->resample_sample_fmt = dec->sample_fmt;
00857 ost->resample_channels = dec->channels;
00858 ost->resample_sample_rate = dec->sample_rate;
00859 if (ost->resample)
00860 audio_resample_close(ost->resample);
00861 }
00862
00863 if (audio_sync_method <= 1 &&
00864 ost->resample_sample_fmt == enc->sample_fmt &&
00865 ost->resample_channels == enc->channels &&
00866 ost->resample_sample_rate == enc->sample_rate) {
00867 ost->resample = NULL;
00868 ost->audio_resample = 0;
00869 } else {
00870 if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
00871 fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
00872 ost->resample = av_audio_resample_init(enc->channels, dec->channels,
00873 enc->sample_rate, dec->sample_rate,
00874 enc->sample_fmt, dec->sample_fmt,
00875 16, 10, 0, 0.8);
00876 if (!ost->resample) {
00877 fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
00878 dec->channels, dec->sample_rate,
00879 enc->channels, enc->sample_rate);
00880 ffmpeg_exit(1);
00881 }
00882 }
00883 }
00884
00885 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
00886 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
00887 MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
00888 if (ost->reformat_ctx)
00889 av_audio_convert_free(ost->reformat_ctx);
00890 ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
00891 dec->sample_fmt, 1, NULL, 0);
00892 if (!ost->reformat_ctx) {
00893 fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
00894 av_get_sample_fmt_name(dec->sample_fmt),
00895 av_get_sample_fmt_name(enc->sample_fmt));
00896 ffmpeg_exit(1);
00897 }
00898 ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
00899 }
00900
00901 if(audio_sync_method){
00902 double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
00903 - av_fifo_size(ost->fifo)/(enc->channels * 2);
00904 double idelta= delta*dec->sample_rate / enc->sample_rate;
00905 int byte_delta= ((int)idelta)*2*dec->channels;
00906
00907
00908 if(fabs(delta) > 50){
00909 if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
00910 if(byte_delta < 0){
00911 byte_delta= FFMAX(byte_delta, -size);
00912 size += byte_delta;
00913 buf -= byte_delta;
00914 if(verbose > 2)
00915 fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
00916 if(!size)
00917 return;
00918 ist->is_start=0;
00919 }else{
00920 static uint8_t *input_tmp= NULL;
00921 input_tmp= av_realloc(input_tmp, byte_delta + size);
00922
00923 if(byte_delta > allocated_for_size - size){
00924 allocated_for_size= byte_delta + (int64_t)size;
00925 goto need_realloc;
00926 }
00927 ist->is_start=0;
00928
00929 memset(input_tmp, 0, byte_delta);
00930 memcpy(input_tmp + byte_delta, buf, size);
00931 buf= input_tmp;
00932 size += byte_delta;
00933 if(verbose > 2)
00934 fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
00935 }
00936 }else if(audio_sync_method>1){
00937 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
00938 av_assert0(ost->audio_resample);
00939 if(verbose > 2)
00940 fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
00941
00942 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
00943 }
00944 }
00945 }else
00946 ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
00947 - av_fifo_size(ost->fifo)/(enc->channels * 2);
00948
00949 if (ost->audio_resample) {
00950 buftmp = audio_buf;
00951 size_out = audio_resample(ost->resample,
00952 (short *)buftmp, (short *)buf,
00953 size / (dec->channels * isize));
00954 size_out = size_out * enc->channels * osize;
00955 } else {
00956 buftmp = buf;
00957 size_out = size;
00958 }
00959
00960 if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
00961 const void *ibuf[6]= {buftmp};
00962 void *obuf[6]= {audio_buf};
00963 int istride[6]= {isize};
00964 int ostride[6]= {osize};
00965 int len= size_out/istride[0];
00966 if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
00967 printf("av_audio_convert() failed\n");
00968 if (exit_on_error)
00969 ffmpeg_exit(1);
00970 return;
00971 }
00972 buftmp = audio_buf;
00973 size_out = len*osize;
00974 }
00975
00976
00977 if (enc->frame_size > 1) {
00978
00979 if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
00980 fprintf(stderr, "av_fifo_realloc2() failed\n");
00981 ffmpeg_exit(1);
00982 }
00983 av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
00984
00985 frame_bytes = enc->frame_size * osize * enc->channels;
00986
00987 while (av_fifo_size(ost->fifo) >= frame_bytes) {
00988 AVPacket pkt;
00989 av_init_packet(&pkt);
00990
00991 av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
00992
00993
00994
00995 ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
00996 (short *)audio_buf);
00997 if (ret < 0) {
00998 fprintf(stderr, "Audio encoding failed\n");
00999 ffmpeg_exit(1);
01000 }
01001 audio_size += ret;
01002 pkt.stream_index= ost->index;
01003 pkt.data= audio_out;
01004 pkt.size= ret;
01005 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01006 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01007 pkt.flags |= AV_PKT_FLAG_KEY;
01008 write_frame(s, &pkt, enc, ost->bitstream_filters);
01009
01010 ost->sync_opts += enc->frame_size;
01011 }
01012 } else {
01013 AVPacket pkt;
01014 av_init_packet(&pkt);
01015
01016 ost->sync_opts += size_out / (osize * enc->channels);
01017
01018
01019
01020 size_out /= osize;
01021 if (coded_bps)
01022 size_out = size_out*coded_bps/8;
01023
01024 if(size_out > audio_out_size){
01025 fprintf(stderr, "Internal error, buffer size too small\n");
01026 ffmpeg_exit(1);
01027 }
01028
01029
01030 ret = avcodec_encode_audio(enc, audio_out, size_out,
01031 (short *)buftmp);
01032 if (ret < 0) {
01033 fprintf(stderr, "Audio encoding failed\n");
01034 ffmpeg_exit(1);
01035 }
01036 audio_size += ret;
01037 pkt.stream_index= ost->index;
01038 pkt.data= audio_out;
01039 pkt.size= ret;
01040 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01041 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01042 pkt.flags |= AV_PKT_FLAG_KEY;
01043 write_frame(s, &pkt, enc, ost->bitstream_filters);
01044 }
01045 }
01046
01047 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
01048 {
01049 AVCodecContext *dec;
01050 AVPicture *picture2;
01051 AVPicture picture_tmp;
01052 uint8_t *buf = 0;
01053
01054 dec = ist->st->codec;
01055
01056
01057 if (do_deinterlace) {
01058 int size;
01059
01060
01061 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
01062 buf = av_malloc(size);
01063 if (!buf)
01064 return;
01065
01066 picture2 = &picture_tmp;
01067 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
01068
01069 if(avpicture_deinterlace(picture2, picture,
01070 dec->pix_fmt, dec->width, dec->height) < 0) {
01071
01072 fprintf(stderr, "Deinterlacing failed\n");
01073 av_free(buf);
01074 buf = NULL;
01075 picture2 = picture;
01076 }
01077 } else {
01078 picture2 = picture;
01079 }
01080
01081 if (picture != picture2)
01082 *picture = *picture2;
01083 *bufp = buf;
01084 }
01085
01086
01087 #define AV_DELAY_MAX 0.100
01088
01089 static void do_subtitle_out(AVFormatContext *s,
01090 AVOutputStream *ost,
01091 AVInputStream *ist,
01092 AVSubtitle *sub,
01093 int64_t pts)
01094 {
01095 static uint8_t *subtitle_out = NULL;
01096 int subtitle_out_max_size = 1024 * 1024;
01097 int subtitle_out_size, nb, i;
01098 AVCodecContext *enc;
01099 AVPacket pkt;
01100
01101 if (pts == AV_NOPTS_VALUE) {
01102 fprintf(stderr, "Subtitle packets must have a pts\n");
01103 if (exit_on_error)
01104 ffmpeg_exit(1);
01105 return;
01106 }
01107
01108 enc = ost->st->codec;
01109
01110 if (!subtitle_out) {
01111 subtitle_out = av_malloc(subtitle_out_max_size);
01112 }
01113
01114
01115
01116
01117 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
01118 nb = 2;
01119 else
01120 nb = 1;
01121
01122 for(i = 0; i < nb; i++) {
01123 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
01124
01125 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
01126 sub->end_display_time -= sub->start_display_time;
01127 sub->start_display_time = 0;
01128 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
01129 subtitle_out_max_size, sub);
01130 if (subtitle_out_size < 0) {
01131 fprintf(stderr, "Subtitle encoding failed\n");
01132 ffmpeg_exit(1);
01133 }
01134
01135 av_init_packet(&pkt);
01136 pkt.stream_index = ost->index;
01137 pkt.data = subtitle_out;
01138 pkt.size = subtitle_out_size;
01139 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
01140 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
01141
01142
01143 if (i == 0)
01144 pkt.pts += 90 * sub->start_display_time;
01145 else
01146 pkt.pts += 90 * sub->end_display_time;
01147 }
01148 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01149 }
01150 }
01151
01152 static int bit_buffer_size= 1024*256;
01153 static uint8_t *bit_buffer= NULL;
01154
01155 static void do_video_out(AVFormatContext *s,
01156 AVOutputStream *ost,
01157 AVInputStream *ist,
01158 AVFrame *in_picture,
01159 int *frame_size)
01160 {
01161 int nb_frames, i, ret, av_unused resample_changed;
01162 AVFrame *final_picture, *formatted_picture;
01163 AVCodecContext *enc, *dec;
01164 double sync_ipts;
01165
01166 enc = ost->st->codec;
01167 dec = ist->st->codec;
01168
01169 sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
01170
01171
01172 nb_frames = 1;
01173
01174 *frame_size = 0;
01175
01176 if(video_sync_method){
01177 double vdelta = sync_ipts - ost->sync_opts;
01178
01179 if (vdelta < -1.1)
01180 nb_frames = 0;
01181 else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
01182 if(vdelta<=-0.6){
01183 nb_frames=0;
01184 }else if(vdelta>0.6)
01185 ost->sync_opts= lrintf(sync_ipts);
01186 }else if (vdelta > 1.1)
01187 nb_frames = lrintf(vdelta);
01188
01189 if (nb_frames == 0){
01190 ++nb_frames_drop;
01191 if (verbose>2)
01192 fprintf(stderr, "*** drop!\n");
01193 }else if (nb_frames > 1) {
01194 nb_frames_dup += nb_frames - 1;
01195 if (verbose>2)
01196 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
01197 }
01198 }else
01199 ost->sync_opts= lrintf(sync_ipts);
01200
01201 nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
01202 if (nb_frames <= 0)
01203 return;
01204
01205 formatted_picture = in_picture;
01206 final_picture = formatted_picture;
01207
01208 #if !CONFIG_AVFILTER
01209 resample_changed = ost->resample_width != dec->width ||
01210 ost->resample_height != dec->height ||
01211 ost->resample_pix_fmt != dec->pix_fmt;
01212
01213 if (resample_changed) {
01214 av_log(NULL, AV_LOG_INFO,
01215 "Input stream #%d.%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
01216 ist->file_index, ist->st->index,
01217 ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
01218 dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt));
01219 ost->resample_width = dec->width;
01220 ost->resample_height = dec->height;
01221 ost->resample_pix_fmt = dec->pix_fmt;
01222 }
01223
01224 ost->video_resample = dec->width != enc->width ||
01225 dec->height != enc->height ||
01226 dec->pix_fmt != enc->pix_fmt;
01227
01228 if (ost->video_resample) {
01229 final_picture = &ost->resample_frame;
01230 if (!ost->img_resample_ctx || resample_changed) {
01231
01232 if (!ost->resample_frame.data[0]) {
01233 avcodec_get_frame_defaults(&ost->resample_frame);
01234 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
01235 enc->width, enc->height)) {
01236 fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
01237 ffmpeg_exit(1);
01238 }
01239 }
01240
01241 sws_freeContext(ost->img_resample_ctx);
01242 ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
01243 enc->width, enc->height, enc->pix_fmt,
01244 ost->sws_flags, NULL, NULL, NULL);
01245 if (ost->img_resample_ctx == NULL) {
01246 fprintf(stderr, "Cannot get resampling context\n");
01247 ffmpeg_exit(1);
01248 }
01249 }
01250 sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
01251 0, ost->resample_height, final_picture->data, final_picture->linesize);
01252 }
01253 #endif
01254
01255
01256 for(i=0;i<nb_frames;i++) {
01257 AVPacket pkt;
01258 av_init_packet(&pkt);
01259 pkt.stream_index= ost->index;
01260
01261 if (s->oformat->flags & AVFMT_RAWPICTURE) {
01262
01263
01264
01265 AVFrame* old_frame = enc->coded_frame;
01266 enc->coded_frame = dec->coded_frame;
01267 pkt.data= (uint8_t *)final_picture;
01268 pkt.size= sizeof(AVPicture);
01269 pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
01270 pkt.flags |= AV_PKT_FLAG_KEY;
01271
01272 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01273 enc->coded_frame = old_frame;
01274 } else {
01275 AVFrame big_picture;
01276
01277 big_picture= *final_picture;
01278
01279
01280 big_picture.interlaced_frame = in_picture->interlaced_frame;
01281 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
01282 if(top_field_first == -1)
01283 big_picture.top_field_first = in_picture->top_field_first;
01284 else
01285 big_picture.top_field_first = top_field_first;
01286 }
01287
01288
01289
01290 big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
01291 if(!me_threshold)
01292 big_picture.pict_type = 0;
01293
01294 big_picture.pts= ost->sync_opts;
01295
01296
01297 if (ost->forced_kf_index < ost->forced_kf_count &&
01298 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
01299 big_picture.pict_type = AV_PICTURE_TYPE_I;
01300 ost->forced_kf_index++;
01301 }
01302 ret = avcodec_encode_video(enc,
01303 bit_buffer, bit_buffer_size,
01304 &big_picture);
01305 if (ret < 0) {
01306 fprintf(stderr, "Video encoding failed\n");
01307 ffmpeg_exit(1);
01308 }
01309
01310 if(ret>0){
01311 pkt.data= bit_buffer;
01312 pkt.size= ret;
01313 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
01314 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01315
01316
01317
01318
01319 if(enc->coded_frame->key_frame)
01320 pkt.flags |= AV_PKT_FLAG_KEY;
01321 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01322 *frame_size = ret;
01323 video_size += ret;
01324
01325
01326
01327 if (ost->logfile && enc->stats_out) {
01328 fprintf(ost->logfile, "%s", enc->stats_out);
01329 }
01330 }
01331 }
01332 ost->sync_opts++;
01333 ost->frame_number++;
01334 }
01335 }
01336
01337 static double psnr(double d){
01338 return -10.0*log(d)/log(10.0);
01339 }
01340
01341 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
01342 int frame_size)
01343 {
01344 AVCodecContext *enc;
01345 int frame_number;
01346 double ti1, bitrate, avg_bitrate;
01347
01348
01349 if (!vstats_file) {
01350 vstats_file = fopen(vstats_filename, "w");
01351 if (!vstats_file) {
01352 perror("fopen");
01353 ffmpeg_exit(1);
01354 }
01355 }
01356
01357 enc = ost->st->codec;
01358 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01359 frame_number = ost->frame_number;
01360 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01361 if (enc->flags&CODEC_FLAG_PSNR)
01362 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
01363
01364 fprintf(vstats_file,"f_size= %6d ", frame_size);
01365
01366 ti1 = ost->sync_opts * av_q2d(enc->time_base);
01367 if (ti1 < 0.01)
01368 ti1 = 0.01;
01369
01370 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
01371 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
01372 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
01373 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
01374 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
01375 }
01376 }
01377
01378 static void print_report(AVFormatContext **output_files,
01379 AVOutputStream **ost_table, int nb_ostreams,
01380 int is_last_report)
01381 {
01382 char buf[1024];
01383 AVOutputStream *ost;
01384 AVFormatContext *oc;
01385 int64_t total_size;
01386 AVCodecContext *enc;
01387 int frame_number, vid, i;
01388 double bitrate;
01389 int64_t pts = INT64_MAX;
01390 static int64_t last_time = -1;
01391 static int qp_histogram[52];
01392
01393 if (!is_last_report) {
01394 int64_t cur_time;
01395
01396 cur_time = av_gettime();
01397 if (last_time == -1) {
01398 last_time = cur_time;
01399 return;
01400 }
01401 if ((cur_time - last_time) < 500000)
01402 return;
01403 last_time = cur_time;
01404 }
01405
01406
01407 oc = output_files[0];
01408
01409 total_size = avio_size(oc->pb);
01410 if(total_size<0)
01411 total_size= avio_tell(oc->pb);
01412
01413 buf[0] = '\0';
01414 vid = 0;
01415 for(i=0;i<nb_ostreams;i++) {
01416 float q = -1;
01417 ost = ost_table[i];
01418 enc = ost->st->codec;
01419 if (!ost->st->stream_copy && enc->coded_frame)
01420 q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
01421 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01422 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
01423 }
01424 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01425 float t = (av_gettime()-timer_start) / 1000000.0;
01426
01427 frame_number = ost->frame_number;
01428 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
01429 frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
01430 if(is_last_report)
01431 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
01432 if(qp_hist){
01433 int j;
01434 int qp = lrintf(q);
01435 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
01436 qp_histogram[qp]++;
01437 for(j=0; j<32; j++)
01438 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
01439 }
01440 if (enc->flags&CODEC_FLAG_PSNR){
01441 int j;
01442 double error, error_sum=0;
01443 double scale, scale_sum=0;
01444 char type[3]= {'Y','U','V'};
01445 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
01446 for(j=0; j<3; j++){
01447 if(is_last_report){
01448 error= enc->error[j];
01449 scale= enc->width*enc->height*255.0*255.0*frame_number;
01450 }else{
01451 error= enc->coded_frame->error[j];
01452 scale= enc->width*enc->height*255.0*255.0;
01453 }
01454 if(j) scale/=4;
01455 error_sum += error;
01456 scale_sum += scale;
01457 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
01458 }
01459 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
01460 }
01461 vid = 1;
01462 }
01463
01464 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
01465 ost->st->time_base, AV_TIME_BASE_Q));
01466 }
01467
01468 if (verbose > 0 || is_last_report) {
01469 int hours, mins, secs, us;
01470 secs = pts / AV_TIME_BASE;
01471 us = pts % AV_TIME_BASE;
01472 mins = secs / 60;
01473 secs %= 60;
01474 hours = mins / 60;
01475 mins %= 60;
01476
01477 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
01478
01479 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01480 "size=%8.0fkB time=", total_size / 1024.0);
01481 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01482 "%02d:%02d:%02d.%02d ", hours, mins, secs,
01483 (100 * us) / AV_TIME_BASE);
01484 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01485 "bitrate=%6.1fkbits/s", bitrate);
01486
01487 if (nb_frames_dup || nb_frames_drop)
01488 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
01489 nb_frames_dup, nb_frames_drop);
01490
01491 if (verbose >= 0)
01492 fprintf(stderr, "%s \r", buf);
01493
01494 fflush(stderr);
01495 }
01496
01497 if (is_last_report && verbose >= 0){
01498 int64_t raw= audio_size + video_size + extra_size;
01499 fprintf(stderr, "\n");
01500 fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
01501 video_size/1024.0,
01502 audio_size/1024.0,
01503 extra_size/1024.0,
01504 100.0*(total_size - raw)/raw
01505 );
01506 }
01507 }
01508
01509 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
01510 {
01511 int fill_char = 0x00;
01512 if (sample_fmt == AV_SAMPLE_FMT_U8)
01513 fill_char = 0x80;
01514 memset(buf, fill_char, size);
01515 }
01516
01517
01518 static int output_packet(AVInputStream *ist, int ist_index,
01519 AVOutputStream **ost_table, int nb_ostreams,
01520 const AVPacket *pkt)
01521 {
01522 AVFormatContext *os;
01523 AVOutputStream *ost;
01524 int ret, i;
01525 int got_output;
01526 AVFrame picture;
01527 void *buffer_to_free = NULL;
01528 static unsigned int samples_size= 0;
01529 AVSubtitle subtitle, *subtitle_to_free;
01530 int64_t pkt_pts = AV_NOPTS_VALUE;
01531 #if CONFIG_AVFILTER
01532 int frame_available;
01533 #endif
01534
01535 AVPacket avpkt;
01536 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
01537
01538 if(ist->next_pts == AV_NOPTS_VALUE)
01539 ist->next_pts= ist->pts;
01540
01541 if (pkt == NULL) {
01542
01543 av_init_packet(&avpkt);
01544 avpkt.data = NULL;
01545 avpkt.size = 0;
01546 goto handle_eof;
01547 } else {
01548 avpkt = *pkt;
01549 }
01550
01551 if(pkt->dts != AV_NOPTS_VALUE)
01552 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
01553 if(pkt->pts != AV_NOPTS_VALUE)
01554 pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
01555
01556
01557 while (avpkt.size > 0 || (!pkt && got_output)) {
01558 uint8_t *data_buf, *decoded_data_buf;
01559 int data_size, decoded_data_size;
01560 handle_eof:
01561 ist->pts= ist->next_pts;
01562
01563 if(avpkt.size && avpkt.size != pkt->size &&
01564 ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
01565 fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
01566 ist->showed_multi_packet_warning=1;
01567 }
01568
01569
01570 decoded_data_buf = NULL;
01571 decoded_data_size= 0;
01572 data_buf = avpkt.data;
01573 data_size = avpkt.size;
01574 subtitle_to_free = NULL;
01575 if (ist->decoding_needed) {
01576 switch(ist->st->codec->codec_type) {
01577 case AVMEDIA_TYPE_AUDIO:{
01578 if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
01579 samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
01580 av_free(samples);
01581 samples= av_malloc(samples_size);
01582 }
01583 decoded_data_size= samples_size;
01584
01585
01586 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
01587 &avpkt);
01588 if (ret < 0)
01589 goto fail_decode;
01590 avpkt.data += ret;
01591 avpkt.size -= ret;
01592 data_size = ret;
01593 got_output = decoded_data_size > 0;
01594
01595
01596 if (!got_output) {
01597
01598 continue;
01599 }
01600 decoded_data_buf = (uint8_t *)samples;
01601 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
01602 (ist->st->codec->sample_rate * ist->st->codec->channels);
01603 break;}
01604 case AVMEDIA_TYPE_VIDEO:
01605 decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
01606
01607 avcodec_get_frame_defaults(&picture);
01608 avpkt.pts = pkt_pts;
01609 avpkt.dts = ist->pts;
01610 pkt_pts = AV_NOPTS_VALUE;
01611
01612 ret = avcodec_decode_video2(ist->st->codec,
01613 &picture, &got_output, &avpkt);
01614 ist->st->quality= picture.quality;
01615 if (ret < 0)
01616 goto fail_decode;
01617 if (!got_output) {
01618
01619 goto discard_packet;
01620 }
01621 ist->next_pts = ist->pts = picture.best_effort_timestamp;
01622 if (ist->st->codec->time_base.num != 0) {
01623 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01624 ist->next_pts += ((int64_t)AV_TIME_BASE *
01625 ist->st->codec->time_base.num * ticks) /
01626 ist->st->codec->time_base.den;
01627 }
01628 avpkt.size = 0;
01629 buffer_to_free = NULL;
01630 pre_process_video_frame(ist, (AVPicture *)&picture, &buffer_to_free);
01631 break;
01632 case AVMEDIA_TYPE_SUBTITLE:
01633 ret = avcodec_decode_subtitle2(ist->st->codec,
01634 &subtitle, &got_output, &avpkt);
01635 if (ret < 0)
01636 goto fail_decode;
01637 if (!got_output) {
01638 goto discard_packet;
01639 }
01640 subtitle_to_free = &subtitle;
01641 avpkt.size = 0;
01642 break;
01643 default:
01644 goto fail_decode;
01645 }
01646 } else {
01647 switch(ist->st->codec->codec_type) {
01648 case AVMEDIA_TYPE_AUDIO:
01649 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
01650 ist->st->codec->sample_rate;
01651 break;
01652 case AVMEDIA_TYPE_VIDEO:
01653 if (ist->st->codec->time_base.num != 0) {
01654 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01655 ist->next_pts += ((int64_t)AV_TIME_BASE *
01656 ist->st->codec->time_base.num * ticks) /
01657 ist->st->codec->time_base.den;
01658 }
01659 break;
01660 }
01661 ret = avpkt.size;
01662 avpkt.size = 0;
01663 }
01664
01665 #if CONFIG_AVFILTER
01666 if(ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
01667 if (start_time == 0 || ist->pts >= start_time) {
01668 for(i=0;i<nb_ostreams;i++) {
01669 ost = ost_table[i];
01670 if (ost->input_video_filter && ost->source_index == ist_index) {
01671 if (!picture.sample_aspect_ratio.num)
01672 picture.sample_aspect_ratio = ist->st->sample_aspect_ratio;
01673 picture.pts = ist->pts;
01674
01675 av_vsrc_buffer_add_frame(ost->input_video_filter, &picture, AV_VSRC_BUF_FLAG_OVERWRITE);
01676 }
01677 }
01678 }
01679 #endif
01680
01681
01682 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
01683 if (audio_volume != 256) {
01684 short *volp;
01685 volp = samples;
01686 for(i=0;i<(decoded_data_size / sizeof(short));i++) {
01687 int v = ((*volp) * audio_volume + 128) >> 8;
01688 if (v < -32768) v = -32768;
01689 if (v > 32767) v = 32767;
01690 *volp++ = v;
01691 }
01692 }
01693 }
01694
01695
01696 if (rate_emu) {
01697 int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
01698 int64_t now = av_gettime() - ist->start;
01699 if (pts > now)
01700 usleep(pts - now);
01701 }
01702
01703
01704 if (start_time == 0 || ist->pts >= start_time)
01705 for(i=0;i<nb_ostreams;i++) {
01706 int frame_size;
01707
01708 ost = ost_table[i];
01709 if (ost->source_index == ist_index) {
01710 #if CONFIG_AVFILTER
01711 frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
01712 !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01713 while (frame_available) {
01714 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter) {
01715 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
01716 if (av_vsink_buffer_get_video_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
01717 goto cont;
01718 if (ost->picref) {
01719 avfilter_fill_frame_from_video_buffer_ref(&picture, ost->picref);
01720 ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
01721 }
01722 }
01723 #endif
01724 os = output_files[ost->file_index];
01725
01726
01727
01728
01729 if (ost->encoding_needed) {
01730 av_assert0(ist->decoding_needed);
01731 switch(ost->st->codec->codec_type) {
01732 case AVMEDIA_TYPE_AUDIO:
01733 do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
01734 break;
01735 case AVMEDIA_TYPE_VIDEO:
01736 #if CONFIG_AVFILTER
01737 if (ost->picref->video && !ost->frame_aspect_ratio)
01738 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
01739 #endif
01740 do_video_out(os, ost, ist, &picture, &frame_size);
01741 if (vstats_filename && frame_size)
01742 do_video_stats(os, ost, frame_size);
01743 break;
01744 case AVMEDIA_TYPE_SUBTITLE:
01745 do_subtitle_out(os, ost, ist, &subtitle,
01746 pkt->pts);
01747 break;
01748 default:
01749 abort();
01750 }
01751 } else {
01752 AVFrame avframe;
01753 AVPicture pict;
01754 AVPacket opkt;
01755 int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
01756
01757 av_init_packet(&opkt);
01758
01759 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
01760 #if !CONFIG_AVFILTER
01761 continue;
01762 #else
01763 goto cont;
01764 #endif
01765
01766
01767
01768
01769 avcodec_get_frame_defaults(&avframe);
01770 ost->st->codec->coded_frame= &avframe;
01771 avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
01772
01773 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01774 audio_size += data_size;
01775 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01776 video_size += data_size;
01777 ost->sync_opts++;
01778 }
01779
01780 opkt.stream_index= ost->index;
01781 if(pkt->pts != AV_NOPTS_VALUE)
01782 opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
01783 else
01784 opkt.pts= AV_NOPTS_VALUE;
01785
01786 if (pkt->dts == AV_NOPTS_VALUE)
01787 opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
01788 else
01789 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
01790 opkt.dts -= ost_tb_start_time;
01791
01792 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
01793 opkt.flags= pkt->flags;
01794
01795
01796 if( ost->st->codec->codec_id != CODEC_ID_H264
01797 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
01798 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
01799 ) {
01800 if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
01801 opkt.destruct= av_destruct_packet;
01802 } else {
01803 opkt.data = data_buf;
01804 opkt.size = data_size;
01805 }
01806
01807 if (os->oformat->flags & AVFMT_RAWPICTURE) {
01808
01809 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
01810 opkt.data = (uint8_t *)&pict;
01811 opkt.size = sizeof(AVPicture);
01812 opkt.flags |= AV_PKT_FLAG_KEY;
01813 }
01814 write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
01815 ost->st->codec->frame_number++;
01816 ost->frame_number++;
01817 av_free_packet(&opkt);
01818 }
01819 #if CONFIG_AVFILTER
01820 cont:
01821 frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
01822 ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01823 avfilter_unref_buffer(ost->picref);
01824 }
01825 #endif
01826 }
01827 }
01828
01829 av_free(buffer_to_free);
01830
01831 if (subtitle_to_free) {
01832 avsubtitle_free(subtitle_to_free);
01833 subtitle_to_free = NULL;
01834 }
01835 }
01836 discard_packet:
01837 if (pkt == NULL) {
01838
01839
01840 for(i=0;i<nb_ostreams;i++) {
01841 ost = ost_table[i];
01842 if (ost->source_index == ist_index) {
01843 AVCodecContext *enc= ost->st->codec;
01844 os = output_files[ost->file_index];
01845
01846 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
01847 continue;
01848 if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
01849 continue;
01850
01851 if (ost->encoding_needed) {
01852 for(;;) {
01853 AVPacket pkt;
01854 int fifo_bytes;
01855 av_init_packet(&pkt);
01856 pkt.stream_index= ost->index;
01857
01858 switch(ost->st->codec->codec_type) {
01859 case AVMEDIA_TYPE_AUDIO:
01860 fifo_bytes = av_fifo_size(ost->fifo);
01861 ret = 0;
01862
01863 if (fifo_bytes > 0) {
01864 int osize = av_get_bytes_per_sample(enc->sample_fmt);
01865 int fs_tmp = enc->frame_size;
01866
01867 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
01868 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
01869 enc->frame_size = fifo_bytes / (osize * enc->channels);
01870 } else {
01871 int frame_bytes = enc->frame_size*osize*enc->channels;
01872 if (allocated_audio_buf_size < frame_bytes)
01873 ffmpeg_exit(1);
01874 generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
01875 }
01876
01877 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
01878 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
01879 ost->st->time_base.num, enc->sample_rate);
01880 enc->frame_size = fs_tmp;
01881 }
01882 if(ret <= 0) {
01883 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
01884 }
01885 if (ret < 0) {
01886 fprintf(stderr, "Audio encoding failed\n");
01887 ffmpeg_exit(1);
01888 }
01889 audio_size += ret;
01890 pkt.flags |= AV_PKT_FLAG_KEY;
01891 break;
01892 case AVMEDIA_TYPE_VIDEO:
01893 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
01894 if (ret < 0) {
01895 fprintf(stderr, "Video encoding failed\n");
01896 ffmpeg_exit(1);
01897 }
01898 video_size += ret;
01899 if(enc->coded_frame && enc->coded_frame->key_frame)
01900 pkt.flags |= AV_PKT_FLAG_KEY;
01901 if (ost->logfile && enc->stats_out) {
01902 fprintf(ost->logfile, "%s", enc->stats_out);
01903 }
01904 break;
01905 default:
01906 ret=-1;
01907 }
01908
01909 if(ret<=0)
01910 break;
01911 pkt.data= bit_buffer;
01912 pkt.size= ret;
01913 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01914 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01915 write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
01916 }
01917 }
01918 }
01919 }
01920 }
01921
01922 return 0;
01923 fail_decode:
01924 return -1;
01925 }
01926
01927 static void print_sdp(AVFormatContext **avc, int n)
01928 {
01929 char sdp[2048];
01930
01931 av_sdp_create(avc, n, sdp, sizeof(sdp));
01932 printf("SDP:\n%s\n", sdp);
01933 fflush(stdout);
01934 }
01935
01936 static int copy_chapters(int infile, int outfile)
01937 {
01938 AVFormatContext *is = input_files[infile].ctx;
01939 AVFormatContext *os = output_files[outfile];
01940 int i;
01941
01942 for (i = 0; i < is->nb_chapters; i++) {
01943 AVChapter *in_ch = is->chapters[i], *out_ch;
01944 int64_t ts_off = av_rescale_q(start_time - input_files_ts_offset[infile],
01945 AV_TIME_BASE_Q, in_ch->time_base);
01946 int64_t rt = (recording_time == INT64_MAX) ? INT64_MAX :
01947 av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
01948
01949
01950 if (in_ch->end < ts_off)
01951 continue;
01952 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
01953 break;
01954
01955 out_ch = av_mallocz(sizeof(AVChapter));
01956 if (!out_ch)
01957 return AVERROR(ENOMEM);
01958
01959 out_ch->id = in_ch->id;
01960 out_ch->time_base = in_ch->time_base;
01961 out_ch->start = FFMAX(0, in_ch->start - ts_off);
01962 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
01963
01964 if (metadata_chapters_autocopy)
01965 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
01966
01967 os->nb_chapters++;
01968 os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
01969 if (!os->chapters)
01970 return AVERROR(ENOMEM);
01971 os->chapters[os->nb_chapters - 1] = out_ch;
01972 }
01973 return 0;
01974 }
01975
01976 static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
01977 AVCodecContext *avctx)
01978 {
01979 char *p;
01980 int n = 1, i;
01981 int64_t t;
01982
01983 for (p = kf; *p; p++)
01984 if (*p == ',')
01985 n++;
01986 ost->forced_kf_count = n;
01987 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
01988 if (!ost->forced_kf_pts) {
01989 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
01990 ffmpeg_exit(1);
01991 }
01992 for (i = 0; i < n; i++) {
01993 p = i ? strchr(p, ',') + 1 : kf;
01994 t = parse_time_or_die("force_key_frames", p, 1);
01995 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
01996 }
01997 }
01998
01999
02000
02001
02002 static int transcode(AVFormatContext **output_files,
02003 int nb_output_files,
02004 AVInputFile *input_files,
02005 int nb_input_files,
02006 AVStreamMap *stream_maps, int nb_stream_maps)
02007 {
02008 int ret = 0, i, j, k, n, nb_ostreams = 0, step;
02009
02010 AVFormatContext *is, *os;
02011 AVCodecContext *codec, *icodec;
02012 AVOutputStream *ost, **ost_table = NULL;
02013 AVInputStream *ist;
02014 char error[1024];
02015 int key;
02016 int want_sdp = 1;
02017 uint8_t no_packet[MAX_FILES]={0};
02018 int no_packet_count=0;
02019 int nb_frame_threshold[AVMEDIA_TYPE_NB]={0};
02020 int nb_streams[AVMEDIA_TYPE_NB]={0};
02021
02022 if (rate_emu)
02023 for (i = 0; i < nb_input_streams; i++)
02024 input_streams[i].start = av_gettime();
02025
02026
02027 nb_ostreams = 0;
02028 for(i=0;i<nb_output_files;i++) {
02029 os = output_files[i];
02030 if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
02031 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02032 fprintf(stderr, "Output file #%d does not contain any stream\n", i);
02033 ret = AVERROR(EINVAL);
02034 goto fail;
02035 }
02036 nb_ostreams += os->nb_streams;
02037 }
02038 if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
02039 fprintf(stderr, "Number of stream maps must match number of output streams\n");
02040 ret = AVERROR(EINVAL);
02041 goto fail;
02042 }
02043
02044
02045 for(i=0;i<nb_stream_maps;i++) {
02046 int fi = stream_maps[i].file_index;
02047 int si = stream_maps[i].stream_index;
02048
02049 if (fi < 0 || fi > nb_input_files - 1 ||
02050 si < 0 || si > input_files[fi].nb_streams - 1) {
02051 fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
02052 ret = AVERROR(EINVAL);
02053 goto fail;
02054 }
02055 fi = stream_maps[i].sync_file_index;
02056 si = stream_maps[i].sync_stream_index;
02057 if (fi < 0 || fi > nb_input_files - 1 ||
02058 si < 0 || si > input_files[fi].nb_streams - 1) {
02059 fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
02060 ret = AVERROR(EINVAL);
02061 goto fail;
02062 }
02063 }
02064
02065 ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
02066 if (!ost_table)
02067 goto fail;
02068
02069 for(k=0;k<nb_output_files;k++) {
02070 os = output_files[k];
02071 for(i=0;i<os->nb_streams;i++,n++) {
02072 nb_streams[os->streams[i]->codec->codec_type]++;
02073 }
02074 }
02075 for(step=1<<30; step; step>>=1){
02076 int found_streams[AVMEDIA_TYPE_NB]={0};
02077 for(j=0; j<AVMEDIA_TYPE_NB; j++)
02078 nb_frame_threshold[j] += step;
02079
02080 for(j=0; j<nb_input_streams; j++) {
02081 int skip=0;
02082 ist = &input_streams[j];
02083 if(opt_programid){
02084 int pi,si;
02085 AVFormatContext *f= input_files[ ist->file_index ].ctx;
02086 skip=1;
02087 for(pi=0; pi<f->nb_programs; pi++){
02088 AVProgram *p= f->programs[pi];
02089 if(p->id == opt_programid)
02090 for(si=0; si<p->nb_stream_indexes; si++){
02091 if(f->streams[ p->stream_index[si] ] == ist->st)
02092 skip=0;
02093 }
02094 }
02095 }
02096 if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip
02097 && nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames){
02098 found_streams[ist->st->codec->codec_type]++;
02099 }
02100 }
02101 for(j=0; j<AVMEDIA_TYPE_NB; j++)
02102 if(found_streams[j] < nb_streams[j])
02103 nb_frame_threshold[j] -= step;
02104 }
02105 n = 0;
02106 for(k=0;k<nb_output_files;k++) {
02107 os = output_files[k];
02108 for(i=0;i<os->nb_streams;i++,n++) {
02109 int found;
02110 ost = ost_table[n] = output_streams_for_file[k][i];
02111 ost->st = os->streams[i];
02112 if (nb_stream_maps > 0) {
02113 ost->source_index = input_files[stream_maps[n].file_index].ist_index +
02114 stream_maps[n].stream_index;
02115
02116
02117 if (input_streams[ost->source_index].st->codec->codec_type != ost->st->codec->codec_type) {
02118 int i= ost->file_index;
02119 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02120 fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
02121 stream_maps[n].file_index, stream_maps[n].stream_index,
02122 ost->file_index, ost->index);
02123 ffmpeg_exit(1);
02124 }
02125
02126 } else {
02127
02128 found = 0;
02129 for (j = 0; j < nb_input_streams; j++) {
02130 int skip=0;
02131 ist = &input_streams[j];
02132 if(opt_programid){
02133 int pi,si;
02134 AVFormatContext *f = input_files[ist->file_index].ctx;
02135 skip=1;
02136 for(pi=0; pi<f->nb_programs; pi++){
02137 AVProgram *p= f->programs[pi];
02138 if(p->id == opt_programid)
02139 for(si=0; si<p->nb_stream_indexes; si++){
02140 if(f->streams[ p->stream_index[si] ] == ist->st)
02141 skip=0;
02142 }
02143 }
02144 }
02145 if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
02146 ist->st->codec->codec_type == ost->st->codec->codec_type &&
02147 nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames) {
02148 ost->source_index = j;
02149 found = 1;
02150 break;
02151 }
02152 }
02153
02154 if (!found) {
02155 if(! opt_programid) {
02156
02157 for (j = 0; j < nb_input_streams; j++) {
02158 ist = &input_streams[j];
02159 if ( ist->st->codec->codec_type == ost->st->codec->codec_type
02160 && ist->st->discard != AVDISCARD_ALL) {
02161 ost->source_index = j;
02162 found = 1;
02163 }
02164 }
02165 }
02166 if (!found) {
02167 int i= ost->file_index;
02168 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02169 fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
02170 ost->file_index, ost->index);
02171 ffmpeg_exit(1);
02172 }
02173 }
02174 }
02175 ist = &input_streams[ost->source_index];
02176 ist->discard = 0;
02177 ost->sync_ist = (nb_stream_maps > 0) ?
02178 &input_streams[input_files[stream_maps[n].sync_file_index].ist_index +
02179 stream_maps[n].sync_stream_index] : ist;
02180 }
02181 }
02182
02183
02184 for(i=0;i<nb_ostreams;i++) {
02185 ost = ost_table[i];
02186 os = output_files[ost->file_index];
02187 ist = &input_streams[ost->source_index];
02188
02189 codec = ost->st->codec;
02190 icodec = ist->st->codec;
02191
02192 if (metadata_streams_autocopy)
02193 av_dict_copy(&ost->st->metadata, ist->st->metadata,
02194 AV_DICT_DONT_OVERWRITE);
02195
02196 ost->st->disposition = ist->st->disposition;
02197 codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
02198 codec->chroma_sample_location = icodec->chroma_sample_location;
02199
02200 if (ost->st->stream_copy) {
02201 uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
02202
02203 if (extra_size > INT_MAX)
02204 goto fail;
02205
02206
02207 codec->codec_id = icodec->codec_id;
02208 codec->codec_type = icodec->codec_type;
02209
02210 if(!codec->codec_tag){
02211 if( !os->oformat->codec_tag
02212 || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
02213 || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
02214 codec->codec_tag = icodec->codec_tag;
02215 }
02216
02217 codec->bit_rate = icodec->bit_rate;
02218 codec->rc_max_rate = icodec->rc_max_rate;
02219 codec->rc_buffer_size = icodec->rc_buffer_size;
02220 codec->extradata= av_mallocz(extra_size);
02221 if (!codec->extradata)
02222 goto fail;
02223 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
02224 codec->extradata_size= icodec->extradata_size;
02225 if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
02226 codec->time_base = icodec->time_base;
02227 codec->time_base.num *= icodec->ticks_per_frame;
02228 av_reduce(&codec->time_base.num, &codec->time_base.den,
02229 codec->time_base.num, codec->time_base.den, INT_MAX);
02230 }else
02231 codec->time_base = ist->st->time_base;
02232 switch(codec->codec_type) {
02233 case AVMEDIA_TYPE_AUDIO:
02234 if(audio_volume != 256) {
02235 fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
02236 ffmpeg_exit(1);
02237 }
02238 codec->channel_layout = icodec->channel_layout;
02239 codec->sample_rate = icodec->sample_rate;
02240 codec->channels = icodec->channels;
02241 codec->frame_size = icodec->frame_size;
02242 codec->audio_service_type = icodec->audio_service_type;
02243 codec->block_align= icodec->block_align;
02244 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
02245 codec->block_align= 0;
02246 if(codec->codec_id == CODEC_ID_AC3)
02247 codec->block_align= 0;
02248 break;
02249 case AVMEDIA_TYPE_VIDEO:
02250 codec->pix_fmt = icodec->pix_fmt;
02251 codec->width = icodec->width;
02252 codec->height = icodec->height;
02253 codec->has_b_frames = icodec->has_b_frames;
02254 if (!codec->sample_aspect_ratio.num) {
02255 codec->sample_aspect_ratio =
02256 ost->st->sample_aspect_ratio =
02257 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
02258 ist->st->codec->sample_aspect_ratio.num ?
02259 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
02260 }
02261 break;
02262 case AVMEDIA_TYPE_SUBTITLE:
02263 codec->width = icodec->width;
02264 codec->height = icodec->height;
02265 break;
02266 case AVMEDIA_TYPE_DATA:
02267 break;
02268 default:
02269 abort();
02270 }
02271 } else {
02272 if (!ost->enc)
02273 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
02274 switch(codec->codec_type) {
02275 case AVMEDIA_TYPE_AUDIO:
02276 ost->fifo= av_fifo_alloc(1024);
02277 if(!ost->fifo)
02278 goto fail;
02279 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
02280 if (!codec->sample_rate) {
02281 codec->sample_rate = icodec->sample_rate;
02282 if (icodec->lowres)
02283 codec->sample_rate >>= icodec->lowres;
02284 }
02285 choose_sample_rate(ost->st, ost->enc);
02286 codec->time_base = (AVRational){1, codec->sample_rate};
02287 if (!codec->channels)
02288 codec->channels = icodec->channels;
02289 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
02290 codec->channel_layout = 0;
02291 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
02292 icodec->request_channels = codec->channels;
02293 ist->decoding_needed = 1;
02294 ost->encoding_needed = 1;
02295 ost->resample_sample_fmt = icodec->sample_fmt;
02296 ost->resample_sample_rate = icodec->sample_rate;
02297 ost->resample_channels = icodec->channels;
02298 break;
02299 case AVMEDIA_TYPE_VIDEO:
02300 if (codec->pix_fmt == PIX_FMT_NONE)
02301 codec->pix_fmt = icodec->pix_fmt;
02302 choose_pixel_fmt(ost->st, ost->enc);
02303
02304 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
02305 fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
02306 ffmpeg_exit(1);
02307 }
02308
02309 if (!codec->width || !codec->height) {
02310 codec->width = icodec->width;
02311 codec->height = icodec->height;
02312 }
02313
02314 ost->video_resample = codec->width != icodec->width ||
02315 codec->height != icodec->height ||
02316 codec->pix_fmt != icodec->pix_fmt;
02317 if (ost->video_resample) {
02318 codec->bits_per_raw_sample= frame_bits_per_raw_sample;
02319 }
02320
02321 ost->resample_height = icodec->height;
02322 ost->resample_width = icodec->width;
02323 ost->resample_pix_fmt= icodec->pix_fmt;
02324 ost->encoding_needed = 1;
02325 ist->decoding_needed = 1;
02326
02327 if (!ost->frame_rate.num)
02328 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
02329 if (ost->enc && ost->enc->supported_framerates && !force_fps) {
02330 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
02331 ost->frame_rate = ost->enc->supported_framerates[idx];
02332 }
02333 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
02334 if( av_q2d(codec->time_base) < 0.001 && video_sync_method
02335 && (video_sync_method==1 || (video_sync_method<0 && !(os->oformat->flags & AVFMT_VARIABLE_FPS)))){
02336 av_log(os, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
02337 "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
02338 }
02339
02340 if (ost->forced_key_frames)
02341 parse_forced_key_frames(ost->forced_key_frames, ost, codec);
02342
02343 #if CONFIG_AVFILTER
02344 if (configure_video_filters(ist, ost)) {
02345 fprintf(stderr, "Error opening filters!\n");
02346 exit(1);
02347 }
02348 #endif
02349 break;
02350 case AVMEDIA_TYPE_SUBTITLE:
02351 ost->encoding_needed = 1;
02352 ist->decoding_needed = 1;
02353 break;
02354 default:
02355 abort();
02356 break;
02357 }
02358
02359 if (ost->encoding_needed && codec->codec_id != CODEC_ID_H264 &&
02360 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
02361 char logfilename[1024];
02362 FILE *f;
02363
02364 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
02365 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
02366 i);
02367 if (codec->flags & CODEC_FLAG_PASS1) {
02368 f = fopen(logfilename, "wb");
02369 if (!f) {
02370 fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
02371 ffmpeg_exit(1);
02372 }
02373 ost->logfile = f;
02374 } else {
02375 char *logbuffer;
02376 size_t logbuffer_size;
02377 if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
02378 fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
02379 ffmpeg_exit(1);
02380 }
02381 codec->stats_in = logbuffer;
02382 }
02383 }
02384 }
02385 if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
02386
02387 int size= codec->width * codec->height;
02388 bit_buffer_size= FFMAX(bit_buffer_size, 7*size + 10000);
02389 }
02390 }
02391
02392 if (!bit_buffer)
02393 bit_buffer = av_malloc(bit_buffer_size);
02394 if (!bit_buffer) {
02395 fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
02396 bit_buffer_size);
02397 ret = AVERROR(ENOMEM);
02398 goto fail;
02399 }
02400
02401
02402 for(i=0;i<nb_ostreams;i++) {
02403 ost = ost_table[i];
02404 if (ost->encoding_needed) {
02405 AVCodec *codec = ost->enc;
02406 AVCodecContext *dec = input_streams[ost->source_index].st->codec;
02407 if (!codec) {
02408 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
02409 ost->st->codec->codec_id, ost->file_index, ost->index);
02410 ret = AVERROR(EINVAL);
02411 goto dump_format;
02412 }
02413 if (dec->subtitle_header) {
02414 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
02415 if (!ost->st->codec->subtitle_header) {
02416 ret = AVERROR(ENOMEM);
02417 goto dump_format;
02418 }
02419 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
02420 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
02421 }
02422 if (avcodec_open(ost->st->codec, codec) < 0) {
02423 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
02424 ost->file_index, ost->index);
02425 ret = AVERROR(EINVAL);
02426 goto dump_format;
02427 }
02428 extra_size += ost->st->codec->extradata_size;
02429 }
02430 }
02431
02432
02433 for (i = 0; i < nb_input_streams; i++) {
02434 ist = &input_streams[i];
02435 if (ist->decoding_needed) {
02436 AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
02437 if (!codec)
02438 codec = avcodec_find_decoder(ist->st->codec->codec_id);
02439 if (!codec) {
02440 snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
02441 ist->st->codec->codec_id, ist->file_index, ist->st->index);
02442 ret = AVERROR(EINVAL);
02443 goto dump_format;
02444 }
02445 if (avcodec_open(ist->st->codec, codec) < 0) {
02446 snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
02447 ist->file_index, ist->st->index);
02448 ret = AVERROR(EINVAL);
02449 goto dump_format;
02450 }
02451
02452
02453 }
02454 }
02455
02456
02457 for (i = 0; i < nb_input_streams; i++) {
02458 AVStream *st;
02459 ist = &input_streams[i];
02460 st= ist->st;
02461 ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
02462 ist->next_pts = AV_NOPTS_VALUE;
02463 ist->is_start = 1;
02464 }
02465
02466
02467 for (i=0;i<nb_meta_data_maps;i++) {
02468 AVFormatContext *files[2];
02469 AVDictionary **meta[2];
02470 int j;
02471
02472 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
02473 if ((index) < 0 || (index) >= (nb_elems)) {\
02474 snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
02475 (desc), (index));\
02476 ret = AVERROR(EINVAL);\
02477 goto dump_format;\
02478 }
02479
02480 int out_file_index = meta_data_maps[i][0].file;
02481 int in_file_index = meta_data_maps[i][1].file;
02482 if (in_file_index < 0 || out_file_index < 0)
02483 continue;
02484 METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
02485 METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
02486
02487 files[0] = output_files[out_file_index];
02488 files[1] = input_files[in_file_index].ctx;
02489
02490 for (j = 0; j < 2; j++) {
02491 AVMetaDataMap *map = &meta_data_maps[i][j];
02492
02493 switch (map->type) {
02494 case 'g':
02495 meta[j] = &files[j]->metadata;
02496 break;
02497 case 's':
02498 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
02499 meta[j] = &files[j]->streams[map->index]->metadata;
02500 break;
02501 case 'c':
02502 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
02503 meta[j] = &files[j]->chapters[map->index]->metadata;
02504 break;
02505 case 'p':
02506 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
02507 meta[j] = &files[j]->programs[map->index]->metadata;
02508 break;
02509 }
02510 }
02511
02512 av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
02513 }
02514
02515
02516 if (metadata_global_autocopy) {
02517
02518 for (i = 0; i < nb_output_files; i++)
02519 av_dict_copy(&output_files[i]->metadata, input_files[0].ctx->metadata,
02520 AV_DICT_DONT_OVERWRITE);
02521 }
02522
02523
02524 for (i = 0; i < nb_chapter_maps; i++) {
02525 int infile = chapter_maps[i].in_file;
02526 int outfile = chapter_maps[i].out_file;
02527
02528 if (infile < 0 || outfile < 0)
02529 continue;
02530 if (infile >= nb_input_files) {
02531 snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
02532 ret = AVERROR(EINVAL);
02533 goto dump_format;
02534 }
02535 if (outfile >= nb_output_files) {
02536 snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
02537 ret = AVERROR(EINVAL);
02538 goto dump_format;
02539 }
02540 copy_chapters(infile, outfile);
02541 }
02542
02543
02544 if (!nb_chapter_maps)
02545 for (i = 0; i < nb_input_files; i++) {
02546 if (!input_files[i].ctx->nb_chapters)
02547 continue;
02548
02549 for (j = 0; j < nb_output_files; j++)
02550 if ((ret = copy_chapters(i, j)) < 0)
02551 goto dump_format;
02552 break;
02553 }
02554
02555
02556 for(i=0;i<nb_output_files;i++) {
02557 os = output_files[i];
02558 if (av_write_header(os) < 0) {
02559 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
02560 ret = AVERROR(EINVAL);
02561 goto dump_format;
02562 }
02563 if (strcmp(output_files[i]->oformat->name, "rtp")) {
02564 want_sdp = 0;
02565 }
02566 }
02567
02568 dump_format:
02569
02570
02571 for(i=0;i<nb_output_files;i++) {
02572 av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02573 }
02574
02575
02576 if (verbose >= 0) {
02577 fprintf(stderr, "Stream mapping:\n");
02578 for(i=0;i<nb_ostreams;i++) {
02579 ost = ost_table[i];
02580 fprintf(stderr, " Stream #%d.%d -> #%d.%d",
02581 input_streams[ost->source_index].file_index,
02582 input_streams[ost->source_index].st->index,
02583 ost->file_index,
02584 ost->index);
02585 if (ost->sync_ist != &input_streams[ost->source_index])
02586 fprintf(stderr, " [sync #%d.%d]",
02587 ost->sync_ist->file_index,
02588 ost->sync_ist->st->index);
02589 fprintf(stderr, "\n");
02590 }
02591 }
02592
02593 if (ret) {
02594 fprintf(stderr, "%s\n", error);
02595 goto fail;
02596 }
02597
02598 if (want_sdp) {
02599 print_sdp(output_files, nb_output_files);
02600 }
02601
02602 if (!using_stdin) {
02603 if(verbose >= 0)
02604 fprintf(stderr, "Press [q] to stop, [?] for help\n");
02605 avio_set_interrupt_cb(decode_interrupt_cb);
02606 }
02607 term_init();
02608
02609 timer_start = av_gettime();
02610
02611 for(; received_sigterm == 0;) {
02612 int file_index, ist_index;
02613 AVPacket pkt;
02614 double ipts_min;
02615 double opts_min;
02616
02617 redo:
02618 ipts_min= 1e100;
02619 opts_min= 1e100;
02620
02621 if (!using_stdin) {
02622 if (q_pressed)
02623 break;
02624
02625 key = read_key();
02626 if (key == 'q')
02627 break;
02628 if (key == '+') verbose++;
02629 if (key == '-') verbose--;
02630 if (key == 's') qp_hist ^= 1;
02631 if (key == 'h'){
02632 if (do_hex_dump){
02633 do_hex_dump = do_pkt_dump = 0;
02634 } else if(do_pkt_dump){
02635 do_hex_dump = 1;
02636 } else
02637 do_pkt_dump = 1;
02638 av_log_set_level(AV_LOG_DEBUG);
02639 }
02640 if (key == 'd' || key == 'D'){
02641 int debug=0;
02642 if(key == 'D') {
02643 debug = input_streams[0].st->codec->debug<<1;
02644 if(!debug) debug = 1;
02645 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE))
02646 debug += debug;
02647 }else
02648 scanf("%d", &debug);
02649 for(i=0;i<nb_input_streams;i++) {
02650 input_streams[i].st->codec->debug = debug;
02651 }
02652 for(i=0;i<nb_ostreams;i++) {
02653 ost = ost_table[i];
02654 ost->st->codec->debug = debug;
02655 }
02656 if(debug) av_log_set_level(AV_LOG_DEBUG);
02657 fprintf(stderr,"debug=%d\n", debug);
02658 }
02659 if (key == '?'){
02660 fprintf(stderr, "key function\n"
02661 "? show this help\n"
02662 "+ increase verbosity\n"
02663 "- decrease verbosity\n"
02664 "D cycle through available debug modes\n"
02665 "h dump packets/hex press to cycle through the 3 states\n"
02666 "q quit\n"
02667 "s Show QP histogram\n"
02668 );
02669 }
02670 }
02671
02672
02673
02674 file_index = -1;
02675 for(i=0;i<nb_ostreams;i++) {
02676 double ipts, opts;
02677 ost = ost_table[i];
02678 os = output_files[ost->file_index];
02679 ist = &input_streams[ost->source_index];
02680 if(ist->is_past_recording_time || no_packet[ist->file_index])
02681 continue;
02682 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
02683 ipts = (double)ist->pts;
02684 if (!input_files[ist->file_index].eof_reached){
02685 if(ipts < ipts_min) {
02686 ipts_min = ipts;
02687 if(input_sync ) file_index = ist->file_index;
02688 }
02689 if(opts < opts_min) {
02690 opts_min = opts;
02691 if(!input_sync) file_index = ist->file_index;
02692 }
02693 }
02694 if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
02695 file_index= -1;
02696 break;
02697 }
02698 }
02699
02700 if (file_index < 0) {
02701 if(no_packet_count){
02702 no_packet_count=0;
02703 memset(no_packet, 0, sizeof(no_packet));
02704 usleep(10000);
02705 continue;
02706 }
02707 break;
02708 }
02709
02710
02711 if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
02712 break;
02713
02714
02715 is = input_files[file_index].ctx;
02716 ret= av_read_frame(is, &pkt);
02717 if(ret == AVERROR(EAGAIN)){
02718 no_packet[file_index]=1;
02719 no_packet_count++;
02720 continue;
02721 }
02722 if (ret < 0) {
02723 input_files[file_index].eof_reached = 1;
02724 if (opt_shortest)
02725 break;
02726 else
02727 continue;
02728 }
02729
02730 no_packet_count=0;
02731 memset(no_packet, 0, sizeof(no_packet));
02732
02733 if (do_pkt_dump) {
02734 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
02735 is->streams[pkt.stream_index]);
02736 }
02737
02738
02739 if (pkt.stream_index >= input_files[file_index].nb_streams)
02740 goto discard_packet;
02741 ist_index = input_files[file_index].ist_index + pkt.stream_index;
02742 ist = &input_streams[ist_index];
02743 if (ist->discard)
02744 goto discard_packet;
02745
02746 if (pkt.dts != AV_NOPTS_VALUE)
02747 pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02748 if (pkt.pts != AV_NOPTS_VALUE)
02749 pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02750
02751 if (pkt.stream_index < nb_input_files_ts_scale[file_index]
02752 && input_files_ts_scale[file_index][pkt.stream_index]){
02753 if(pkt.pts != AV_NOPTS_VALUE)
02754 pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
02755 if(pkt.dts != AV_NOPTS_VALUE)
02756 pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
02757 }
02758
02759
02760 if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
02761 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
02762 int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
02763 int64_t delta= pkt_dts - ist->next_pts;
02764 if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
02765 input_files_ts_offset[ist->file_index]-= delta;
02766 if (verbose > 2)
02767 fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
02768 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02769 if(pkt.pts != AV_NOPTS_VALUE)
02770 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02771 }
02772 }
02773
02774
02775 if (recording_time != INT64_MAX &&
02776 (pkt.pts != AV_NOPTS_VALUE ?
02777 av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000})
02778 :
02779 av_compare_ts(ist->pts, AV_TIME_BASE_Q, recording_time + start_time, (AVRational){1, 1000000})
02780 )>= 0) {
02781 ist->is_past_recording_time = 1;
02782 goto discard_packet;
02783 }
02784
02785
02786 if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
02787
02788 if (verbose >= 0)
02789 fprintf(stderr, "Error while decoding stream #%d.%d\n",
02790 ist->file_index, ist->st->index);
02791 if (exit_on_error)
02792 ffmpeg_exit(1);
02793 av_free_packet(&pkt);
02794 goto redo;
02795 }
02796
02797 discard_packet:
02798 av_free_packet(&pkt);
02799
02800
02801 print_report(output_files, ost_table, nb_ostreams, 0);
02802 }
02803
02804
02805 for (i = 0; i < nb_input_streams; i++) {
02806 ist = &input_streams[i];
02807 if (ist->decoding_needed) {
02808 output_packet(ist, i, ost_table, nb_ostreams, NULL);
02809 }
02810 }
02811
02812 term_exit();
02813
02814
02815 for(i=0;i<nb_output_files;i++) {
02816 os = output_files[i];
02817 av_write_trailer(os);
02818 }
02819
02820
02821 print_report(output_files, ost_table, nb_ostreams, 1);
02822
02823
02824 for(i=0;i<nb_ostreams;i++) {
02825 ost = ost_table[i];
02826 if (ost->encoding_needed) {
02827 av_freep(&ost->st->codec->stats_in);
02828 avcodec_close(ost->st->codec);
02829 }
02830 #if CONFIG_AVFILTER
02831 avfilter_graph_free(&ost->graph);
02832 #endif
02833 }
02834
02835
02836 for (i = 0; i < nb_input_streams; i++) {
02837 ist = &input_streams[i];
02838 if (ist->decoding_needed) {
02839 avcodec_close(ist->st->codec);
02840 }
02841 }
02842
02843
02844 ret = 0;
02845
02846 fail:
02847 av_freep(&bit_buffer);
02848
02849 if (ost_table) {
02850 for(i=0;i<nb_ostreams;i++) {
02851 ost = ost_table[i];
02852 if (ost) {
02853 if (ost->st->stream_copy)
02854 av_freep(&ost->st->codec->extradata);
02855 if (ost->logfile) {
02856 fclose(ost->logfile);
02857 ost->logfile = NULL;
02858 }
02859 av_fifo_free(ost->fifo);
02860
02861 av_freep(&ost->st->codec->subtitle_header);
02862 av_free(ost->resample_frame.data[0]);
02863 av_free(ost->forced_kf_pts);
02864 av_free(ost->forced_key_frames);
02865 if (ost->video_resample)
02866 sws_freeContext(ost->img_resample_ctx);
02867 if (ost->resample)
02868 audio_resample_close(ost->resample);
02869 if (ost->reformat_ctx)
02870 av_audio_convert_free(ost->reformat_ctx);
02871 av_free(ost);
02872 }
02873 }
02874 av_free(ost_table);
02875 }
02876 return ret;
02877 }
02878
02879 static int opt_format(const char *opt, const char *arg)
02880 {
02881 last_asked_format = arg;
02882 return 0;
02883 }
02884
02885 static int opt_video_rc_override_string(const char *opt, const char *arg)
02886 {
02887 video_rc_override_string = arg;
02888 return 0;
02889 }
02890
02891 static int opt_me_threshold(const char *opt, const char *arg)
02892 {
02893 me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
02894 return 0;
02895 }
02896
02897 static int opt_verbose(const char *opt, const char *arg)
02898 {
02899 verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
02900 return 0;
02901 }
02902
02903 static int opt_frame_rate(const char *opt, const char *arg)
02904 {
02905 if (av_parse_video_rate(&frame_rate, arg) < 0) {
02906 fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
02907 ffmpeg_exit(1);
02908 }
02909 return 0;
02910 }
02911
02912 static int opt_bitrate(const char *opt, const char *arg)
02913 {
02914 int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
02915
02916 opt_default(opt, arg);
02917
02918 if (av_get_int(avcodec_opts[codec_type], "b", NULL) < 1000)
02919 fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
02920
02921 return 0;
02922 }
02923
02924 static int opt_frame_crop(const char *opt, const char *arg)
02925 {
02926 fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
02927 return AVERROR(EINVAL);
02928 }
02929
02930 static int opt_frame_size(const char *opt, const char *arg)
02931 {
02932 if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
02933 fprintf(stderr, "Incorrect frame size\n");
02934 return AVERROR(EINVAL);
02935 }
02936 return 0;
02937 }
02938
02939 static int opt_pad(const char *opt, const char *arg) {
02940 fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
02941 return -1;
02942 }
02943
02944 static int opt_frame_pix_fmt(const char *opt, const char *arg)
02945 {
02946 if (strcmp(arg, "list")) {
02947 frame_pix_fmt = av_get_pix_fmt(arg);
02948 if (frame_pix_fmt == PIX_FMT_NONE) {
02949 fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
02950 return AVERROR(EINVAL);
02951 }
02952 } else {
02953 opt_pix_fmts(NULL, NULL);
02954 ffmpeg_exit(0);
02955 }
02956 return 0;
02957 }
02958
02959 static int opt_frame_aspect_ratio(const char *opt, const char *arg)
02960 {
02961 int x = 0, y = 0;
02962 double ar = 0;
02963 const char *p;
02964 char *end;
02965
02966 p = strchr(arg, ':');
02967 if (p) {
02968 x = strtol(arg, &end, 10);
02969 if (end == p)
02970 y = strtol(end+1, &end, 10);
02971 if (x > 0 && y > 0)
02972 ar = (double)x / (double)y;
02973 } else
02974 ar = strtod(arg, NULL);
02975
02976 if (!ar) {
02977 fprintf(stderr, "Incorrect aspect ratio specification.\n");
02978 return AVERROR(EINVAL);
02979 }
02980 frame_aspect_ratio = ar;
02981 return 0;
02982 }
02983
02984 static int opt_metadata(const char *opt, const char *arg)
02985 {
02986 char *mid= strchr(arg, '=');
02987
02988 if(!mid){
02989 fprintf(stderr, "Missing =\n");
02990 ffmpeg_exit(1);
02991 }
02992 *mid++= 0;
02993
02994 av_dict_set(&metadata, arg, mid, 0);
02995
02996 return 0;
02997 }
02998
02999 static int opt_qscale(const char *opt, const char *arg)
03000 {
03001 video_qscale = parse_number_or_die(opt, arg, OPT_FLOAT, 0, 255);
03002 if (video_qscale <= 0 || video_qscale > 255) {
03003 fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
03004 return AVERROR(EINVAL);
03005 }
03006 return 0;
03007 }
03008
03009 static int opt_top_field_first(const char *opt, const char *arg)
03010 {
03011 top_field_first = parse_number_or_die(opt, arg, OPT_INT, 0, 1);
03012 opt_default(opt, arg);
03013 return 0;
03014 }
03015
03016 static int opt_thread_count(const char *opt, const char *arg)
03017 {
03018 thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03019 #if !HAVE_THREADS
03020 if (verbose >= 0)
03021 fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
03022 #endif
03023 return 0;
03024 }
03025
03026 static int opt_audio_sample_fmt(const char *opt, const char *arg)
03027 {
03028 if (strcmp(arg, "list")) {
03029 audio_sample_fmt = av_get_sample_fmt(arg);
03030 if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
03031 av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
03032 return AVERROR(EINVAL);
03033 }
03034 } else {
03035 int i;
03036 char fmt_str[128];
03037 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
03038 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
03039 ffmpeg_exit(0);
03040 }
03041 return 0;
03042 }
03043
03044 static int opt_audio_rate(const char *opt, const char *arg)
03045 {
03046 audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03047 return 0;
03048 }
03049
03050 static int opt_audio_channels(const char *opt, const char *arg)
03051 {
03052 audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03053 return 0;
03054 }
03055
03056 static int opt_video_channel(const char *opt, const char *arg)
03057 {
03058 video_channel = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03059 return 0;
03060 }
03061
03062 static int opt_video_standard(const char *opt, const char *arg)
03063 {
03064 video_standard = av_strdup(arg);
03065 return 0;
03066 }
03067
03068 static int opt_codec(const char *opt, const char *arg)
03069 {
03070 int *pstream_copy; char **pcodec_name; enum AVMediaType codec_type;
03071
03072 if (!strcmp(opt, "acodec")) { pstream_copy = &audio_stream_copy; pcodec_name = &audio_codec_name; codec_type = AVMEDIA_TYPE_AUDIO; }
03073 else if (!strcmp(opt, "vcodec")) { pstream_copy = &video_stream_copy; pcodec_name = &video_codec_name; codec_type = AVMEDIA_TYPE_VIDEO; }
03074 else if (!strcmp(opt, "scodec")) { pstream_copy = &subtitle_stream_copy; pcodec_name = &subtitle_codec_name; codec_type = AVMEDIA_TYPE_SUBTITLE; }
03075 else if (!strcmp(opt, "dcodec")) { pstream_copy = &data_stream_copy; pcodec_name = &data_codec_name; codec_type = AVMEDIA_TYPE_DATA; }
03076
03077 av_freep(pcodec_name);
03078 if (!strcmp(arg, "copy")) {
03079 *pstream_copy = 1;
03080 } else {
03081 *pcodec_name = av_strdup(arg);
03082 }
03083 return 0;
03084 }
03085
03086 static int opt_codec_tag(const char *opt, const char *arg)
03087 {
03088 char *tail;
03089 uint32_t *codec_tag;
03090
03091 codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
03092 !strcmp(opt, "vtag") ? &video_codec_tag :
03093 !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
03094 if (!codec_tag)
03095 return -1;
03096
03097 *codec_tag = strtol(arg, &tail, 0);
03098 if (!tail || *tail)
03099 *codec_tag = AV_RL32(arg);
03100
03101 return 0;
03102 }
03103
03104 static int opt_map(const char *opt, const char *arg)
03105 {
03106 AVStreamMap *m;
03107 char *p;
03108
03109 stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
03110 m = &stream_maps[nb_stream_maps-1];
03111
03112 m->file_index = strtol(arg, &p, 0);
03113 if (*p)
03114 p++;
03115
03116 m->stream_index = strtol(p, &p, 0);
03117 if (*p) {
03118 p++;
03119 m->sync_file_index = strtol(p, &p, 0);
03120 if (*p)
03121 p++;
03122 m->sync_stream_index = strtol(p, &p, 0);
03123 } else {
03124 m->sync_file_index = m->file_index;
03125 m->sync_stream_index = m->stream_index;
03126 }
03127 return 0;
03128 }
03129
03130 static void parse_meta_type(char *arg, char *type, int *index, char **endptr)
03131 {
03132 *endptr = arg;
03133 if (*arg == ',') {
03134 *type = *(++arg);
03135 switch (*arg) {
03136 case 'g':
03137 break;
03138 case 's':
03139 case 'c':
03140 case 'p':
03141 *index = strtol(++arg, endptr, 0);
03142 break;
03143 default:
03144 fprintf(stderr, "Invalid metadata type %c.\n", *arg);
03145 ffmpeg_exit(1);
03146 }
03147 } else
03148 *type = 'g';
03149 }
03150
03151 static int opt_map_metadata(const char *opt, const char *arg)
03152 {
03153 AVMetaDataMap *m, *m1;
03154 char *p;
03155
03156 meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
03157 &nb_meta_data_maps, nb_meta_data_maps + 1);
03158
03159 m = &meta_data_maps[nb_meta_data_maps - 1][0];
03160 m->file = strtol(arg, &p, 0);
03161 parse_meta_type(p, &m->type, &m->index, &p);
03162 if (*p)
03163 p++;
03164
03165 m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
03166 m1->file = strtol(p, &p, 0);
03167 parse_meta_type(p, &m1->type, &m1->index, &p);
03168
03169 if (m->type == 'g' || m1->type == 'g')
03170 metadata_global_autocopy = 0;
03171 if (m->type == 's' || m1->type == 's')
03172 metadata_streams_autocopy = 0;
03173 if (m->type == 'c' || m1->type == 'c')
03174 metadata_chapters_autocopy = 0;
03175
03176 return 0;
03177 }
03178
03179 static int opt_map_meta_data(const char *opt, const char *arg)
03180 {
03181 fprintf(stderr, "-map_meta_data is deprecated and will be removed soon. "
03182 "Use -map_metadata instead.\n");
03183 return opt_map_metadata(opt, arg);
03184 }
03185
03186 static int opt_map_chapters(const char *opt, const char *arg)
03187 {
03188 AVChapterMap *c;
03189 char *p;
03190
03191 chapter_maps = grow_array(chapter_maps, sizeof(*chapter_maps), &nb_chapter_maps,
03192 nb_chapter_maps + 1);
03193 c = &chapter_maps[nb_chapter_maps - 1];
03194 c->out_file = strtol(arg, &p, 0);
03195 if (*p)
03196 p++;
03197
03198 c->in_file = strtol(p, &p, 0);
03199 return 0;
03200 }
03201
03202 static int opt_input_ts_scale(const char *opt, const char *arg)
03203 {
03204 unsigned int stream;
03205 double scale;
03206 char *p;
03207
03208 stream = strtol(arg, &p, 0);
03209 if (*p)
03210 p++;
03211 scale= strtod(p, &p);
03212
03213 if(stream >= MAX_STREAMS)
03214 ffmpeg_exit(1);
03215
03216 input_files_ts_scale[nb_input_files] = grow_array(input_files_ts_scale[nb_input_files], sizeof(*input_files_ts_scale[nb_input_files]), &nb_input_files_ts_scale[nb_input_files], stream + 1);
03217 input_files_ts_scale[nb_input_files][stream]= scale;
03218 return 0;
03219 }
03220
03221 static int opt_recording_time(const char *opt, const char *arg)
03222 {
03223 recording_time = parse_time_or_die(opt, arg, 1);
03224 return 0;
03225 }
03226
03227 static int opt_start_time(const char *opt, const char *arg)
03228 {
03229 start_time = parse_time_or_die(opt, arg, 1);
03230 return 0;
03231 }
03232
03233 static int opt_recording_timestamp(const char *opt, const char *arg)
03234 {
03235 recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
03236 return 0;
03237 }
03238
03239 static int opt_input_ts_offset(const char *opt, const char *arg)
03240 {
03241 input_ts_offset = parse_time_or_die(opt, arg, 1);
03242 return 0;
03243 }
03244
03245 static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
03246 {
03247 const char *codec_string = encoder ? "encoder" : "decoder";
03248 AVCodec *codec;
03249
03250 if(!name)
03251 return CODEC_ID_NONE;
03252 codec = encoder ?
03253 avcodec_find_encoder_by_name(name) :
03254 avcodec_find_decoder_by_name(name);
03255 if(!codec) {
03256 fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
03257 ffmpeg_exit(1);
03258 }
03259 if(codec->type != type) {
03260 fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
03261 ffmpeg_exit(1);
03262 }
03263 if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
03264 strict > FF_COMPLIANCE_EXPERIMENTAL) {
03265 fprintf(stderr, "%s '%s' is experimental and might produce bad "
03266 "results.\nAdd '-strict experimental' if you want to use it.\n",
03267 codec_string, codec->name);
03268 codec = encoder ?
03269 avcodec_find_encoder(codec->id) :
03270 avcodec_find_decoder(codec->id);
03271 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
03272 fprintf(stderr, "Or use the non experimental %s '%s'.\n",
03273 codec_string, codec->name);
03274 ffmpeg_exit(1);
03275 }
03276 return codec->id;
03277 }
03278
03279 static int opt_input_file(const char *opt, const char *filename)
03280 {
03281 AVFormatContext *ic;
03282 AVFormatParameters params, *ap = ¶ms;
03283 AVInputFormat *file_iformat = NULL;
03284 int err, i, ret, rfps, rfps_base;
03285 int64_t timestamp;
03286
03287 if (last_asked_format) {
03288 if (!(file_iformat = av_find_input_format(last_asked_format))) {
03289 fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
03290 ffmpeg_exit(1);
03291 }
03292 last_asked_format = NULL;
03293 }
03294
03295 if (!strcmp(filename, "-"))
03296 filename = "pipe:";
03297
03298 using_stdin |= !strncmp(filename, "pipe:", 5) ||
03299 !strcmp(filename, "/dev/stdin");
03300
03301
03302 ic = avformat_alloc_context();
03303 if (!ic) {
03304 print_error(filename, AVERROR(ENOMEM));
03305 ffmpeg_exit(1);
03306 }
03307
03308 memset(ap, 0, sizeof(*ap));
03309 ap->prealloced_context = 1;
03310 ap->sample_rate = audio_sample_rate;
03311 ap->channels = audio_channels;
03312 ap->time_base.den = frame_rate.num;
03313 ap->time_base.num = frame_rate.den;
03314 ap->width = frame_width;
03315 ap->height = frame_height;
03316 ap->pix_fmt = frame_pix_fmt;
03317
03318 ap->channel = video_channel;
03319 ap->standard = video_standard;
03320
03321 set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
03322
03323 ic->video_codec_id =
03324 find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0,
03325 avcodec_opts[AVMEDIA_TYPE_VIDEO ]->strict_std_compliance);
03326 ic->audio_codec_id =
03327 find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0,
03328 avcodec_opts[AVMEDIA_TYPE_AUDIO ]->strict_std_compliance);
03329 ic->subtitle_codec_id=
03330 find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
03331 avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
03332 ic->flags |= AVFMT_FLAG_NONBLOCK | AVFMT_FLAG_PRIV_OPT;
03333
03334
03335 err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
03336 if(err >= 0){
03337 set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
03338 err = av_demuxer_open(ic, ap);
03339 if(err < 0)
03340 avformat_free_context(ic);
03341 }
03342 if (err < 0) {
03343 print_error(filename, err);
03344 ffmpeg_exit(1);
03345 }
03346 if(opt_programid) {
03347 int i, j;
03348 int found=0;
03349 for(i=0; i<ic->nb_streams; i++){
03350 ic->streams[i]->discard= AVDISCARD_ALL;
03351 }
03352 for(i=0; i<ic->nb_programs; i++){
03353 AVProgram *p= ic->programs[i];
03354 if(p->id != opt_programid){
03355 p->discard = AVDISCARD_ALL;
03356 }else{
03357 found=1;
03358 for(j=0; j<p->nb_stream_indexes; j++){
03359 ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
03360 }
03361 }
03362 }
03363 if(!found){
03364 fprintf(stderr, "Specified program id not found\n");
03365 ffmpeg_exit(1);
03366 }
03367 opt_programid=0;
03368 }
03369
03370 ic->loop_input = loop_input;
03371
03372
03373
03374 ret = av_find_stream_info(ic);
03375 if (ret < 0 && verbose >= 0) {
03376 fprintf(stderr, "%s: could not find codec parameters\n", filename);
03377 av_close_input_file(ic);
03378 ffmpeg_exit(1);
03379 }
03380
03381 timestamp = start_time;
03382
03383 if (ic->start_time != AV_NOPTS_VALUE)
03384 timestamp += ic->start_time;
03385
03386
03387 if (start_time != 0) {
03388 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
03389 if (ret < 0) {
03390 fprintf(stderr, "%s: could not seek to position %0.3f\n",
03391 filename, (double)timestamp / AV_TIME_BASE);
03392 }
03393
03394 start_time = 0;
03395 }
03396
03397
03398 for(i=0;i<ic->nb_streams;i++) {
03399 AVStream *st = ic->streams[i];
03400 AVCodecContext *dec = st->codec;
03401 AVInputStream *ist;
03402
03403 dec->thread_count = thread_count;
03404 input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
03405
03406 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
03407 ist = &input_streams[nb_input_streams - 1];
03408 ist->st = st;
03409 ist->file_index = nb_input_files;
03410 ist->discard = 1;
03411
03412 switch (dec->codec_type) {
03413 case AVMEDIA_TYPE_AUDIO:
03414 input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
03415 if(!input_codecs[nb_input_codecs-1])
03416 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03417 set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
03418 channel_layout = dec->channel_layout;
03419 audio_sample_fmt = dec->sample_fmt;
03420 if(audio_disable)
03421 st->discard= AVDISCARD_ALL;
03422 break;
03423 case AVMEDIA_TYPE_VIDEO:
03424 input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
03425 if(!input_codecs[nb_input_codecs-1])
03426 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03427 set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
03428 rfps = ic->streams[i]->r_frame_rate.num;
03429 rfps_base = ic->streams[i]->r_frame_rate.den;
03430 if (dec->lowres) {
03431 dec->flags |= CODEC_FLAG_EMU_EDGE;
03432 dec->height >>= dec->lowres;
03433 dec->width >>= dec->lowres;
03434 }
03435 if(me_threshold)
03436 dec->debug |= FF_DEBUG_MV;
03437
03438 if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
03439
03440 if (verbose >= 0)
03441 fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
03442 i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
03443
03444 (float)rfps / rfps_base, rfps, rfps_base);
03445 }
03446
03447 if(video_disable)
03448 st->discard= AVDISCARD_ALL;
03449 else if(video_discard)
03450 st->discard= video_discard;
03451 break;
03452 case AVMEDIA_TYPE_DATA:
03453 break;
03454 case AVMEDIA_TYPE_SUBTITLE:
03455 input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
03456 if(!input_codecs[nb_input_codecs-1])
03457 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03458 if(subtitle_disable)
03459 st->discard = AVDISCARD_ALL;
03460 break;
03461 case AVMEDIA_TYPE_ATTACHMENT:
03462 case AVMEDIA_TYPE_UNKNOWN:
03463 break;
03464 default:
03465 abort();
03466 }
03467 }
03468
03469 input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
03470
03471 if (verbose >= 0)
03472 av_dump_format(ic, nb_input_files, filename, 0);
03473
03474 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
03475 input_files[nb_input_files - 1].ctx = ic;
03476 input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
03477 input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
03478
03479 top_field_first = -1;
03480 video_channel = 0;
03481 frame_rate = (AVRational){0, 0};
03482 frame_pix_fmt = PIX_FMT_NONE;
03483 frame_height = 0;
03484 frame_width = 0;
03485 audio_sample_rate = 0;
03486 audio_channels = 0;
03487
03488 av_freep(&video_codec_name);
03489 av_freep(&audio_codec_name);
03490 av_freep(&subtitle_codec_name);
03491 uninit_opts();
03492 init_opts();
03493 return 0;
03494 }
03495
03496 static void check_inputs(int *has_video_ptr,
03497 int *has_audio_ptr,
03498 int *has_subtitle_ptr,
03499 int *has_data_ptr)
03500 {
03501 int has_video, has_audio, has_subtitle, has_data, i, j;
03502 AVFormatContext *ic;
03503
03504 has_video = 0;
03505 has_audio = 0;
03506 has_subtitle = 0;
03507 has_data = 0;
03508
03509 for(j=0;j<nb_input_files;j++) {
03510 ic = input_files[j].ctx;
03511 for(i=0;i<ic->nb_streams;i++) {
03512 AVCodecContext *enc = ic->streams[i]->codec;
03513 switch(enc->codec_type) {
03514 case AVMEDIA_TYPE_AUDIO:
03515 has_audio = 1;
03516 break;
03517 case AVMEDIA_TYPE_VIDEO:
03518 has_video = 1;
03519 break;
03520 case AVMEDIA_TYPE_SUBTITLE:
03521 has_subtitle = 1;
03522 break;
03523 case AVMEDIA_TYPE_DATA:
03524 case AVMEDIA_TYPE_ATTACHMENT:
03525 case AVMEDIA_TYPE_UNKNOWN:
03526 has_data = 1;
03527 break;
03528 default:
03529 abort();
03530 }
03531 }
03532 }
03533 *has_video_ptr = has_video;
03534 *has_audio_ptr = has_audio;
03535 *has_subtitle_ptr = has_subtitle;
03536 *has_data_ptr = has_data;
03537 }
03538
03539 static void new_video_stream(AVFormatContext *oc, int file_idx)
03540 {
03541 AVStream *st;
03542 AVOutputStream *ost;
03543 AVCodecContext *video_enc;
03544 enum CodecID codec_id = CODEC_ID_NONE;
03545 AVCodec *codec= NULL;
03546
03547 st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03548 if (!st) {
03549 fprintf(stderr, "Could not alloc stream\n");
03550 ffmpeg_exit(1);
03551 }
03552 ost = new_output_stream(oc, file_idx);
03553
03554 if(!video_stream_copy){
03555 if (video_codec_name) {
03556 codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
03557 avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
03558 codec = avcodec_find_encoder_by_name(video_codec_name);
03559 ost->enc = codec;
03560 } else {
03561 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
03562 codec = avcodec_find_encoder(codec_id);
03563 }
03564 ost->frame_aspect_ratio = frame_aspect_ratio;
03565 frame_aspect_ratio = 0;
03566 #if CONFIG_AVFILTER
03567 ost->avfilter = vfilters;
03568 vfilters = NULL;
03569 #endif
03570 }
03571
03572 avcodec_get_context_defaults3(st->codec, codec);
03573 ost->bitstream_filters = video_bitstream_filters;
03574 video_bitstream_filters= NULL;
03575
03576 st->codec->thread_count= thread_count;
03577
03578 video_enc = st->codec;
03579
03580 if(video_codec_tag)
03581 video_enc->codec_tag= video_codec_tag;
03582
03583 if(oc->oformat->flags & AVFMT_GLOBALHEADER) {
03584 video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03585 avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
03586 }
03587
03588 if (video_stream_copy) {
03589 st->stream_copy = 1;
03590 video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
03591 video_enc->sample_aspect_ratio =
03592 st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
03593 } else {
03594 const char *p;
03595 int i;
03596
03597 if (frame_rate.num)
03598 ost->frame_rate = frame_rate;
03599 video_enc->codec_id = codec_id;
03600 set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03601
03602 video_enc->width = frame_width;
03603 video_enc->height = frame_height;
03604 video_enc->pix_fmt = frame_pix_fmt;
03605 video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
03606 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
03607
03608 if (intra_only)
03609 video_enc->gop_size = 0;
03610 if (video_qscale || same_quality) {
03611 video_enc->flags |= CODEC_FLAG_QSCALE;
03612 video_enc->global_quality=
03613 st->quality = FF_QP2LAMBDA * video_qscale;
03614 }
03615
03616 if(intra_matrix)
03617 video_enc->intra_matrix = intra_matrix;
03618 if(inter_matrix)
03619 video_enc->inter_matrix = inter_matrix;
03620
03621 p= video_rc_override_string;
03622 for(i=0; p; i++){
03623 int start, end, q;
03624 int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
03625 if(e!=3){
03626 fprintf(stderr, "error parsing rc_override\n");
03627 ffmpeg_exit(1);
03628 }
03629 video_enc->rc_override=
03630 av_realloc(video_enc->rc_override,
03631 sizeof(RcOverride)*(i+1));
03632 video_enc->rc_override[i].start_frame= start;
03633 video_enc->rc_override[i].end_frame = end;
03634 if(q>0){
03635 video_enc->rc_override[i].qscale= q;
03636 video_enc->rc_override[i].quality_factor= 1.0;
03637 }
03638 else{
03639 video_enc->rc_override[i].qscale= 0;
03640 video_enc->rc_override[i].quality_factor= -q/100.0;
03641 }
03642 p= strchr(p, '/');
03643 if(p) p++;
03644 }
03645 video_enc->rc_override_count=i;
03646 if (!video_enc->rc_initial_buffer_occupancy)
03647 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
03648 video_enc->me_threshold= me_threshold;
03649 video_enc->intra_dc_precision= intra_dc_precision - 8;
03650
03651 if (do_psnr)
03652 video_enc->flags|= CODEC_FLAG_PSNR;
03653
03654
03655 if (do_pass) {
03656 if (do_pass == 1) {
03657 video_enc->flags |= CODEC_FLAG_PASS1;
03658 } else {
03659 video_enc->flags |= CODEC_FLAG_PASS2;
03660 }
03661 }
03662
03663 if (forced_key_frames) {
03664 ost->forced_key_frames = forced_key_frames;
03665 forced_key_frames = NULL;
03666 }
03667 }
03668 if (video_language) {
03669 av_dict_set(&st->metadata, "language", video_language, 0);
03670 av_freep(&video_language);
03671 }
03672
03673
03674 video_disable = 0;
03675 av_freep(&video_codec_name);
03676 video_stream_copy = 0;
03677 frame_pix_fmt = PIX_FMT_NONE;
03678 }
03679
03680 static void new_audio_stream(AVFormatContext *oc, int file_idx)
03681 {
03682 AVStream *st;
03683 AVOutputStream *ost;
03684 AVCodec *codec= NULL;
03685 AVCodecContext *audio_enc;
03686 enum CodecID codec_id = CODEC_ID_NONE;
03687
03688 st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03689 if (!st) {
03690 fprintf(stderr, "Could not alloc stream\n");
03691 ffmpeg_exit(1);
03692 }
03693 ost = new_output_stream(oc, file_idx);
03694
03695 if(!audio_stream_copy){
03696 if (audio_codec_name) {
03697 codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
03698 avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
03699 codec = avcodec_find_encoder_by_name(audio_codec_name);
03700 ost->enc = codec;
03701 } else {
03702 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
03703 codec = avcodec_find_encoder(codec_id);
03704 }
03705 }
03706
03707 avcodec_get_context_defaults3(st->codec, codec);
03708
03709 ost->bitstream_filters = audio_bitstream_filters;
03710 audio_bitstream_filters= NULL;
03711
03712 st->codec->thread_count= thread_count;
03713
03714 audio_enc = st->codec;
03715 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
03716
03717 if(audio_codec_tag)
03718 audio_enc->codec_tag= audio_codec_tag;
03719
03720 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03721 audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03722 avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
03723 }
03724 if (audio_stream_copy) {
03725 st->stream_copy = 1;
03726 } else {
03727 audio_enc->codec_id = codec_id;
03728 set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03729
03730 if (audio_qscale > QSCALE_NONE) {
03731 audio_enc->flags |= CODEC_FLAG_QSCALE;
03732 audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
03733 }
03734 if (audio_channels)
03735 audio_enc->channels = audio_channels;
03736 audio_enc->sample_fmt = audio_sample_fmt;
03737 if (audio_sample_rate)
03738 audio_enc->sample_rate = audio_sample_rate;
03739 audio_enc->channel_layout = channel_layout;
03740 choose_sample_fmt(st, codec);
03741 }
03742 if (audio_language) {
03743 av_dict_set(&st->metadata, "language", audio_language, 0);
03744 av_freep(&audio_language);
03745 }
03746
03747
03748 audio_disable = 0;
03749 av_freep(&audio_codec_name);
03750 audio_stream_copy = 0;
03751 }
03752
03753 static void new_data_stream(AVFormatContext *oc, int file_idx)
03754 {
03755 AVStream *st;
03756 AVCodec *codec=NULL;
03757 AVCodecContext *data_enc;
03758
03759 st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03760 if (!st) {
03761 fprintf(stderr, "Could not alloc stream\n");
03762 ffmpeg_exit(1);
03763 }
03764 new_output_stream(oc, file_idx);
03765 data_enc = st->codec;
03766 if (!data_stream_copy) {
03767 fprintf(stderr, "Data stream encoding not supported yet (only streamcopy)\n");
03768 ffmpeg_exit(1);
03769 }
03770 avcodec_get_context_defaults3(st->codec, codec);
03771
03772 data_enc->codec_type = AVMEDIA_TYPE_DATA;
03773
03774 if (data_codec_tag)
03775 data_enc->codec_tag= data_codec_tag;
03776
03777 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03778 data_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03779 avcodec_opts[AVMEDIA_TYPE_DATA]->flags |= CODEC_FLAG_GLOBAL_HEADER;
03780 }
03781 if (data_stream_copy) {
03782 st->stream_copy = 1;
03783 }
03784
03785 data_disable = 0;
03786 av_freep(&data_codec_name);
03787 data_stream_copy = 0;
03788 }
03789
03790 static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
03791 {
03792 AVStream *st;
03793 AVOutputStream *ost;
03794 AVCodec *codec=NULL;
03795 AVCodecContext *subtitle_enc;
03796 enum CodecID codec_id = CODEC_ID_NONE;
03797
03798 st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03799 if (!st) {
03800 fprintf(stderr, "Could not alloc stream\n");
03801 ffmpeg_exit(1);
03802 }
03803 ost = new_output_stream(oc, file_idx);
03804 subtitle_enc = st->codec;
03805 if(!subtitle_stream_copy){
03806 if (subtitle_codec_name) {
03807 codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
03808 avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
03809 codec = avcodec_find_encoder_by_name(subtitle_codec_name);
03810 ost->enc = codec;
03811 } else {
03812 codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);
03813 codec = avcodec_find_encoder(codec_id);
03814 }
03815 }
03816 avcodec_get_context_defaults3(st->codec, codec);
03817
03818 ost->bitstream_filters = subtitle_bitstream_filters;
03819 subtitle_bitstream_filters= NULL;
03820
03821 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
03822
03823 if(subtitle_codec_tag)
03824 subtitle_enc->codec_tag= subtitle_codec_tag;
03825
03826 if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03827 subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03828 avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->flags |= CODEC_FLAG_GLOBAL_HEADER;
03829 }
03830 if (subtitle_stream_copy) {
03831 st->stream_copy = 1;
03832 } else {
03833 subtitle_enc->codec_id = codec_id;
03834 set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03835 }
03836
03837 if (subtitle_language) {
03838 av_dict_set(&st->metadata, "language", subtitle_language, 0);
03839 av_freep(&subtitle_language);
03840 }
03841
03842 subtitle_disable = 0;
03843 av_freep(&subtitle_codec_name);
03844 subtitle_stream_copy = 0;
03845 }
03846
03847 static int opt_new_stream(const char *opt, const char *arg)
03848 {
03849 AVFormatContext *oc;
03850 int file_idx = nb_output_files - 1;
03851 if (nb_output_files <= 0) {
03852 fprintf(stderr, "At least one output file must be specified\n");
03853 ffmpeg_exit(1);
03854 }
03855 oc = output_files[file_idx];
03856
03857 if (!strcmp(opt, "newvideo" )) new_video_stream (oc, file_idx);
03858 else if (!strcmp(opt, "newaudio" )) new_audio_stream (oc, file_idx);
03859 else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
03860 else if (!strcmp(opt, "newdata" )) new_data_stream (oc, file_idx);
03861 else av_assert0(0);
03862 return 0;
03863 }
03864
03865
03866 static int opt_streamid(const char *opt, const char *arg)
03867 {
03868 int idx;
03869 char *p;
03870 char idx_str[16];
03871
03872 av_strlcpy(idx_str, arg, sizeof(idx_str));
03873 p = strchr(idx_str, ':');
03874 if (!p) {
03875 fprintf(stderr,
03876 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
03877 arg, opt);
03878 ffmpeg_exit(1);
03879 }
03880 *p++ = '\0';
03881 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
03882 streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
03883 streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
03884 return 0;
03885 }
03886
03887 static int opt_output_file(const char *opt, const char *filename)
03888 {
03889 AVFormatContext *oc;
03890 int err, use_video, use_audio, use_subtitle, use_data;
03891 int input_has_video, input_has_audio, input_has_subtitle, input_has_data;
03892 AVFormatParameters params, *ap = ¶ms;
03893 AVOutputFormat *file_oformat;
03894
03895 if(nb_output_files >= FF_ARRAY_ELEMS(output_files)){
03896 fprintf(stderr, "Too many output files\n");
03897 ffmpeg_exit(1);
03898 }
03899
03900 if (!strcmp(filename, "-"))
03901 filename = "pipe:";
03902
03903 err = avformat_alloc_output_context2(&oc, NULL, last_asked_format, filename);
03904 last_asked_format = NULL;
03905 if (!oc) {
03906 print_error(filename, err);
03907 ffmpeg_exit(1);
03908 }
03909 file_oformat= oc->oformat;
03910
03911 if (!strcmp(file_oformat->name, "ffm") &&
03912 av_strstart(filename, "http:", NULL)) {
03913
03914
03915 int err = read_ffserver_streams(oc, filename);
03916 if (err < 0) {
03917 print_error(filename, err);
03918 ffmpeg_exit(1);
03919 }
03920 } else {
03921 use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
03922 use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
03923 use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
03924 use_data = data_stream_copy || data_codec_name;
03925
03926
03927
03928 if (nb_input_files > 0) {
03929 check_inputs(&input_has_video,
03930 &input_has_audio,
03931 &input_has_subtitle,
03932 &input_has_data);
03933
03934 if (!input_has_video)
03935 use_video = 0;
03936 if (!input_has_audio)
03937 use_audio = 0;
03938 if (!input_has_subtitle)
03939 use_subtitle = 0;
03940 if (!input_has_data)
03941 use_data = 0;
03942 }
03943
03944
03945 if (audio_disable) use_audio = 0;
03946 if (video_disable) use_video = 0;
03947 if (subtitle_disable) use_subtitle = 0;
03948 if (data_disable) use_data = 0;
03949
03950 if (use_video) new_video_stream(oc, nb_output_files);
03951 if (use_audio) new_audio_stream(oc, nb_output_files);
03952 if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
03953 if (use_data) new_data_stream(oc, nb_output_files);
03954
03955 oc->timestamp = recording_timestamp;
03956
03957 av_dict_copy(&oc->metadata, metadata, 0);
03958 av_dict_free(&metadata);
03959 }
03960
03961 output_files[nb_output_files++] = oc;
03962
03963
03964 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
03965 if (!av_filename_number_test(oc->filename)) {
03966 print_error(oc->filename, AVERROR(EINVAL));
03967 ffmpeg_exit(1);
03968 }
03969 }
03970
03971 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
03972
03973 if (!file_overwrite &&
03974 (strchr(filename, ':') == NULL ||
03975 filename[1] == ':' ||
03976 av_strstart(filename, "file:", NULL))) {
03977 if (avio_check(filename, 0) == 0) {
03978 if (!using_stdin) {
03979 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
03980 fflush(stderr);
03981 if (!read_yesno()) {
03982 fprintf(stderr, "Not overwriting - exiting\n");
03983 ffmpeg_exit(1);
03984 }
03985 }
03986 else {
03987 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
03988 ffmpeg_exit(1);
03989 }
03990 }
03991 }
03992
03993
03994 if ((err = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE)) < 0) {
03995 print_error(filename, err);
03996 ffmpeg_exit(1);
03997 }
03998 }
03999
04000 memset(ap, 0, sizeof(*ap));
04001 if (av_set_parameters(oc, ap) < 0) {
04002 fprintf(stderr, "%s: Invalid encoding parameters\n",
04003 oc->filename);
04004 ffmpeg_exit(1);
04005 }
04006
04007 oc->preload= (int)(mux_preload*AV_TIME_BASE);
04008 oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
04009 oc->loop_output = loop_output;
04010
04011 set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
04012
04013 frame_rate = (AVRational){0, 0};
04014 frame_width = 0;
04015 frame_height = 0;
04016 audio_sample_rate = 0;
04017 audio_channels = 0;
04018
04019 av_freep(&forced_key_frames);
04020 uninit_opts();
04021 init_opts();
04022 return 0;
04023 }
04024
04025
04026 static int opt_pass(const char *opt, const char *arg)
04027 {
04028 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
04029 return 0;
04030 }
04031
04032 static int64_t getutime(void)
04033 {
04034 #if HAVE_GETRUSAGE
04035 struct rusage rusage;
04036
04037 getrusage(RUSAGE_SELF, &rusage);
04038 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
04039 #elif HAVE_GETPROCESSTIMES
04040 HANDLE proc;
04041 FILETIME c, e, k, u;
04042 proc = GetCurrentProcess();
04043 GetProcessTimes(proc, &c, &e, &k, &u);
04044 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
04045 #else
04046 return av_gettime();
04047 #endif
04048 }
04049
04050 static int64_t getmaxrss(void)
04051 {
04052 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
04053 struct rusage rusage;
04054 getrusage(RUSAGE_SELF, &rusage);
04055 return (int64_t)rusage.ru_maxrss * 1024;
04056 #elif HAVE_GETPROCESSMEMORYINFO
04057 HANDLE proc;
04058 PROCESS_MEMORY_COUNTERS memcounters;
04059 proc = GetCurrentProcess();
04060 memcounters.cb = sizeof(memcounters);
04061 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
04062 return memcounters.PeakPagefileUsage;
04063 #else
04064 return 0;
04065 #endif
04066 }
04067
04068 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
04069 {
04070 int i;
04071 const char *p = str;
04072 for(i = 0;; i++) {
04073 dest[i] = atoi(p);
04074 if(i == 63)
04075 break;
04076 p = strchr(p, ',');
04077 if(!p) {
04078 fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
04079 ffmpeg_exit(1);
04080 }
04081 p++;
04082 }
04083 }
04084
04085 static int opt_inter_matrix(const char *opt, const char *arg)
04086 {
04087 inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
04088 parse_matrix_coeffs(inter_matrix, arg);
04089 return 0;
04090 }
04091
04092 static int opt_intra_matrix(const char *opt, const char *arg)
04093 {
04094 intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
04095 parse_matrix_coeffs(intra_matrix, arg);
04096 return 0;
04097 }
04098
04099 static void show_usage(void)
04100 {
04101 printf("Hyper fast Audio and Video encoder\n");
04102 printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
04103 printf("\n");
04104 }
04105
04106 static int opt_help(const char *opt, const char *arg)
04107 {
04108 AVCodec *c;
04109 AVOutputFormat *oformat = NULL;
04110
04111 av_log_set_callback(log_callback_help);
04112 show_usage();
04113 show_help_options(options, "Main options:\n",
04114 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
04115 show_help_options(options, "\nAdvanced options:\n",
04116 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
04117 OPT_EXPERT);
04118 show_help_options(options, "\nVideo options:\n",
04119 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04120 OPT_VIDEO);
04121 show_help_options(options, "\nAdvanced Video options:\n",
04122 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04123 OPT_VIDEO | OPT_EXPERT);
04124 show_help_options(options, "\nAudio options:\n",
04125 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04126 OPT_AUDIO);
04127 show_help_options(options, "\nAdvanced Audio options:\n",
04128 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04129 OPT_AUDIO | OPT_EXPERT);
04130 show_help_options(options, "\nSubtitle options:\n",
04131 OPT_SUBTITLE | OPT_GRAB,
04132 OPT_SUBTITLE);
04133 show_help_options(options, "\nAudio/Video grab options:\n",
04134 OPT_GRAB,
04135 OPT_GRAB);
04136 printf("\n");
04137 av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04138 printf("\n");
04139
04140
04141 c = NULL;
04142 while ((c = av_codec_next(c))) {
04143 if (c->priv_class) {
04144 av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04145 printf("\n");
04146 }
04147 }
04148
04149 av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04150 printf("\n");
04151
04152
04153 while ((oformat = av_oformat_next(oformat))) {
04154 if (oformat->priv_class) {
04155 av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
04156 printf("\n");
04157 }
04158 }
04159
04160 av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04161 return 0;
04162 }
04163
04164 static int opt_target(const char *opt, const char *arg)
04165 {
04166 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
04167 static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
04168
04169 if(!strncmp(arg, "pal-", 4)) {
04170 norm = PAL;
04171 arg += 4;
04172 } else if(!strncmp(arg, "ntsc-", 5)) {
04173 norm = NTSC;
04174 arg += 5;
04175 } else if(!strncmp(arg, "film-", 5)) {
04176 norm = FILM;
04177 arg += 5;
04178 } else {
04179 int fr;
04180
04181 fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
04182 if(fr == 25000) {
04183 norm = PAL;
04184 } else if((fr == 29970) || (fr == 23976)) {
04185 norm = NTSC;
04186 } else {
04187
04188 if(nb_input_files) {
04189 int i, j;
04190 for (j = 0; j < nb_input_files; j++) {
04191 for (i = 0; i < input_files[j].ctx->nb_streams; i++) {
04192 AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
04193 if(c->codec_type != AVMEDIA_TYPE_VIDEO)
04194 continue;
04195 fr = c->time_base.den * 1000 / c->time_base.num;
04196 if(fr == 25000) {
04197 norm = PAL;
04198 break;
04199 } else if((fr == 29970) || (fr == 23976)) {
04200 norm = NTSC;
04201 break;
04202 }
04203 }
04204 if(norm != UNKNOWN)
04205 break;
04206 }
04207 }
04208 }
04209 if(verbose > 0 && norm != UNKNOWN)
04210 fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
04211 }
04212
04213 if(norm == UNKNOWN) {
04214 fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
04215 fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
04216 fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
04217 ffmpeg_exit(1);
04218 }
04219
04220 if(!strcmp(arg, "vcd")) {
04221 opt_codec("vcodec", "mpeg1video");
04222 opt_codec("acodec", "mp2");
04223 opt_format("f", "vcd");
04224
04225 opt_frame_size("s", norm == PAL ? "352x288" : "352x240");
04226 opt_frame_rate("r", frame_rates[norm]);
04227 opt_default("g", norm == PAL ? "15" : "18");
04228
04229 opt_default("b", "1150000");
04230 opt_default("maxrate", "1150000");
04231 opt_default("minrate", "1150000");
04232 opt_default("bufsize", "327680");
04233
04234 opt_default("ab", "224000");
04235 audio_sample_rate = 44100;
04236 audio_channels = 2;
04237
04238 opt_default("packetsize", "2324");
04239 opt_default("muxrate", "1411200");
04240
04241
04242
04243
04244
04245
04246 mux_preload= (36000+3*1200) / 90000.0;
04247 } else if(!strcmp(arg, "svcd")) {
04248
04249 opt_codec("vcodec", "mpeg2video");
04250 opt_codec("acodec", "mp2");
04251 opt_format("f", "svcd");
04252
04253 opt_frame_size("s", norm == PAL ? "480x576" : "480x480");
04254 opt_frame_rate("r", frame_rates[norm]);
04255 opt_frame_pix_fmt("pix_fmt", "yuv420p");
04256 opt_default("g", norm == PAL ? "15" : "18");
04257
04258 opt_default("b", "2040000");
04259 opt_default("maxrate", "2516000");
04260 opt_default("minrate", "0");
04261 opt_default("bufsize", "1835008");
04262 opt_default("flags", "+scan_offset");
04263
04264
04265 opt_default("ab", "224000");
04266 audio_sample_rate = 44100;
04267
04268 opt_default("packetsize", "2324");
04269
04270 } else if(!strcmp(arg, "dvd")) {
04271
04272 opt_codec("vcodec", "mpeg2video");
04273 opt_codec("acodec", "ac3");
04274 opt_format("f", "dvd");
04275
04276 opt_frame_size("vcodec", norm == PAL ? "720x576" : "720x480");
04277 opt_frame_rate("r", frame_rates[norm]);
04278 opt_frame_pix_fmt("pix_fmt", "yuv420p");
04279 opt_default("g", norm == PAL ? "15" : "18");
04280
04281 opt_default("b", "6000000");
04282 opt_default("maxrate", "9000000");
04283 opt_default("minrate", "0");
04284 opt_default("bufsize", "1835008");
04285
04286 opt_default("packetsize", "2048");
04287 opt_default("muxrate", "10080000");
04288
04289 opt_default("ab", "448000");
04290 audio_sample_rate = 48000;
04291
04292 } else if(!strncmp(arg, "dv", 2)) {
04293
04294 opt_format("f", "dv");
04295
04296 opt_frame_size("s", norm == PAL ? "720x576" : "720x480");
04297 opt_frame_pix_fmt("pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
04298 norm == PAL ? "yuv420p" : "yuv411p");
04299 opt_frame_rate("r", frame_rates[norm]);
04300
04301 audio_sample_rate = 48000;
04302 audio_channels = 2;
04303
04304 } else {
04305 fprintf(stderr, "Unknown target: %s\n", arg);
04306 return AVERROR(EINVAL);
04307 }
04308 return 0;
04309 }
04310
04311 static int opt_vstats_file(const char *opt, const char *arg)
04312 {
04313 av_free (vstats_filename);
04314 vstats_filename=av_strdup (arg);
04315 return 0;
04316 }
04317
04318 static int opt_vstats(const char *opt, const char *arg)
04319 {
04320 char filename[40];
04321 time_t today2 = time(NULL);
04322 struct tm *today = localtime(&today2);
04323
04324 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
04325 today->tm_sec);
04326 return opt_vstats_file(opt, filename);
04327 }
04328
04329 static int opt_bsf(const char *opt, const char *arg)
04330 {
04331 AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg);
04332 AVBitStreamFilterContext **bsfp;
04333
04334 if(!bsfc){
04335 fprintf(stderr, "Unknown bitstream filter %s\n", arg);
04336 ffmpeg_exit(1);
04337 }
04338
04339 bsfp= *opt == 'v' ? &video_bitstream_filters :
04340 *opt == 'a' ? &audio_bitstream_filters :
04341 &subtitle_bitstream_filters;
04342 while(*bsfp)
04343 bsfp= &(*bsfp)->next;
04344
04345 *bsfp= bsfc;
04346
04347 return 0;
04348 }
04349
04350 static int opt_preset(const char *opt, const char *arg)
04351 {
04352 FILE *f=NULL;
04353 char filename[1000], tmp[1000], tmp2[1000], line[1000];
04354 char *codec_name = *opt == 'v' ? video_codec_name :
04355 *opt == 'a' ? audio_codec_name :
04356 subtitle_codec_name;
04357
04358 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
04359 fprintf(stderr, "File for preset '%s' not found\n", arg);
04360 ffmpeg_exit(1);
04361 }
04362
04363 while(!feof(f)){
04364 int e= fscanf(f, "%999[^\n]\n", line) - 1;
04365 if(line[0] == '#' && !e)
04366 continue;
04367 e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
04368 if(e){
04369 fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
04370 ffmpeg_exit(1);
04371 }
04372 if (!strcmp(tmp, "acodec") ||
04373 !strcmp(tmp, "vcodec") ||
04374 !strcmp(tmp, "scodec") ||
04375 !strcmp(tmp, "dcodec")) {
04376 opt_codec(tmp, tmp2);
04377 }else if(opt_default(tmp, tmp2) < 0){
04378 fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
04379 ffmpeg_exit(1);
04380 }
04381 }
04382
04383 fclose(f);
04384
04385 return 0;
04386 }
04387
04388 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
04389 {
04390 }
04391
04392 static int opt_passlogfile(const char *opt, const char *arg)
04393 {
04394 pass_logfilename_prefix = arg;
04395 #if CONFIG_LIBX264_ENCODER
04396 return opt_default("passlogfile", arg);
04397 #else
04398 return 0;
04399 #endif
04400 }
04401
04402 static const OptionDef options[] = {
04403
04404 #include "cmdutils_common_opts.h"
04405 { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
04406 { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
04407 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
04408 { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
04409 { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
04410 "outfile[,metadata]:infile[,metadata]" },
04411 { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
04412 "outfile[,metadata]:infile[,metadata]" },
04413 { "map_chapters", HAS_ARG | OPT_EXPERT, {(void*)opt_map_chapters}, "set chapters mapping", "outfile:infile" },
04414 { "t", HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
04415 { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" },
04416 { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
04417 { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
04418 { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
04419 { "timestamp", HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
04420 { "metadata", HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
04421 { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
04422 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
04423 "add timings for benchmarking" },
04424 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
04425 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
04426 "dump each input packet" },
04427 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
04428 "when dumping packets, also dump the payload" },
04429 { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
04430 { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
04431 { "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)", "" },
04432 { "v", HAS_ARG, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
04433 { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
04434 { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
04435 { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
04436 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
04437 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
04438 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
04439 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
04440 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" },
04441 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
04442 { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
04443 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
04444 { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)©_initial_nonkeyframes}, "copy initial non-keyframes" },
04445
04446
04447 { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04448 { "vb", HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04449 { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
04450 { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
04451 { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
04452 { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
04453 { "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" },
04454 { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
04455 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04456 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04457 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04458 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04459 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04460 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04461 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04462 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04463 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
04464 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
04465 { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
04466 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
04467 { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
04468 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
04469 { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_codec}, "force video codec ('copy' to copy stream)", "codec" },
04470 { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold", "threshold" },
04471 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
04472 "use same quantizer as source (implies VBR)" },
04473 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
04474 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
04475 { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
04476 "deinterlace pictures" },
04477 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
04478 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
04479 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
04480 #if CONFIG_AVFILTER
04481 { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
04482 #endif
04483 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
04484 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
04485 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
04486 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
04487 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
04488 { "newvideo", OPT_VIDEO, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
04489 { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
04490 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
04491 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
04492 { "streamid", HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
04493 { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
04494
04495
04496 { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04497 { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
04498 { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
04499 { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
04500 { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
04501 { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
04502 { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_codec}, "force audio codec ('copy' to copy stream)", "codec" },
04503 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
04504 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" },
04505 { "newaudio", OPT_AUDIO, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
04506 { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
04507 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_sample_fmt}, "set sample format, 'list' as argument shows all the sample formats supported", "format" },
04508
04509
04510 { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
04511 { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
04512 { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
04513 { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
04514 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
04515
04516
04517 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
04518 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
04519 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
04520
04521
04522 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
04523 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
04524
04525 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04526 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04527 { "sbsf", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04528
04529 { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
04530 { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
04531 { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
04532 { "fpre", HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
04533
04534 { "dcodec", HAS_ARG | OPT_DATA, {(void*)opt_codec}, "force data codec ('copy' to copy stream)", "codec" },
04535
04536 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
04537 { NULL, },
04538 };
04539
04540 int main(int argc, char **argv)
04541 {
04542 int64_t ti;
04543
04544 av_log_set_flags(AV_LOG_SKIP_REPEATED);
04545
04546 if(argc>1 && !strcmp(argv[1], "-d")){
04547 run_as_daemon=1;
04548 verbose=-1;
04549 av_log_set_callback(log_callback_null);
04550 argc--;
04551 argv++;
04552 }
04553
04554 avcodec_register_all();
04555 #if CONFIG_AVDEVICE
04556 avdevice_register_all();
04557 #endif
04558 #if CONFIG_AVFILTER
04559 avfilter_register_all();
04560 #endif
04561 av_register_all();
04562
04563 #if HAVE_ISATTY
04564 if(isatty(STDIN_FILENO))
04565 avio_set_interrupt_cb(decode_interrupt_cb);
04566 #endif
04567
04568 init_opts();
04569
04570 if(verbose>=0)
04571 show_banner();
04572
04573
04574 parse_options(argc, argv, options, opt_output_file);
04575
04576 if(nb_output_files <= 0 && nb_input_files == 0) {
04577 show_usage();
04578 fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
04579 ffmpeg_exit(1);
04580 }
04581
04582
04583 if (nb_output_files <= 0) {
04584 fprintf(stderr, "At least one output file must be specified\n");
04585 ffmpeg_exit(1);
04586 }
04587
04588 if (nb_input_files == 0) {
04589 fprintf(stderr, "At least one input file must be specified\n");
04590 ffmpeg_exit(1);
04591 }
04592
04593 ti = getutime();
04594 if (transcode(output_files, nb_output_files, input_files, nb_input_files,
04595 stream_maps, nb_stream_maps) < 0)
04596 ffmpeg_exit(1);
04597 ti = getutime() - ti;
04598 if (do_benchmark) {
04599 int maxrss = getmaxrss() / 1024;
04600 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
04601 }
04602
04603 return ffmpeg_exit(0);
04604 }