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