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