00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00026 #include "config.h"
00027 #include <ctype.h>
00028 #include <string.h>
00029 #include <math.h>
00030 #include <stdlib.h>
00031 #include <errno.h>
00032 #include <signal.h>
00033 #include <limits.h>
00034 #include <unistd.h>
00035 #include "libavformat/avformat.h"
00036 #include "libavdevice/avdevice.h"
00037 #include "libswscale/swscale.h"
00038 #include "libswresample/swresample.h"
00039 #include "libavutil/opt.h"
00040 #include "libavutil/audioconvert.h"
00041 #include "libavutil/parseutils.h"
00042 #include "libavutil/samplefmt.h"
00043 #include "libavutil/colorspace.h"
00044 #include "libavutil/fifo.h"
00045 #include "libavutil/intreadwrite.h"
00046 #include "libavutil/dict.h"
00047 #include "libavutil/mathematics.h"
00048 #include "libavutil/pixdesc.h"
00049 #include "libavutil/avstring.h"
00050 #include "libavutil/libm.h"
00051 #include "libavutil/imgutils.h"
00052 #include "libavutil/timestamp.h"
00053 #include "libavutil/bprint.h"
00054 #include "libavformat/os_support.h"
00055
00056 #include "libavformat/ffm.h"
00057
00058 # include "libavfilter/avcodec.h"
00059 # include "libavfilter/avfilter.h"
00060 # include "libavfilter/avfiltergraph.h"
00061 # include "libavfilter/buffersrc.h"
00062 # include "libavfilter/buffersink.h"
00063
00064 #if HAVE_SYS_RESOURCE_H
00065 #include <sys/types.h>
00066 #include <sys/time.h>
00067 #include <sys/resource.h>
00068 #elif HAVE_GETPROCESSTIMES
00069 #include <windows.h>
00070 #endif
00071 #if HAVE_GETPROCESSMEMORYINFO
00072 #include <windows.h>
00073 #include <psapi.h>
00074 #endif
00075
00076 #if HAVE_SYS_SELECT_H
00077 #include <sys/select.h>
00078 #endif
00079
00080 #if HAVE_TERMIOS_H
00081 #include <fcntl.h>
00082 #include <sys/ioctl.h>
00083 #include <sys/time.h>
00084 #include <termios.h>
00085 #elif HAVE_KBHIT
00086 #include <conio.h>
00087 #endif
00088 #include <time.h>
00089
00090 #include "cmdutils.h"
00091
00092 #include "libavutil/avassert.h"
00093
00094 #define VSYNC_AUTO -1
00095 #define VSYNC_PASSTHROUGH 0
00096 #define VSYNC_CFR 1
00097 #define VSYNC_VFR 2
00098 #define VSYNC_DROP 0xff
00099
00100 #define SINKA
00101
00102 const char program_name[] = "ffmpeg";
00103 const int program_birth_year = 2000;
00104
00105
00106 typedef struct StreamMap {
00107 int disabled;
00108 int file_index;
00109 int stream_index;
00110 int sync_file_index;
00111 int sync_stream_index;
00112 char *linklabel;
00113 } StreamMap;
00114
00115 typedef struct {
00116 int file_idx, stream_idx, channel_idx;
00117 int ofile_idx, ostream_idx;
00118 } AudioChannelMap;
00119
00120 static const OptionDef options[];
00121
00122 #define MAX_STREAMS 1024
00123
00124 static int frame_bits_per_raw_sample = 0;
00125 static int video_discard = 0;
00126 static int same_quant = 0;
00127 static int do_deinterlace = 0;
00128 static int intra_dc_precision = 8;
00129 static int qp_hist = 0;
00130 static int intra_only = 0;
00131 static const char *video_codec_name = NULL;
00132 static const char *audio_codec_name = NULL;
00133 static const char *subtitle_codec_name = NULL;
00134
00135 static int file_overwrite = 0;
00136 static int no_file_overwrite = 0;
00137 static int do_benchmark = 0;
00138 static int do_benchmark_all = 0;
00139 static int do_hex_dump = 0;
00140 static int do_pkt_dump = 0;
00141 static int do_psnr = 0;
00142 static int do_pass = 0;
00143 static const char *pass_logfilename_prefix;
00144 static int video_sync_method = VSYNC_AUTO;
00145 static int audio_sync_method = 0;
00146 static float audio_drift_threshold = 0.1;
00147 static int copy_ts = 0;
00148 static int copy_tb = -1;
00149 static int opt_shortest = 0;
00150 static char *vstats_filename;
00151 static FILE *vstats_file;
00152
00153 static int audio_volume = 256;
00154
00155 static int exit_on_error = 0;
00156 static int using_stdin = 0;
00157 static int run_as_daemon = 0;
00158 static volatile int received_nb_signals = 0;
00159 static int64_t video_size = 0;
00160 static int64_t audio_size = 0;
00161 static int64_t extra_size = 0;
00162 static int nb_frames_dup = 0;
00163 static int nb_frames_drop = 0;
00164 static int input_sync;
00165
00166 static float dts_delta_threshold = 10;
00167 static float dts_error_threshold = 3600*30;
00168
00169 static int print_stats = 1;
00170 static int debug_ts = 0;
00171 static int current_time;
00172
00173 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
00174
00175 typedef struct InputFilter {
00176 AVFilterContext *filter;
00177 struct InputStream *ist;
00178 struct FilterGraph *graph;
00179 } InputFilter;
00180
00181 typedef struct OutputFilter {
00182 AVFilterContext *filter;
00183 struct OutputStream *ost;
00184 struct FilterGraph *graph;
00185
00186
00187 AVFilterInOut *out_tmp;
00188 } OutputFilter;
00189
00190 typedef struct FilterGraph {
00191 int index;
00192 const char *graph_desc;
00193
00194 AVFilterGraph *graph;
00195
00196 InputFilter **inputs;
00197 int nb_inputs;
00198 OutputFilter **outputs;
00199 int nb_outputs;
00200 } FilterGraph;
00201
00202 typedef struct FrameBuffer {
00203 uint8_t *base[4];
00204 uint8_t *data[4];
00205 int linesize[4];
00206
00207 int h, w;
00208 enum PixelFormat pix_fmt;
00209
00210 int refcount;
00211 struct InputStream *ist;
00212 struct FrameBuffer *next;
00213 } FrameBuffer;
00214
00215 typedef struct InputStream {
00216 int file_index;
00217 AVStream *st;
00218 int discard;
00219 int decoding_needed;
00220 AVCodec *dec;
00221 AVFrame *decoded_frame;
00222
00223 int64_t start;
00224
00225
00226 int64_t next_dts;
00227
00228 int64_t dts;
00229
00230 int64_t next_pts;
00231 int64_t pts;
00232 double ts_scale;
00233 int is_start;
00234 int saw_first_ts;
00235 int showed_multi_packet_warning;
00236 AVDictionary *opts;
00237
00238 int resample_height;
00239 int resample_width;
00240 int resample_pix_fmt;
00241
00242 int resample_sample_fmt;
00243 int resample_sample_rate;
00244 int resample_channels;
00245 uint64_t resample_channel_layout;
00246
00247
00248 FrameBuffer *buffer_pool;
00249 int dr1;
00250
00251
00252
00253 InputFilter **filters;
00254 int nb_filters;
00255 } InputStream;
00256
00257 typedef struct InputFile {
00258 AVFormatContext *ctx;
00259 int eof_reached;
00260 int ist_index;
00261 int buffer_size;
00262 int64_t ts_offset;
00263 int nb_streams;
00264
00265 int rate_emu;
00266 } InputFile;
00267
00268 typedef struct OutputStream {
00269 int file_index;
00270 int index;
00271 int source_index;
00272 AVStream *st;
00273 int encoding_needed;
00274 int frame_number;
00275
00276
00277 struct InputStream *sync_ist;
00278 int64_t sync_opts;
00279
00280
00281 int64_t first_pts;
00282 AVBitStreamFilterContext *bitstream_filters;
00283 AVCodec *enc;
00284 int64_t max_frames;
00285 AVFrame *filtered_frame;
00286
00287
00288 AVRational frame_rate;
00289 int force_fps;
00290 int top_field_first;
00291
00292 float frame_aspect_ratio;
00293 float last_quality;
00294
00295
00296 int64_t *forced_kf_pts;
00297 int forced_kf_count;
00298 int forced_kf_index;
00299
00300
00301 int audio_channels_map[SWR_CH_MAX];
00302 int audio_channels_mapped;
00303
00304 FILE *logfile;
00305
00306 OutputFilter *filter;
00307 char *avfilter;
00308
00309 int64_t sws_flags;
00310 int64_t swr_dither_method;
00311 double swr_dither_scale;
00312 AVDictionary *opts;
00313 int is_past_recording_time;
00314 int stream_copy;
00315 const char *attachment_filename;
00316 int copy_initial_nonkeyframes;
00317
00318 int keep_pix_fmt;
00319 } OutputStream;
00320
00321
00322 #if HAVE_TERMIOS_H
00323
00324
00325 static struct termios oldtty;
00326 static int restore_tty;
00327 #endif
00328
00329 typedef struct OutputFile {
00330 AVFormatContext *ctx;
00331 AVDictionary *opts;
00332 int ost_index;
00333 int64_t recording_time;
00334 int64_t start_time;
00335 uint64_t limit_filesize;
00336 } OutputFile;
00337
00338 static InputStream **input_streams = NULL;
00339 static int nb_input_streams = 0;
00340 static InputFile **input_files = NULL;
00341 static int nb_input_files = 0;
00342
00343 static OutputStream **output_streams = NULL;
00344 static int nb_output_streams = 0;
00345 static OutputFile **output_files = NULL;
00346 static int nb_output_files = 0;
00347
00348 static FilterGraph **filtergraphs;
00349 int nb_filtergraphs;
00350
00351 typedef struct OptionsContext {
00352
00353 int64_t start_time;
00354 const char *format;
00355
00356 SpecifierOpt *codec_names;
00357 int nb_codec_names;
00358 SpecifierOpt *audio_channels;
00359 int nb_audio_channels;
00360 SpecifierOpt *audio_sample_rate;
00361 int nb_audio_sample_rate;
00362 SpecifierOpt *frame_rates;
00363 int nb_frame_rates;
00364 SpecifierOpt *frame_sizes;
00365 int nb_frame_sizes;
00366 SpecifierOpt *frame_pix_fmts;
00367 int nb_frame_pix_fmts;
00368
00369
00370 int64_t input_ts_offset;
00371 int rate_emu;
00372
00373 SpecifierOpt *ts_scale;
00374 int nb_ts_scale;
00375 SpecifierOpt *dump_attachment;
00376 int nb_dump_attachment;
00377
00378
00379 StreamMap *stream_maps;
00380 int nb_stream_maps;
00381 AudioChannelMap *audio_channel_maps;
00382 int nb_audio_channel_maps;
00383 int metadata_global_manual;
00384 int metadata_streams_manual;
00385 int metadata_chapters_manual;
00386 const char **attachments;
00387 int nb_attachments;
00388
00389 int chapters_input_file;
00390
00391 int64_t recording_time;
00392 uint64_t limit_filesize;
00393 float mux_preload;
00394 float mux_max_delay;
00395
00396 int video_disable;
00397 int audio_disable;
00398 int subtitle_disable;
00399 int data_disable;
00400
00401
00402 int *streamid_map;
00403 int nb_streamid_map;
00404
00405 SpecifierOpt *metadata;
00406 int nb_metadata;
00407 SpecifierOpt *max_frames;
00408 int nb_max_frames;
00409 SpecifierOpt *bitstream_filters;
00410 int nb_bitstream_filters;
00411 SpecifierOpt *codec_tags;
00412 int nb_codec_tags;
00413 SpecifierOpt *sample_fmts;
00414 int nb_sample_fmts;
00415 SpecifierOpt *qscale;
00416 int nb_qscale;
00417 SpecifierOpt *forced_key_frames;
00418 int nb_forced_key_frames;
00419 SpecifierOpt *force_fps;
00420 int nb_force_fps;
00421 SpecifierOpt *frame_aspect_ratios;
00422 int nb_frame_aspect_ratios;
00423 SpecifierOpt *rc_overrides;
00424 int nb_rc_overrides;
00425 SpecifierOpt *intra_matrices;
00426 int nb_intra_matrices;
00427 SpecifierOpt *inter_matrices;
00428 int nb_inter_matrices;
00429 SpecifierOpt *top_field_first;
00430 int nb_top_field_first;
00431 SpecifierOpt *metadata_map;
00432 int nb_metadata_map;
00433 SpecifierOpt *presets;
00434 int nb_presets;
00435 SpecifierOpt *copy_initial_nonkeyframes;
00436 int nb_copy_initial_nonkeyframes;
00437 SpecifierOpt *filters;
00438 int nb_filters;
00439 } OptionsContext;
00440
00441 static void do_video_stats(AVFormatContext *os, OutputStream *ost, int frame_size);
00442
00443 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
00444 {\
00445 int i, ret;\
00446 for (i = 0; i < o->nb_ ## name; i++) {\
00447 char *spec = o->name[i].specifier;\
00448 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
00449 outvar = o->name[i].u.type;\
00450 else if (ret < 0)\
00451 exit_program(1);\
00452 }\
00453 }
00454
00455 static int64_t getutime(void)
00456 {
00457 #if HAVE_GETRUSAGE
00458 struct rusage rusage;
00459
00460 getrusage(RUSAGE_SELF, &rusage);
00461 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
00462 #elif HAVE_GETPROCESSTIMES
00463 HANDLE proc;
00464 FILETIME c, e, k, u;
00465 proc = GetCurrentProcess();
00466 GetProcessTimes(proc, &c, &e, &k, &u);
00467 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
00468 #else
00469 return av_gettime();
00470 #endif
00471 }
00472
00473 static void update_benchmark(const char *fmt, ...)
00474 {
00475 if (do_benchmark_all) {
00476 int64_t t = getutime();
00477 va_list va;
00478 char buf[1024];
00479
00480 if (fmt) {
00481 va_start(va, fmt);
00482 vsnprintf(buf, sizeof(buf), fmt, va);
00483 va_end(va);
00484 printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
00485 }
00486 current_time = t;
00487 }
00488 }
00489
00490 static void reset_options(OptionsContext *o, int is_input)
00491 {
00492 const OptionDef *po = options;
00493 OptionsContext bak= *o;
00494 int i;
00495
00496
00497 while (po->name) {
00498 void *dst = (uint8_t*)o + po->u.off;
00499
00500 if (po->flags & OPT_SPEC) {
00501 SpecifierOpt **so = dst;
00502 int i, *count = (int*)(so + 1);
00503 for (i = 0; i < *count; i++) {
00504 av_freep(&(*so)[i].specifier);
00505 if (po->flags & OPT_STRING)
00506 av_freep(&(*so)[i].u.str);
00507 }
00508 av_freep(so);
00509 *count = 0;
00510 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
00511 av_freep(dst);
00512 po++;
00513 }
00514
00515 for (i = 0; i < o->nb_stream_maps; i++)
00516 av_freep(&o->stream_maps[i].linklabel);
00517 av_freep(&o->stream_maps);
00518 av_freep(&o->audio_channel_maps);
00519 av_freep(&o->streamid_map);
00520
00521 memset(o, 0, sizeof(*o));
00522
00523 if(is_input) o->recording_time = bak.recording_time;
00524 else o->recording_time = INT64_MAX;
00525 o->mux_max_delay = 0.7;
00526 o->limit_filesize = UINT64_MAX;
00527 o->chapters_input_file = INT_MAX;
00528
00529 uninit_opts();
00530 init_opts();
00531 }
00532
00533 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
00534 {
00535 FrameBuffer *buf = av_mallocz(sizeof(*buf));
00536 int i, ret;
00537 const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
00538 int h_chroma_shift, v_chroma_shift;
00539 int edge = 32;
00540 int w = s->width, h = s->height;
00541
00542 if (!buf)
00543 return AVERROR(ENOMEM);
00544
00545 avcodec_align_dimensions(s, &w, &h);
00546
00547 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
00548 w += 2*edge;
00549 h += 2*edge;
00550 }
00551
00552 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
00553 s->pix_fmt, 32)) < 0) {
00554 av_freep(&buf);
00555 return ret;
00556 }
00557
00558
00559
00560
00561
00562 memset(buf->base[0], 128, ret);
00563
00564 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
00565 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
00566 const int h_shift = i==0 ? 0 : h_chroma_shift;
00567 const int v_shift = i==0 ? 0 : v_chroma_shift;
00568 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1] || !buf->base[i])
00569 buf->data[i] = buf->base[i];
00570 else
00571 buf->data[i] = buf->base[i] +
00572 FFALIGN((buf->linesize[i]*edge >> v_shift) +
00573 (pixel_size*edge >> h_shift), 32);
00574 }
00575 buf->w = s->width;
00576 buf->h = s->height;
00577 buf->pix_fmt = s->pix_fmt;
00578 buf->ist = ist;
00579
00580 *pbuf = buf;
00581 return 0;
00582 }
00583
00584 static void free_buffer_pool(InputStream *ist)
00585 {
00586 FrameBuffer *buf = ist->buffer_pool;
00587 while (buf) {
00588 ist->buffer_pool = buf->next;
00589 av_freep(&buf->base[0]);
00590 av_free(buf);
00591 buf = ist->buffer_pool;
00592 }
00593 }
00594
00595 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
00596 {
00597 av_assert0(buf->refcount > 0);
00598 buf->refcount--;
00599 if (!buf->refcount) {
00600 FrameBuffer *tmp;
00601 for(tmp= ist->buffer_pool; tmp; tmp= tmp->next)
00602 av_assert1(tmp != buf);
00603 buf->next = ist->buffer_pool;
00604 ist->buffer_pool = buf;
00605 }
00606 }
00607
00608 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
00609 {
00610 InputStream *ist = s->opaque;
00611 FrameBuffer *buf;
00612 int ret, i;
00613
00614 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
00615 return -1;
00616
00617 if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
00618 return ret;
00619
00620 buf = ist->buffer_pool;
00621 ist->buffer_pool = buf->next;
00622 buf->next = NULL;
00623 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
00624 av_freep(&buf->base[0]);
00625 av_free(buf);
00626 if ((ret = alloc_buffer(ist, s, &buf)) < 0)
00627 return ret;
00628 }
00629 av_assert0(!buf->refcount);
00630 buf->refcount++;
00631
00632 frame->opaque = buf;
00633 frame->type = FF_BUFFER_TYPE_USER;
00634 frame->extended_data = frame->data;
00635 frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
00636 frame->width = buf->w;
00637 frame->height = buf->h;
00638 frame->format = buf->pix_fmt;
00639 frame->sample_aspect_ratio = s->sample_aspect_ratio;
00640
00641 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
00642 frame->base[i] = buf->base[i];
00643 frame->data[i] = buf->data[i];
00644 frame->linesize[i] = buf->linesize[i];
00645 }
00646
00647 return 0;
00648 }
00649
00650 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
00651 {
00652 InputStream *ist = s->opaque;
00653 FrameBuffer *buf = frame->opaque;
00654 int i;
00655
00656 if(frame->type!=FF_BUFFER_TYPE_USER)
00657 return avcodec_default_release_buffer(s, frame);
00658
00659 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
00660 frame->data[i] = NULL;
00661
00662 unref_buffer(ist, buf);
00663 }
00664
00665 static void filter_release_buffer(AVFilterBuffer *fb)
00666 {
00667 FrameBuffer *buf = fb->priv;
00668 av_free(fb);
00669 unref_buffer(buf->ist, buf);
00670 }
00671
00672 static enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
00673 {
00674 if (codec && codec->pix_fmts) {
00675 const enum PixelFormat *p = codec->pix_fmts;
00676 int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
00677 enum PixelFormat best= PIX_FMT_NONE;
00678 if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
00679 if (st->codec->codec_id == CODEC_ID_MJPEG) {
00680 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
00681 } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
00682 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
00683 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
00684 }
00685 }
00686 for (; *p != PIX_FMT_NONE; p++) {
00687 best= avcodec_find_best_pix_fmt2(best, *p, target, has_alpha, NULL);
00688 if (*p == target)
00689 break;
00690 }
00691 if (*p == PIX_FMT_NONE) {
00692 if (target != PIX_FMT_NONE)
00693 av_log(NULL, AV_LOG_WARNING,
00694 "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
00695 av_pix_fmt_descriptors[target].name,
00696 codec->name,
00697 av_pix_fmt_descriptors[best].name);
00698 return best;
00699 }
00700 }
00701 return target;
00702 }
00703
00704 static char *choose_pix_fmts(OutputStream *ost)
00705 {
00706 if (ost->keep_pix_fmt) {
00707 if (ost->filter)
00708 avfilter_graph_set_auto_convert(ost->filter->graph->graph,
00709 AVFILTER_AUTO_CONVERT_NONE);
00710 if (ost->st->codec->pix_fmt == PIX_FMT_NONE)
00711 return NULL;
00712 return av_strdup(av_get_pix_fmt_name(ost->st->codec->pix_fmt));
00713 }
00714 if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
00715 return av_strdup(av_get_pix_fmt_name(choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt)));
00716 } else if (ost->enc && ost->enc->pix_fmts) {
00717 const enum PixelFormat *p;
00718 AVIOContext *s = NULL;
00719 uint8_t *ret;
00720 int len;
00721
00722 if (avio_open_dyn_buf(&s) < 0)
00723 exit_program(1);
00724
00725 p = ost->enc->pix_fmts;
00726 if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
00727 if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
00728 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
00729 } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
00730 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
00731 PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
00732 }
00733 }
00734
00735 for (; *p != PIX_FMT_NONE; p++) {
00736 const char *name = av_get_pix_fmt_name(*p);
00737 avio_printf(s, "%s:", name);
00738 }
00739 len = avio_close_dyn_buf(s, &ret);
00740 ret[len - 1] = 0;
00741 return ret;
00742 } else
00743 return NULL;
00744 }
00745
00750 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
00751 static char *choose_ ## var ## s(OutputStream *ost) \
00752 { \
00753 if (ost->st->codec->var != none) { \
00754 get_name(ost->st->codec->var); \
00755 return av_strdup(name); \
00756 } else if (ost->enc->supported_list) { \
00757 const type *p; \
00758 AVIOContext *s = NULL; \
00759 uint8_t *ret; \
00760 int len; \
00761 \
00762 if (avio_open_dyn_buf(&s) < 0) \
00763 exit_program(1); \
00764 \
00765 for (p = ost->enc->supported_list; *p != none; p++) { \
00766 get_name(*p); \
00767 avio_printf(s, "%s" separator, name); \
00768 } \
00769 len = avio_close_dyn_buf(s, &ret); \
00770 ret[len - 1] = 0; \
00771 return ret; \
00772 } else \
00773 return NULL; \
00774 }
00775
00776 #define GET_PIX_FMT_NAME(pix_fmt)\
00777 const char *name = av_get_pix_fmt_name(pix_fmt);
00778
00779
00780
00781
00782 #define GET_SAMPLE_FMT_NAME(sample_fmt)\
00783 const char *name = av_get_sample_fmt_name(sample_fmt)
00784
00785 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
00786 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
00787
00788 #define GET_SAMPLE_RATE_NAME(rate)\
00789 char name[16];\
00790 snprintf(name, sizeof(name), "%d", rate);
00791
00792 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
00793 GET_SAMPLE_RATE_NAME, ",")
00794
00795 #define GET_CH_LAYOUT_NAME(ch_layout)\
00796 char name[16];\
00797 snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
00798
00799 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
00800 GET_CH_LAYOUT_NAME, ",")
00801
00802 static int configure_audio_filters(FilterGraph *fg, AVFilterContext **in_filter,
00803 AVFilterContext **out_filter)
00804 {
00805 InputStream *ist = fg->inputs[0]->ist;
00806 OutputStream *ost = fg->outputs[0]->ost;
00807 AVCodecContext *codec = ost->st->codec;
00808 AVCodecContext *icodec = ist->st->codec;
00809 char *sample_fmts, *sample_rates, *channel_layouts;
00810 char args[256];
00811 int ret;
00812
00813 avfilter_graph_free(&fg->graph);
00814 if (!(fg->graph = avfilter_graph_alloc()))
00815 return AVERROR(ENOMEM);
00816
00817 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:"
00818 "channel_layout=0x%"PRIx64, ist->st->time_base.num,
00819 ist->st->time_base.den, icodec->sample_rate,
00820 av_get_sample_fmt_name(icodec->sample_fmt), icodec->channel_layout);
00821 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
00822 avfilter_get_by_name("abuffer"),
00823 "src", args, NULL, fg->graph);
00824 if (ret < 0)
00825 return ret;
00826
00827 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
00828 avfilter_get_by_name("abuffersink_old"),
00829 "out", NULL, NULL, fg->graph);
00830 if (ret < 0)
00831 return ret;
00832
00833 *in_filter = fg->inputs[0]->filter;
00834 *out_filter = fg->outputs[0]->filter;
00835
00836 if (codec->channels && !codec->channel_layout)
00837 codec->channel_layout = av_get_default_channel_layout(codec->channels);
00838
00839 sample_fmts = choose_sample_fmts(ost);
00840 sample_rates = choose_sample_rates(ost);
00841 channel_layouts = choose_channel_layouts(ost);
00842 if (sample_fmts || sample_rates || channel_layouts) {
00843 AVFilterContext *format;
00844 char args[256];
00845 int len = 0;
00846
00847 if (sample_fmts)
00848 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
00849 sample_fmts);
00850 if (sample_rates)
00851 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
00852 sample_rates);
00853 if (channel_layouts)
00854 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
00855 channel_layouts);
00856 args[len - 1] = 0;
00857
00858 av_freep(&sample_fmts);
00859 av_freep(&sample_rates);
00860 av_freep(&channel_layouts);
00861
00862 ret = avfilter_graph_create_filter(&format,
00863 avfilter_get_by_name("aformat"),
00864 "aformat", args, NULL, fg->graph);
00865 if (ret < 0)
00866 return ret;
00867
00868 ret = avfilter_link(format, 0, fg->outputs[0]->filter, 0);
00869 if (ret < 0)
00870 return ret;
00871
00872 *out_filter = format;
00873 }
00874
00875 #define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do { \
00876 AVFilterContext *filt_ctx; \
00877 \
00878 av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi " \
00879 "similarly to -af " filter_name "=%s.\n", arg); \
00880 \
00881 ret = avfilter_graph_create_filter(&filt_ctx, \
00882 avfilter_get_by_name(filter_name), \
00883 filter_name, arg, NULL, fg->graph); \
00884 if (ret < 0) \
00885 return ret; \
00886 \
00887 ret = avfilter_link(*in_filter, 0, filt_ctx, 0); \
00888 if (ret < 0) \
00889 return ret; \
00890 \
00891 *in_filter = filt_ctx; \
00892 } while (0)
00893
00894 if (audio_sync_method > 0) {
00895 char args[256] = {0};
00896
00897 av_strlcatf(args, sizeof(args), "min_comp=0.001:min_hard_comp=%f", audio_drift_threshold);
00898 if (audio_sync_method > 1)
00899 av_strlcatf(args, sizeof(args), ":max_soft_comp=%f", audio_sync_method/(double)icodec->sample_rate);
00900 AUTO_INSERT_FILTER("-async", "aresample", args);
00901 }
00902
00903 if (ost->audio_channels_mapped) {
00904 int i;
00905 AVBPrint pan_buf;
00906
00907 av_bprint_init(&pan_buf, 256, 8192);
00908 av_bprintf(&pan_buf, "0x%"PRIx64,
00909 av_get_default_channel_layout(ost->audio_channels_mapped));
00910 for (i = 0; i < ost->audio_channels_mapped; i++)
00911 if (ost->audio_channels_map[i] != -1)
00912 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
00913
00914 AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);
00915 av_bprint_finalize(&pan_buf, NULL);
00916 }
00917
00918 if (audio_volume != 256) {
00919 char args[256];
00920
00921 snprintf(args, sizeof(args), "%lf", audio_volume / 256.);
00922 AUTO_INSERT_FILTER("-vol", "volume", args);
00923 }
00924
00925 return 0;
00926 }
00927
00928 static int configure_video_filters(FilterGraph *fg, AVFilterContext **in_filter,
00929 AVFilterContext **out_filter)
00930 {
00931 InputStream *ist = fg->inputs[0]->ist;
00932 OutputStream *ost = fg->outputs[0]->ost;
00933 AVFilterContext *filter;
00934 AVCodecContext *codec = ost->st->codec;
00935 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
00936 char *pix_fmts;
00937 AVRational sample_aspect_ratio;
00938 char args[255];
00939 int ret;
00940
00941 if (ist->st->sample_aspect_ratio.num) {
00942 sample_aspect_ratio = ist->st->sample_aspect_ratio;
00943 } else
00944 sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
00945
00946 snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
00947 ist->st->codec->height, ist->st->codec->pix_fmt,
00948 ist->st->time_base.num, ist->st->time_base.den,
00949 sample_aspect_ratio.num, sample_aspect_ratio.den,
00950 SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
00951
00952 ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
00953 avfilter_get_by_name("buffer"),
00954 "src", args, NULL, fg->graph);
00955 if (ret < 0)
00956 return ret;
00957
00958 #if FF_API_OLD_VSINK_API
00959 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
00960 avfilter_get_by_name("buffersink"),
00961 "out", NULL, NULL, fg->graph);
00962 #else
00963 ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
00964 avfilter_get_by_name("buffersink"),
00965 "out", NULL, buffersink_params, fg->graph);
00966 #endif
00967 av_freep(&buffersink_params);
00968
00969 if (ret < 0)
00970 return ret;
00971 *in_filter = fg->inputs[0]->filter;
00972 *out_filter = fg->outputs[0]->filter;
00973
00974 if (codec->width || codec->height) {
00975 snprintf(args, 255, "%d:%d:flags=0x%X",
00976 codec->width,
00977 codec->height,
00978 (unsigned)ost->sws_flags);
00979 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
00980 NULL, args, NULL, fg->graph)) < 0)
00981 return ret;
00982 if ((ret = avfilter_link(*in_filter, 0, filter, 0)) < 0)
00983 return ret;
00984 *in_filter = filter;
00985 }
00986
00987 if ((pix_fmts = choose_pix_fmts(ost))) {
00988 if ((ret = avfilter_graph_create_filter(&filter,
00989 avfilter_get_by_name("format"),
00990 "format", pix_fmts, NULL,
00991 fg->graph)) < 0)
00992 return ret;
00993 if ((ret = avfilter_link(filter, 0, *out_filter, 0)) < 0)
00994 return ret;
00995
00996 *out_filter = filter;
00997 av_freep(&pix_fmts);
00998 }
00999
01000 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
01001 fg->graph->scale_sws_opts = av_strdup(args);
01002
01003 return 0;
01004 }
01005
01006 static int configure_simple_filtergraph(FilterGraph *fg)
01007 {
01008 OutputStream *ost = fg->outputs[0]->ost;
01009 AVFilterContext *in_filter, *out_filter;
01010 int ret;
01011
01012 avfilter_graph_free(&fg->graph);
01013 fg->graph = avfilter_graph_alloc();
01014 if (!fg->graph)
01015 return AVERROR(ENOMEM);
01016
01017 switch (ost->st->codec->codec_type) {
01018 case AVMEDIA_TYPE_VIDEO:
01019 ret = configure_video_filters(fg, &in_filter, &out_filter);
01020 break;
01021 case AVMEDIA_TYPE_AUDIO:
01022 ret = configure_audio_filters(fg, &in_filter, &out_filter);
01023 break;
01024 default: av_assert0(0);
01025 }
01026 if (ret < 0)
01027 return ret;
01028
01029 if (ost->avfilter) {
01030 AVFilterInOut *outputs = avfilter_inout_alloc();
01031 AVFilterInOut *inputs = avfilter_inout_alloc();
01032
01033 outputs->name = av_strdup("in");
01034 outputs->filter_ctx = in_filter;
01035 outputs->pad_idx = 0;
01036 outputs->next = NULL;
01037
01038 inputs->name = av_strdup("out");
01039 inputs->filter_ctx = out_filter;
01040 inputs->pad_idx = 0;
01041 inputs->next = NULL;
01042
01043 if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
01044 return ret;
01045 av_freep(&ost->avfilter);
01046 } else {
01047 if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)
01048 return ret;
01049 }
01050
01051 if (ost->keep_pix_fmt)
01052 avfilter_graph_set_auto_convert(fg->graph,
01053 AVFILTER_AUTO_CONVERT_NONE);
01054
01055 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
01056 return ret;
01057
01058 ost->filter = fg->outputs[0];
01059
01060 return 0;
01061 }
01062
01063 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
01064 {
01065 FilterGraph *fg = av_mallocz(sizeof(*fg));
01066
01067 if (!fg)
01068 exit_program(1);
01069 fg->index = nb_filtergraphs;
01070
01071 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
01072 fg->nb_outputs + 1);
01073 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
01074 exit_program(1);
01075 fg->outputs[0]->ost = ost;
01076 fg->outputs[0]->graph = fg;
01077
01078 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
01079 fg->nb_inputs + 1);
01080 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
01081 exit_program(1);
01082 fg->inputs[0]->ist = ist;
01083 fg->inputs[0]->graph = fg;
01084
01085 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
01086 &ist->nb_filters, ist->nb_filters + 1);
01087 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
01088
01089 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
01090 &nb_filtergraphs, nb_filtergraphs + 1);
01091 filtergraphs[nb_filtergraphs - 1] = fg;
01092
01093 return fg;
01094 }
01095
01096 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
01097 {
01098 InputStream *ist = NULL;
01099 enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
01100 int i;
01101
01102
01103 if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
01104 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
01105 "currently.\n");
01106 exit_program(1);
01107 }
01108
01109 if (in->name) {
01110 AVFormatContext *s;
01111 AVStream *st = NULL;
01112 char *p;
01113 int file_idx = strtol(in->name, &p, 0);
01114
01115 if (file_idx < 0 || file_idx >= nb_input_files) {
01116 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtergraph description %s.\n",
01117 file_idx, fg->graph_desc);
01118 exit_program(1);
01119 }
01120 s = input_files[file_idx]->ctx;
01121
01122 for (i = 0; i < s->nb_streams; i++) {
01123 if (s->streams[i]->codec->codec_type != type)
01124 continue;
01125 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
01126 st = s->streams[i];
01127 break;
01128 }
01129 }
01130 if (!st) {
01131 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
01132 "matches no streams.\n", p, fg->graph_desc);
01133 exit_program(1);
01134 }
01135 ist = input_streams[input_files[file_idx]->ist_index + st->index];
01136 } else {
01137
01138 for (i = 0; i < nb_input_streams; i++) {
01139 ist = input_streams[i];
01140 if (ist->st->codec->codec_type == type && ist->discard)
01141 break;
01142 }
01143 if (i == nb_input_streams) {
01144 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
01145 "unlabeled input pad %d on filter %s", in->pad_idx,
01146 in->filter_ctx->name);
01147 exit_program(1);
01148 }
01149 }
01150 ist->discard = 0;
01151 ist->decoding_needed = 1;
01152 ist->st->discard = AVDISCARD_NONE;
01153
01154 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
01155 &fg->nb_inputs, fg->nb_inputs + 1);
01156 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
01157 exit_program(1);
01158 fg->inputs[fg->nb_inputs - 1]->ist = ist;
01159 fg->inputs[fg->nb_inputs - 1]->graph = fg;
01160
01161 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
01162 &ist->nb_filters, ist->nb_filters + 1);
01163 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
01164 }
01165
01166 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
01167 {
01168 char *pix_fmts;
01169 AVCodecContext *codec = ofilter->ost->st->codec;
01170 AVFilterContext *last_filter = out->filter_ctx;
01171 int pad_idx = out->pad_idx;
01172 int ret;
01173 AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
01174
01175 #if FF_API_OLD_VSINK_API
01176 ret = avfilter_graph_create_filter(&ofilter->filter,
01177 avfilter_get_by_name("buffersink"),
01178 "out", NULL, NULL, fg->graph);
01179 #else
01180 ret = avfilter_graph_create_filter(&ofilter->filter,
01181 avfilter_get_by_name("buffersink"),
01182 "out", NULL, buffersink_params, fg->graph);
01183 #endif
01184 av_freep(&buffersink_params);
01185
01186 if (ret < 0)
01187 return ret;
01188
01189 if (codec->width || codec->height) {
01190 char args[255];
01191 AVFilterContext *filter;
01192
01193 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
01194 codec->width,
01195 codec->height,
01196 (unsigned)ofilter->ost->sws_flags);
01197 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
01198 NULL, args, NULL, fg->graph)) < 0)
01199 return ret;
01200 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
01201 return ret;
01202
01203 last_filter = filter;
01204 pad_idx = 0;
01205 }
01206
01207 if ((pix_fmts = choose_pix_fmts(ofilter->ost))) {
01208 AVFilterContext *filter;
01209 if ((ret = avfilter_graph_create_filter(&filter,
01210 avfilter_get_by_name("format"),
01211 "format", pix_fmts, NULL,
01212 fg->graph)) < 0)
01213 return ret;
01214 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
01215 return ret;
01216
01217 last_filter = filter;
01218 pad_idx = 0;
01219 av_freep(&pix_fmts);
01220 }
01221
01222 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
01223 return ret;
01224
01225 return 0;
01226 }
01227
01228 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
01229 {
01230 OutputStream *ost = ofilter->ost;
01231 AVCodecContext *codec = ost->st->codec;
01232 AVFilterContext *last_filter = out->filter_ctx;
01233 int pad_idx = out->pad_idx;
01234 char *sample_fmts, *sample_rates, *channel_layouts;
01235 int ret;
01236
01237 ret = avfilter_graph_create_filter(&ofilter->filter,
01238 avfilter_get_by_name("abuffersink"),
01239 "out", NULL, NULL, fg->graph);
01240 if (ret < 0)
01241 return ret;
01242
01243 if (codec->channels && !codec->channel_layout)
01244 codec->channel_layout = av_get_default_channel_layout(codec->channels);
01245
01246 sample_fmts = choose_sample_fmts(ost);
01247 sample_rates = choose_sample_rates(ost);
01248 channel_layouts = choose_channel_layouts(ost);
01249 if (sample_fmts || sample_rates || channel_layouts) {
01250 AVFilterContext *format;
01251 char args[256];
01252 int len = 0;
01253
01254 if (sample_fmts)
01255 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
01256 sample_fmts);
01257 if (sample_rates)
01258 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
01259 sample_rates);
01260 if (channel_layouts)
01261 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
01262 channel_layouts);
01263 args[len - 1] = 0;
01264
01265 av_freep(&sample_fmts);
01266 av_freep(&sample_rates);
01267 av_freep(&channel_layouts);
01268
01269 ret = avfilter_graph_create_filter(&format,
01270 avfilter_get_by_name("aformat"),
01271 "aformat", args, NULL, fg->graph);
01272 if (ret < 0)
01273 return ret;
01274
01275 ret = avfilter_link(last_filter, pad_idx, format, 0);
01276 if (ret < 0)
01277 return ret;
01278
01279 last_filter = format;
01280 pad_idx = 0;
01281 }
01282
01283 if (audio_sync_method > 0) {
01284 AVFilterContext *async;
01285 char args[256];
01286 int len = 0;
01287
01288 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
01289 "asyncts audio filter instead.\n");
01290
01291 if (audio_sync_method > 1)
01292 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
01293 "max_comp=%d:", audio_sync_method);
01294 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
01295 audio_drift_threshold);
01296
01297 ret = avfilter_graph_create_filter(&async,
01298 avfilter_get_by_name("asyncts"),
01299 "async", args, NULL, fg->graph);
01300 if (ret < 0)
01301 return ret;
01302
01303 ret = avfilter_link(last_filter, pad_idx, async, 0);
01304 if (ret < 0)
01305 return ret;
01306
01307 last_filter = async;
01308 pad_idx = 0;
01309 }
01310
01311 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
01312 return ret;
01313
01314 return 0;
01315 }
01316
01317 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
01318 {
01319 switch (out->filter_ctx->output_pads[out->pad_idx].type) {
01320 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
01321 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
01322 default: av_assert0(0);
01323 }
01324 }
01325
01326 static int configure_complex_filter(FilterGraph *fg)
01327 {
01328 AVFilterInOut *inputs, *outputs, *cur;
01329 int ret, i, init = !fg->graph;
01330
01331 avfilter_graph_free(&fg->graph);
01332 if (!(fg->graph = avfilter_graph_alloc()))
01333 return AVERROR(ENOMEM);
01334
01335 if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
01336 return ret;
01337
01338 for (cur = inputs; init && cur; cur = cur->next)
01339 init_input_filter(fg, cur);
01340
01341 for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
01342 InputFilter *ifilter = fg->inputs[i];
01343 InputStream *ist = ifilter->ist;
01344 AVRational sar;
01345 AVFilter *filter;
01346 char args[255];
01347
01348 switch (cur->filter_ctx->input_pads[cur->pad_idx].type) {
01349 case AVMEDIA_TYPE_VIDEO:
01350 sar = ist->st->sample_aspect_ratio.num ?
01351 ist->st->sample_aspect_ratio :
01352 ist->st->codec->sample_aspect_ratio;
01353 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
01354 ist->st->codec->height, ist->st->codec->pix_fmt,
01355 ist->st->time_base.num, ist->st->time_base.den,
01356 sar.num, sar.den);
01357 filter = avfilter_get_by_name("buffer");
01358 break;
01359 case AVMEDIA_TYPE_AUDIO:
01360 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:"
01361 "sample_fmt=%s:channel_layout=0x%"PRIx64,
01362 ist->st->time_base.num, ist->st->time_base.den,
01363 ist->st->codec->sample_rate,
01364 av_get_sample_fmt_name(ist->st->codec->sample_fmt),
01365 ist->st->codec->channel_layout);
01366 filter = avfilter_get_by_name("abuffer");
01367 break;
01368 default:
01369 av_assert0(0);
01370 }
01371
01372 if ((ret = avfilter_graph_create_filter(&ifilter->filter,
01373 filter, cur->name,
01374 args, NULL, fg->graph)) < 0)
01375 return ret;
01376 if ((ret = avfilter_link(ifilter->filter, 0,
01377 cur->filter_ctx, cur->pad_idx)) < 0)
01378 return ret;
01379 }
01380 avfilter_inout_free(&inputs);
01381
01382 if (!init) {
01383
01384
01385 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
01386 configure_output_filter(fg, fg->outputs[i], cur);
01387 avfilter_inout_free(&outputs);
01388
01389 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
01390 return ret;
01391 } else {
01392
01393 for (cur = outputs; cur;) {
01394 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
01395 &fg->nb_outputs, fg->nb_outputs + 1);
01396 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
01397 exit_program(1);
01398 fg->outputs[fg->nb_outputs - 1]->graph = fg;
01399 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
01400 cur = cur->next;
01401 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
01402 }
01403 }
01404
01405 return 0;
01406 }
01407
01408 static int configure_complex_filters(void)
01409 {
01410 int i, ret = 0;
01411
01412 for (i = 0; i < nb_filtergraphs; i++)
01413 if (!filtergraphs[i]->graph &&
01414 (ret = configure_complex_filter(filtergraphs[i])) < 0)
01415 return ret;
01416 return 0;
01417 }
01418
01419 static int configure_filtergraph(FilterGraph *fg)
01420 {
01421 return fg->graph_desc ? configure_complex_filter(fg) :
01422 configure_simple_filtergraph(fg);
01423 }
01424
01425 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
01426 {
01427 int i;
01428 for (i = 0; i < fg->nb_inputs; i++)
01429 if (fg->inputs[i]->ist == ist)
01430 return 1;
01431 return 0;
01432 }
01433
01434 static void term_exit(void)
01435 {
01436 av_log(NULL, AV_LOG_QUIET, "%s", "");
01437 #if HAVE_TERMIOS_H
01438 if(restore_tty)
01439 tcsetattr (0, TCSANOW, &oldtty);
01440 #endif
01441 }
01442
01443 static volatile int received_sigterm = 0;
01444
01445 static void sigterm_handler(int sig)
01446 {
01447 received_sigterm = sig;
01448 received_nb_signals++;
01449 term_exit();
01450 if(received_nb_signals > 3)
01451 exit(123);
01452 }
01453
01454 static void term_init(void)
01455 {
01456 #if HAVE_TERMIOS_H
01457 if(!run_as_daemon){
01458 struct termios tty;
01459
01460 if (tcgetattr (0, &tty) == 0) {
01461 oldtty = tty;
01462 restore_tty = 1;
01463 atexit(term_exit);
01464
01465 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
01466 |INLCR|IGNCR|ICRNL|IXON);
01467 tty.c_oflag |= OPOST;
01468 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
01469 tty.c_cflag &= ~(CSIZE|PARENB);
01470 tty.c_cflag |= CS8;
01471 tty.c_cc[VMIN] = 1;
01472 tty.c_cc[VTIME] = 0;
01473
01474 tcsetattr (0, TCSANOW, &tty);
01475 }
01476 signal(SIGQUIT, sigterm_handler);
01477 }
01478 #endif
01479 avformat_network_deinit();
01480
01481 signal(SIGINT , sigterm_handler);
01482 signal(SIGTERM, sigterm_handler);
01483 #ifdef SIGXCPU
01484 signal(SIGXCPU, sigterm_handler);
01485 #endif
01486 }
01487
01488
01489 static int read_key(void)
01490 {
01491 unsigned char ch;
01492 #if HAVE_TERMIOS_H
01493 int n = 1;
01494 struct timeval tv;
01495 fd_set rfds;
01496
01497 FD_ZERO(&rfds);
01498 FD_SET(0, &rfds);
01499 tv.tv_sec = 0;
01500 tv.tv_usec = 0;
01501 n = select(1, &rfds, NULL, NULL, &tv);
01502 if (n > 0) {
01503 n = read(0, &ch, 1);
01504 if (n == 1)
01505 return ch;
01506
01507 return n;
01508 }
01509 #elif HAVE_KBHIT
01510 # if HAVE_PEEKNAMEDPIPE
01511 static int is_pipe;
01512 static HANDLE input_handle;
01513 DWORD dw, nchars;
01514 if(!input_handle){
01515 input_handle = GetStdHandle(STD_INPUT_HANDLE);
01516 is_pipe = !GetConsoleMode(input_handle, &dw);
01517 }
01518
01519 if (stdin->_cnt > 0) {
01520 read(0, &ch, 1);
01521 return ch;
01522 }
01523 if (is_pipe) {
01524
01525 if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
01526 return -1;
01527
01528 if(nchars != 0) {
01529 read(0, &ch, 1);
01530 return ch;
01531 }else{
01532 return -1;
01533 }
01534 }
01535 # endif
01536 if(kbhit())
01537 return(getch());
01538 #endif
01539 return -1;
01540 }
01541
01542 static int decode_interrupt_cb(void *ctx)
01543 {
01544 return received_nb_signals > 1;
01545 }
01546
01547 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
01548
01549 void av_noreturn exit_program(int ret)
01550 {
01551 int i, j;
01552
01553 for (i = 0; i < nb_filtergraphs; i++) {
01554 avfilter_graph_free(&filtergraphs[i]->graph);
01555 for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
01556 av_freep(&filtergraphs[i]->inputs[j]);
01557 av_freep(&filtergraphs[i]->inputs);
01558 for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
01559 av_freep(&filtergraphs[i]->outputs[j]);
01560 av_freep(&filtergraphs[i]->outputs);
01561 av_freep(&filtergraphs[i]);
01562 }
01563 av_freep(&filtergraphs);
01564
01565
01566 for (i = 0; i < nb_output_files; i++) {
01567 AVFormatContext *s = output_files[i]->ctx;
01568 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
01569 avio_close(s->pb);
01570 avformat_free_context(s);
01571 av_dict_free(&output_files[i]->opts);
01572 av_freep(&output_files[i]);
01573 }
01574 for (i = 0; i < nb_output_streams; i++) {
01575 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
01576 while (bsfc) {
01577 AVBitStreamFilterContext *next = bsfc->next;
01578 av_bitstream_filter_close(bsfc);
01579 bsfc = next;
01580 }
01581 output_streams[i]->bitstream_filters = NULL;
01582
01583 av_freep(&output_streams[i]->filtered_frame);
01584 av_freep(&output_streams[i]);
01585 }
01586 for (i = 0; i < nb_input_files; i++) {
01587 avformat_close_input(&input_files[i]->ctx);
01588 av_freep(&input_files[i]);
01589 }
01590 for (i = 0; i < nb_input_streams; i++) {
01591 av_freep(&input_streams[i]->decoded_frame);
01592 av_dict_free(&input_streams[i]->opts);
01593 free_buffer_pool(input_streams[i]);
01594 av_freep(&input_streams[i]->filters);
01595 av_freep(&input_streams[i]);
01596 }
01597
01598 if (vstats_file)
01599 fclose(vstats_file);
01600 av_free(vstats_filename);
01601
01602 av_freep(&input_streams);
01603 av_freep(&input_files);
01604 av_freep(&output_streams);
01605 av_freep(&output_files);
01606
01607 uninit_opts();
01608
01609 avfilter_uninit();
01610 avformat_network_deinit();
01611
01612 if (received_sigterm) {
01613 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
01614 (int) received_sigterm);
01615 exit (255);
01616 }
01617
01618 exit(ret);
01619 }
01620
01621 static void assert_avoptions(AVDictionary *m)
01622 {
01623 AVDictionaryEntry *t;
01624 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
01625 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
01626 exit_program(1);
01627 }
01628 }
01629
01630 static void assert_codec_experimental(AVCodecContext *c, int encoder)
01631 {
01632 const char *codec_string = encoder ? "encoder" : "decoder";
01633 AVCodec *codec;
01634 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
01635 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
01636 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
01637 "results.\nAdd '-strict experimental' if you want to use it.\n",
01638 codec_string, c->codec->name);
01639 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
01640 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
01641 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
01642 codec_string, codec->name);
01643 exit_program(1);
01644 }
01645 }
01646
01647 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
01648 {
01649 if (codec && codec->sample_fmts) {
01650 const enum AVSampleFormat *p = codec->sample_fmts;
01651 for (; *p != -1; p++) {
01652 if (*p == st->codec->sample_fmt)
01653 break;
01654 }
01655 if (*p == -1) {
01656 if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
01657 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
01658 if(av_get_sample_fmt_name(st->codec->sample_fmt))
01659 av_log(NULL, AV_LOG_WARNING,
01660 "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
01661 av_get_sample_fmt_name(st->codec->sample_fmt),
01662 codec->name,
01663 av_get_sample_fmt_name(codec->sample_fmts[0]));
01664 st->codec->sample_fmt = codec->sample_fmts[0];
01665 }
01666 }
01667 }
01668
01669 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
01670 {
01671 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
01672 AVCodecContext *avctx = ost->st->codec;
01673 int ret;
01674
01675 if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
01676 (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
01677 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
01678
01679 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
01680 int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
01681 if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) {
01682 av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max);
01683 pkt->pts = pkt->dts = max;
01684 }
01685 }
01686
01687
01688
01689
01690
01691
01692
01693
01694 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
01695 if (ost->frame_number >= ost->max_frames) {
01696 av_free_packet(pkt);
01697 return;
01698 }
01699 ost->frame_number++;
01700 }
01701
01702 while (bsfc) {
01703 AVPacket new_pkt = *pkt;
01704 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
01705 &new_pkt.data, &new_pkt.size,
01706 pkt->data, pkt->size,
01707 pkt->flags & AV_PKT_FLAG_KEY);
01708 if (a > 0) {
01709 av_free_packet(pkt);
01710 new_pkt.destruct = av_destruct_packet;
01711 } else if (a < 0) {
01712 av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
01713 bsfc->filter->name, pkt->stream_index,
01714 avctx->codec ? avctx->codec->name : "copy");
01715 print_error("", a);
01716 if (exit_on_error)
01717 exit_program(1);
01718 }
01719 *pkt = new_pkt;
01720
01721 bsfc = bsfc->next;
01722 }
01723
01724 pkt->stream_index = ost->index;
01725 ret = av_interleaved_write_frame(s, pkt);
01726 if (ret < 0) {
01727 print_error("av_interleaved_write_frame()", ret);
01728 exit_program(1);
01729 }
01730 }
01731
01732 static int check_recording_time(OutputStream *ost)
01733 {
01734 OutputFile *of = output_files[ost->file_index];
01735
01736 if (of->recording_time != INT64_MAX &&
01737 av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
01738 AV_TIME_BASE_Q) >= 0) {
01739 ost->is_past_recording_time = 1;
01740 return 0;
01741 }
01742 return 1;
01743 }
01744
01745 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
01746 AVFrame *frame)
01747 {
01748 AVCodecContext *enc = ost->st->codec;
01749 AVPacket pkt;
01750 int got_packet = 0;
01751
01752 av_init_packet(&pkt);
01753 pkt.data = NULL;
01754 pkt.size = 0;
01755 #if 0
01756 if (!check_recording_time(ost))
01757 return;
01758 #endif
01759 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
01760 frame->pts = ost->sync_opts;
01761 ost->sync_opts = frame->pts + frame->nb_samples;
01762
01763 av_assert0(pkt.size || !pkt.data);
01764 update_benchmark(NULL);
01765 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
01766 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
01767 exit_program(1);
01768 }
01769 update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
01770
01771 if (got_packet) {
01772 if (pkt.pts != AV_NOPTS_VALUE)
01773 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
01774 if (pkt.dts != AV_NOPTS_VALUE)
01775 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
01776 if (pkt.duration > 0)
01777 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
01778
01779 if (debug_ts) {
01780 av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
01781 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
01782 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
01783 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
01784 }
01785
01786 write_frame(s, &pkt, ost);
01787
01788 audio_size += pkt.size;
01789 av_free_packet(&pkt);
01790 }
01791 }
01792
01793 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
01794 {
01795 AVCodecContext *dec;
01796 AVPicture *picture2;
01797 AVPicture picture_tmp;
01798 uint8_t *buf = 0;
01799
01800 dec = ist->st->codec;
01801
01802
01803 if (do_deinterlace) {
01804 int size;
01805
01806
01807 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
01808 buf = av_malloc(size);
01809 if (!buf)
01810 return;
01811
01812 picture2 = &picture_tmp;
01813 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
01814
01815 if (avpicture_deinterlace(picture2, picture,
01816 dec->pix_fmt, dec->width, dec->height) < 0) {
01817
01818 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
01819 av_free(buf);
01820 buf = NULL;
01821 picture2 = picture;
01822 }
01823 } else {
01824 picture2 = picture;
01825 }
01826
01827 if (picture != picture2)
01828 *picture = *picture2;
01829 *bufp = buf;
01830 }
01831
01832 static void do_subtitle_out(AVFormatContext *s,
01833 OutputStream *ost,
01834 InputStream *ist,
01835 AVSubtitle *sub,
01836 int64_t pts)
01837 {
01838 static uint8_t *subtitle_out = NULL;
01839 int subtitle_out_max_size = 1024 * 1024;
01840 int subtitle_out_size, nb, i;
01841 AVCodecContext *enc;
01842 AVPacket pkt;
01843
01844 if (pts == AV_NOPTS_VALUE) {
01845 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
01846 if (exit_on_error)
01847 exit_program(1);
01848 return;
01849 }
01850
01851 enc = ost->st->codec;
01852
01853 if (!subtitle_out) {
01854 subtitle_out = av_malloc(subtitle_out_max_size);
01855 }
01856
01857
01858
01859
01860 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
01861 nb = 2;
01862 else
01863 nb = 1;
01864
01865 for (i = 0; i < nb; i++) {
01866 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
01867
01868 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
01869
01870 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
01871 sub->end_display_time -= sub->start_display_time;
01872 sub->start_display_time = 0;
01873 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
01874 subtitle_out_max_size, sub);
01875 if (subtitle_out_size < 0) {
01876 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
01877 exit_program(1);
01878 }
01879
01880 av_init_packet(&pkt);
01881 pkt.data = subtitle_out;
01882 pkt.size = subtitle_out_size;
01883 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
01884 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
01885
01886
01887 if (i == 0)
01888 pkt.pts += 90 * sub->start_display_time;
01889 else
01890 pkt.pts += 90 * sub->end_display_time;
01891 }
01892 write_frame(s, &pkt, ost);
01893 }
01894 }
01895
01896 static void do_video_out(AVFormatContext *s,
01897 OutputStream *ost,
01898 AVFrame *in_picture,
01899 float quality)
01900 {
01901 int ret, format_video_sync;
01902 AVPacket pkt;
01903 AVCodecContext *enc = ost->st->codec;
01904 int nb_frames, i;
01905 double sync_ipts, delta;
01906 double duration = 0;
01907 int frame_size = 0;
01908 InputStream *ist = NULL;
01909
01910 if (ost->source_index >= 0)
01911 ist = input_streams[ost->source_index];
01912
01913 if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
01914 duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
01915
01916 sync_ipts = in_picture->pts;
01917 delta = sync_ipts - ost->sync_opts + duration;
01918
01919
01920 nb_frames = 1;
01921
01922 format_video_sync = video_sync_method;
01923 if (format_video_sync == VSYNC_AUTO)
01924 format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
01925
01926 switch (format_video_sync) {
01927 case VSYNC_CFR:
01928
01929 if (delta < -1.1)
01930 nb_frames = 0;
01931 else if (delta > 1.1)
01932 nb_frames = lrintf(delta);
01933 break;
01934 case VSYNC_VFR:
01935 if (delta <= -0.6)
01936 nb_frames = 0;
01937 else if (delta > 0.6)
01938 ost->sync_opts = lrint(sync_ipts);
01939 break;
01940 case VSYNC_DROP:
01941 case VSYNC_PASSTHROUGH:
01942 ost->sync_opts = lrint(sync_ipts);
01943 break;
01944 default:
01945 av_assert0(0);
01946 }
01947
01948 nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
01949 if (nb_frames == 0) {
01950 nb_frames_drop++;
01951 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
01952 return;
01953 } else if (nb_frames > 1) {
01954 nb_frames_dup += nb_frames - 1;
01955 av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
01956 }
01957
01958
01959 duplicate_frame:
01960 av_init_packet(&pkt);
01961 pkt.data = NULL;
01962 pkt.size = 0;
01963
01964 in_picture->pts = ost->sync_opts;
01965
01966 if (s->oformat->flags & AVFMT_RAWPICTURE &&
01967 enc->codec->id == CODEC_ID_RAWVIDEO) {
01968
01969
01970
01971 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
01972 enc->coded_frame->top_field_first = in_picture->top_field_first;
01973 pkt.data = (uint8_t *)in_picture;
01974 pkt.size = sizeof(AVPicture);
01975 pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
01976 pkt.flags |= AV_PKT_FLAG_KEY;
01977
01978 write_frame(s, &pkt, ost);
01979 } else {
01980 int got_packet;
01981 AVFrame big_picture;
01982
01983 big_picture = *in_picture;
01984
01985
01986 big_picture.interlaced_frame = in_picture->interlaced_frame;
01987 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
01988 if (ost->top_field_first == -1)
01989 big_picture.top_field_first = in_picture->top_field_first;
01990 else
01991 big_picture.top_field_first = !!ost->top_field_first;
01992 }
01993
01994
01995
01996 big_picture.quality = quality;
01997 if (!enc->me_threshold)
01998 big_picture.pict_type = 0;
01999 if (ost->forced_kf_index < ost->forced_kf_count &&
02000 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
02001 big_picture.pict_type = AV_PICTURE_TYPE_I;
02002 ost->forced_kf_index++;
02003 }
02004 update_benchmark(NULL);
02005 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
02006 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
02007 if (ret < 0) {
02008 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
02009 exit_program(1);
02010 }
02011
02012 if (got_packet) {
02013 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
02014 pkt.pts = ost->sync_opts;
02015
02016 if (pkt.pts != AV_NOPTS_VALUE)
02017 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
02018 if (pkt.dts != AV_NOPTS_VALUE)
02019 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
02020
02021 if (debug_ts) {
02022 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
02023 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
02024 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
02025 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
02026 }
02027
02028 write_frame(s, &pkt, ost);
02029 frame_size = pkt.size;
02030 video_size += pkt.size;
02031 av_free_packet(&pkt);
02032
02033
02034 if (ost->logfile && enc->stats_out) {
02035 fprintf(ost->logfile, "%s", enc->stats_out);
02036 }
02037 }
02038 }
02039 ost->sync_opts++;
02040
02041
02042
02043
02044
02045 ost->frame_number++;
02046
02047 if(--nb_frames)
02048 goto duplicate_frame;
02049
02050 if (vstats_filename && frame_size)
02051 do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
02052 }
02053
02054 static double psnr(double d)
02055 {
02056 return -10.0 * log(d) / log(10.0);
02057 }
02058
02059 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
02060 int frame_size)
02061 {
02062 AVCodecContext *enc;
02063 int frame_number;
02064 double ti1, bitrate, avg_bitrate;
02065
02066
02067 if (!vstats_file) {
02068 vstats_file = fopen(vstats_filename, "w");
02069 if (!vstats_file) {
02070 perror("fopen");
02071 exit_program(1);
02072 }
02073 }
02074
02075 enc = ost->st->codec;
02076 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
02077 frame_number = ost->frame_number;
02078 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
02079 if (enc->flags&CODEC_FLAG_PSNR)
02080 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
02081
02082 fprintf(vstats_file,"f_size= %6d ", frame_size);
02083
02084 ti1 = ost->sync_opts * av_q2d(enc->time_base);
02085 if (ti1 < 0.01)
02086 ti1 = 0.01;
02087
02088 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
02089 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
02090 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
02091 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
02092 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
02093 }
02094 }
02095
02096
02097 static int poll_filters(void)
02098 {
02099 AVFilterBufferRef *picref;
02100 AVFrame *filtered_frame = NULL;
02101 int i, ret, ret_all;
02102 unsigned nb_success, nb_eof;
02103 int64_t frame_pts;
02104
02105 while (1) {
02106
02107 for (i = 0; i < nb_output_streams; i++) {
02108 OutputStream *ost = output_streams[i];
02109 OutputFile *of = output_files[ost->file_index];
02110 int ret = 0;
02111
02112 if (!ost->filter || ost->is_past_recording_time)
02113 continue;
02114
02115 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
02116 return AVERROR(ENOMEM);
02117 } else
02118 avcodec_get_frame_defaults(ost->filtered_frame);
02119 filtered_frame = ost->filtered_frame;
02120
02121 while (1) {
02122 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
02123 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
02124 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
02125 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
02126 ost->st->codec->frame_size);
02127 else
02128 #ifdef SINKA
02129 ret = av_buffersink_read(ost->filter->filter, &picref);
02130 #else
02131 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
02132 AV_BUFFERSINK_FLAG_NO_REQUEST);
02133 #endif
02134 if (ret < 0) {
02135 if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
02136 char buf[256];
02137 av_strerror(ret, buf, sizeof(buf));
02138 av_log(NULL, AV_LOG_WARNING,
02139 "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
02140 }
02141 break;
02142 }
02143 frame_pts = AV_NOPTS_VALUE;
02144 if (picref->pts != AV_NOPTS_VALUE) {
02145 filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
02146 ost->filter->filter->inputs[0]->time_base,
02147 ost->st->codec->time_base) -
02148 av_rescale_q(of->start_time,
02149 AV_TIME_BASE_Q,
02150 ost->st->codec->time_base);
02151
02152 if (of->start_time && filtered_frame->pts < 0) {
02153 avfilter_unref_buffer(picref);
02154 continue;
02155 }
02156 }
02157
02158
02159
02160
02161 switch (ost->filter->filter->inputs[0]->type) {
02162 case AVMEDIA_TYPE_VIDEO:
02163 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
02164 filtered_frame->pts = frame_pts;
02165 if (!ost->frame_aspect_ratio)
02166 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
02167
02168 do_video_out(of->ctx, ost, filtered_frame,
02169 same_quant ? ost->last_quality :
02170 ost->st->codec->global_quality);
02171 break;
02172 case AVMEDIA_TYPE_AUDIO:
02173 avfilter_copy_buf_props(filtered_frame, picref);
02174 filtered_frame->pts = frame_pts;
02175 do_audio_out(of->ctx, ost, filtered_frame);
02176 break;
02177 default:
02178
02179 av_assert0(0);
02180 }
02181
02182 avfilter_unref_buffer(picref);
02183 }
02184 }
02185
02186 ret_all = nb_success = nb_eof = 0;
02187 for (i = 0; i < nb_filtergraphs; i++) {
02188 ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
02189 if (!ret) {
02190 nb_success++;
02191 } else if (ret == AVERROR_EOF) {
02192 nb_eof++;
02193 } else if (ret != AVERROR(EAGAIN)) {
02194 char buf[256];
02195 av_strerror(ret, buf, sizeof(buf));
02196 av_log(NULL, AV_LOG_WARNING,
02197 "Error in request_frame(): %s\n", buf);
02198 ret_all = ret;
02199 }
02200 }
02201 if (!nb_success)
02202 break;
02203
02204 }
02205 return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
02206 }
02207
02208 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
02209 {
02210 char buf[1024];
02211 OutputStream *ost;
02212 AVFormatContext *oc;
02213 int64_t total_size;
02214 AVCodecContext *enc;
02215 int frame_number, vid, i;
02216 double bitrate;
02217 int64_t pts = INT64_MAX;
02218 static int64_t last_time = -1;
02219 static int qp_histogram[52];
02220 int hours, mins, secs, us;
02221
02222 if (!print_stats && !is_last_report)
02223 return;
02224
02225 if (!is_last_report) {
02226 if (last_time == -1) {
02227 last_time = cur_time;
02228 return;
02229 }
02230 if ((cur_time - last_time) < 500000)
02231 return;
02232 last_time = cur_time;
02233 }
02234
02235
02236 oc = output_files[0]->ctx;
02237
02238 total_size = avio_size(oc->pb);
02239 if (total_size < 0) {
02240 total_size = avio_tell(oc->pb);
02241 if (total_size < 0)
02242 total_size = 0;
02243 }
02244
02245 buf[0] = '\0';
02246 vid = 0;
02247 for (i = 0; i < nb_output_streams; i++) {
02248 float q = -1;
02249 ost = output_streams[i];
02250 enc = ost->st->codec;
02251 if (!ost->stream_copy && enc->coded_frame)
02252 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
02253 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
02254 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
02255 }
02256 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
02257 float fps, t = (cur_time-timer_start) / 1000000.0;
02258
02259 frame_number = ost->frame_number;
02260 fps = t > 1 ? frame_number / t : 0;
02261 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
02262 frame_number, fps < 9.95, fps, q);
02263 if (is_last_report)
02264 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
02265 if (qp_hist) {
02266 int j;
02267 int qp = lrintf(q);
02268 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
02269 qp_histogram[qp]++;
02270 for (j = 0; j < 32; j++)
02271 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
02272 }
02273 if (enc->flags&CODEC_FLAG_PSNR) {
02274 int j;
02275 double error, error_sum = 0;
02276 double scale, scale_sum = 0;
02277 char type[3] = { 'Y','U','V' };
02278 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
02279 for (j = 0; j < 3; j++) {
02280 if (is_last_report) {
02281 error = enc->error[j];
02282 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
02283 } else {
02284 error = enc->coded_frame->error[j];
02285 scale = enc->width * enc->height * 255.0 * 255.0;
02286 }
02287 if (j)
02288 scale /= 4;
02289 error_sum += error;
02290 scale_sum += scale;
02291 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
02292 }
02293 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
02294 }
02295 vid = 1;
02296 }
02297
02298 pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
02299 ost->st->time_base, AV_TIME_BASE_Q));
02300 }
02301
02302 secs = pts / AV_TIME_BASE;
02303 us = pts % AV_TIME_BASE;
02304 mins = secs / 60;
02305 secs %= 60;
02306 hours = mins / 60;
02307 mins %= 60;
02308
02309 bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
02310
02311 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
02312 "size=%8.0fkB time=", total_size / 1024.0);
02313 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
02314 "%02d:%02d:%02d.%02d ", hours, mins, secs,
02315 (100 * us) / AV_TIME_BASE);
02316 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
02317 "bitrate=%6.1fkbits/s", bitrate);
02318
02319 if (nb_frames_dup || nb_frames_drop)
02320 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
02321 nb_frames_dup, nb_frames_drop);
02322
02323 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
02324
02325 fflush(stderr);
02326
02327 if (is_last_report) {
02328 int64_t raw= audio_size + video_size + extra_size;
02329 av_log(NULL, AV_LOG_INFO, "\n");
02330 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
02331 video_size / 1024.0,
02332 audio_size / 1024.0,
02333 extra_size / 1024.0,
02334 100.0 * (total_size - raw) / raw
02335 );
02336 if(video_size + audio_size + extra_size == 0){
02337 av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
02338 }
02339 }
02340 }
02341
02342 static void flush_encoders(void)
02343 {
02344 int i, ret;
02345
02346 for (i = 0; i < nb_output_streams; i++) {
02347 OutputStream *ost = output_streams[i];
02348 AVCodecContext *enc = ost->st->codec;
02349 AVFormatContext *os = output_files[ost->file_index]->ctx;
02350 int stop_encoding = 0;
02351
02352 if (!ost->encoding_needed)
02353 continue;
02354
02355 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
02356 continue;
02357 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
02358 continue;
02359
02360 for (;;) {
02361 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
02362 const char *desc;
02363 int64_t *size;
02364
02365 switch (ost->st->codec->codec_type) {
02366 case AVMEDIA_TYPE_AUDIO:
02367 encode = avcodec_encode_audio2;
02368 desc = "Audio";
02369 size = &audio_size;
02370 break;
02371 case AVMEDIA_TYPE_VIDEO:
02372 encode = avcodec_encode_video2;
02373 desc = "Video";
02374 size = &video_size;
02375 break;
02376 default:
02377 stop_encoding = 1;
02378 }
02379
02380 if (encode) {
02381 AVPacket pkt;
02382 int got_packet;
02383 av_init_packet(&pkt);
02384 pkt.data = NULL;
02385 pkt.size = 0;
02386
02387 update_benchmark(NULL);
02388 ret = encode(enc, &pkt, NULL, &got_packet);
02389 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
02390 if (ret < 0) {
02391 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
02392 exit_program(1);
02393 }
02394 *size += pkt.size;
02395 if (ost->logfile && enc->stats_out) {
02396 fprintf(ost->logfile, "%s", enc->stats_out);
02397 }
02398 if (!got_packet) {
02399 stop_encoding = 1;
02400 break;
02401 }
02402 if (pkt.pts != AV_NOPTS_VALUE)
02403 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
02404 if (pkt.dts != AV_NOPTS_VALUE)
02405 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
02406 write_frame(os, &pkt, ost);
02407 }
02408
02409 if (stop_encoding)
02410 break;
02411 }
02412 }
02413 }
02414
02415
02416
02417
02418 static int check_output_constraints(InputStream *ist, OutputStream *ost)
02419 {
02420 OutputFile *of = output_files[ost->file_index];
02421 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
02422
02423 if (ost->source_index != ist_index)
02424 return 0;
02425
02426 if (of->start_time && ist->pts < of->start_time)
02427 return 0;
02428
02429 if (of->recording_time != INT64_MAX &&
02430 av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
02431 (AVRational){ 1, 1000000 }) >= 0) {
02432 ost->is_past_recording_time = 1;
02433 return 0;
02434 }
02435
02436 return 1;
02437 }
02438
02439 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
02440 {
02441 OutputFile *of = output_files[ost->file_index];
02442 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
02443 AVPicture pict;
02444 AVPacket opkt;
02445
02446 av_init_packet(&opkt);
02447
02448 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
02449 !ost->copy_initial_nonkeyframes)
02450 return;
02451
02452
02453 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
02454 audio_size += pkt->size;
02455 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02456 video_size += pkt->size;
02457 ost->sync_opts++;
02458 }
02459
02460 if (pkt->pts != AV_NOPTS_VALUE)
02461 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
02462 else
02463 opkt.pts = AV_NOPTS_VALUE;
02464
02465 if (pkt->dts == AV_NOPTS_VALUE)
02466 opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
02467 else
02468 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
02469 opkt.dts -= ost_tb_start_time;
02470
02471 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
02472 opkt.flags = pkt->flags;
02473
02474
02475 if ( ost->st->codec->codec_id != CODEC_ID_H264
02476 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
02477 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
02478 && ost->st->codec->codec_id != CODEC_ID_VC1
02479 ) {
02480 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
02481 opkt.destruct = av_destruct_packet;
02482 } else {
02483 opkt.data = pkt->data;
02484 opkt.size = pkt->size;
02485 }
02486 if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
02487
02488 avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
02489 opkt.data = (uint8_t *)&pict;
02490 opkt.size = sizeof(AVPicture);
02491 opkt.flags |= AV_PKT_FLAG_KEY;
02492 }
02493
02494 write_frame(of->ctx, &opkt, ost);
02495 ost->st->codec->frame_number++;
02496 av_free_packet(&opkt);
02497 }
02498
02499 static void rate_emu_sleep(InputStream *ist)
02500 {
02501 if (input_files[ist->file_index]->rate_emu) {
02502 int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
02503 int64_t now = av_gettime() - ist->start;
02504 if (pts > now)
02505 usleep(pts - now);
02506 }
02507 }
02508
02509 static int guess_input_channel_layout(InputStream *ist)
02510 {
02511 AVCodecContext *dec = ist->st->codec;
02512
02513 if (!dec->channel_layout) {
02514 char layout_name[256];
02515
02516 dec->channel_layout = av_get_default_channel_layout(dec->channels);
02517 if (!dec->channel_layout)
02518 return 0;
02519 av_get_channel_layout_string(layout_name, sizeof(layout_name),
02520 dec->channels, dec->channel_layout);
02521 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
02522 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
02523 }
02524 return 1;
02525 }
02526
02527 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
02528 {
02529 AVFrame *decoded_frame;
02530 AVCodecContext *avctx = ist->st->codec;
02531 int i, ret, resample_changed;
02532
02533 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
02534 return AVERROR(ENOMEM);
02535 else
02536 avcodec_get_frame_defaults(ist->decoded_frame);
02537 decoded_frame = ist->decoded_frame;
02538
02539 update_benchmark(NULL);
02540 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
02541 update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
02542 if (ret < 0) {
02543 return ret;
02544 }
02545 if (avctx->sample_rate <= 0) {
02546 av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
02547 return AVERROR_INVALIDDATA;
02548 }
02549
02550 if (!*got_output) {
02551
02552 if (!pkt->size)
02553 for (i = 0; i < ist->nb_filters; i++)
02554 av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
02555 AV_BUFFERSRC_FLAG_NO_COPY);
02556 return ret;
02557 }
02558
02559
02560
02561 if (decoded_frame->pts != AV_NOPTS_VALUE)
02562 ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
02563 else if (pkt->pts != AV_NOPTS_VALUE) {
02564 decoded_frame->pts = pkt->pts;
02565 pkt->pts = AV_NOPTS_VALUE;
02566 }else
02567 decoded_frame->pts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
02568
02569
02570 #if 1
02571
02572
02573 ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
02574 avctx->sample_rate;
02575 ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
02576 avctx->sample_rate;
02577 #endif
02578
02579 rate_emu_sleep(ist);
02580
02581 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
02582 ist->resample_channels != avctx->channels ||
02583 ist->resample_channel_layout != decoded_frame->channel_layout ||
02584 ist->resample_sample_rate != decoded_frame->sample_rate;
02585 if (resample_changed) {
02586 char layout1[64], layout2[64];
02587
02588 if (!guess_input_channel_layout(ist)) {
02589 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
02590 "layout for Input Stream #%d.%d\n", ist->file_index,
02591 ist->st->index);
02592 exit_program(1);
02593 }
02594 decoded_frame->channel_layout = avctx->channel_layout;
02595
02596 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
02597 ist->resample_channel_layout);
02598 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
02599 decoded_frame->channel_layout);
02600
02601 av_log(NULL, AV_LOG_INFO,
02602 "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
02603 ist->file_index, ist->st->index,
02604 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
02605 ist->resample_channels, layout1,
02606 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
02607 avctx->channels, layout2);
02608
02609 ist->resample_sample_fmt = decoded_frame->format;
02610 ist->resample_sample_rate = decoded_frame->sample_rate;
02611 ist->resample_channel_layout = decoded_frame->channel_layout;
02612 ist->resample_channels = avctx->channels;
02613
02614 for (i = 0; i < nb_filtergraphs; i++)
02615 if (ist_in_filtergraph(filtergraphs[i], ist) &&
02616 configure_filtergraph(filtergraphs[i]) < 0) {
02617 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
02618 exit_program(1);
02619 }
02620 }
02621
02622 for (i = 0; i < ist->nb_filters; i++)
02623 av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
02624
02625 return ret;
02626 }
02627
02628 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
02629 {
02630 AVFrame *decoded_frame;
02631 void *buffer_to_free = NULL;
02632 int i, ret = 0, resample_changed;
02633 int64_t best_effort_timestamp;
02634 AVRational *frame_sample_aspect;
02635 float quality;
02636
02637 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
02638 return AVERROR(ENOMEM);
02639 else
02640 avcodec_get_frame_defaults(ist->decoded_frame);
02641 decoded_frame = ist->decoded_frame;
02642 pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
02643
02644 update_benchmark(NULL);
02645 ret = avcodec_decode_video2(ist->st->codec,
02646 decoded_frame, got_output, pkt);
02647 update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
02648 if (ret < 0)
02649 return ret;
02650
02651 quality = same_quant ? decoded_frame->quality : 0;
02652 if (!*got_output) {
02653
02654 if (!pkt->size)
02655 for (i = 0; i < ist->nb_filters; i++)
02656 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
02657 return ret;
02658 }
02659
02660 best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
02661 if(best_effort_timestamp != AV_NOPTS_VALUE)
02662 ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
02663
02664 pkt->size = 0;
02665 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
02666
02667 rate_emu_sleep(ist);
02668
02669 if (ist->st->sample_aspect_ratio.num)
02670 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
02671
02672 resample_changed = ist->resample_width != decoded_frame->width ||
02673 ist->resample_height != decoded_frame->height ||
02674 ist->resample_pix_fmt != decoded_frame->format;
02675 if (resample_changed) {
02676 av_log(NULL, AV_LOG_INFO,
02677 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
02678 ist->file_index, ist->st->index,
02679 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
02680 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
02681
02682 ist->resample_width = decoded_frame->width;
02683 ist->resample_height = decoded_frame->height;
02684 ist->resample_pix_fmt = decoded_frame->format;
02685
02686 for (i = 0; i < nb_filtergraphs; i++)
02687 if (ist_in_filtergraph(filtergraphs[i], ist) &&
02688 configure_filtergraph(filtergraphs[i]) < 0) {
02689 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
02690 exit_program(1);
02691 }
02692 }
02693
02694 frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
02695 for (i = 0; i < ist->nb_filters; i++) {
02696 int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
02697 || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
02698 || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
02699
02700 if (ist->filters[i]->graph->nb_outputs == 1)
02701 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
02702
02703 if (!frame_sample_aspect->num)
02704 *frame_sample_aspect = ist->st->sample_aspect_ratio;
02705 if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
02706 FrameBuffer *buf = decoded_frame->opaque;
02707 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
02708 decoded_frame->data, decoded_frame->linesize,
02709 AV_PERM_READ | AV_PERM_PRESERVE,
02710 ist->st->codec->width, ist->st->codec->height,
02711 ist->st->codec->pix_fmt);
02712
02713 avfilter_copy_frame_props(fb, decoded_frame);
02714 fb->buf->priv = buf;
02715 fb->buf->free = filter_release_buffer;
02716
02717 av_assert0(buf->refcount>0);
02718 buf->refcount++;
02719 av_buffersrc_add_ref(ist->filters[i]->filter, fb,
02720 AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
02721 AV_BUFFERSRC_FLAG_NO_COPY);
02722 } else
02723 if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
02724 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
02725 exit_program(1);
02726 }
02727
02728 }
02729
02730 av_free(buffer_to_free);
02731 return ret;
02732 }
02733
02734 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
02735 {
02736 AVSubtitle subtitle;
02737 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
02738 &subtitle, got_output, pkt);
02739 if (ret < 0)
02740 return ret;
02741 if (!*got_output)
02742 return ret;
02743
02744 rate_emu_sleep(ist);
02745
02746 for (i = 0; i < nb_output_streams; i++) {
02747 OutputStream *ost = output_streams[i];
02748
02749 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
02750 continue;
02751
02752 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
02753 }
02754
02755 avsubtitle_free(&subtitle);
02756 return ret;
02757 }
02758
02759
02760 static int output_packet(InputStream *ist, const AVPacket *pkt)
02761 {
02762 int ret = 0, i;
02763 int got_output;
02764
02765 AVPacket avpkt;
02766 if (!ist->saw_first_ts) {
02767 ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
02768 ist->pts = 0;
02769 if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
02770 ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
02771 ist->pts = ist->dts;
02772 }
02773 ist->saw_first_ts = 1;
02774 }
02775
02776 if (ist->next_dts == AV_NOPTS_VALUE)
02777 ist->next_dts = ist->dts;
02778 if (ist->next_pts == AV_NOPTS_VALUE)
02779 ist->next_pts = ist->pts;
02780
02781 if (pkt == NULL) {
02782
02783 av_init_packet(&avpkt);
02784 avpkt.data = NULL;
02785 avpkt.size = 0;
02786 goto handle_eof;
02787 } else {
02788 avpkt = *pkt;
02789 }
02790
02791 if (pkt->dts != AV_NOPTS_VALUE) {
02792 ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
02793 if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
02794 ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
02795 }
02796
02797
02798 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
02799 int duration;
02800 handle_eof:
02801
02802 ist->pts = ist->next_pts;
02803 ist->dts = ist->next_dts;
02804
02805 if (avpkt.size && avpkt.size != pkt->size) {
02806 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
02807 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
02808 ist->showed_multi_packet_warning = 1;
02809 }
02810
02811 switch (ist->st->codec->codec_type) {
02812 case AVMEDIA_TYPE_AUDIO:
02813 ret = decode_audio (ist, &avpkt, &got_output);
02814 break;
02815 case AVMEDIA_TYPE_VIDEO:
02816 ret = decode_video (ist, &avpkt, &got_output);
02817 if (avpkt.duration) {
02818 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
02819 } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
02820 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
02821 duration = ((int64_t)AV_TIME_BASE *
02822 ist->st->codec->time_base.num * ticks) /
02823 ist->st->codec->time_base.den;
02824 } else
02825 duration = 0;
02826
02827 if(ist->dts != AV_NOPTS_VALUE && duration) {
02828 ist->next_dts += duration;
02829 }else
02830 ist->next_dts = AV_NOPTS_VALUE;
02831
02832 if (got_output)
02833 ist->next_pts += duration;
02834 break;
02835 case AVMEDIA_TYPE_SUBTITLE:
02836 ret = transcode_subtitles(ist, &avpkt, &got_output);
02837 break;
02838 default:
02839 return -1;
02840 }
02841
02842 if (ret < 0)
02843 return ret;
02844
02845 avpkt.dts=
02846 avpkt.pts= AV_NOPTS_VALUE;
02847
02848
02849 if (pkt) {
02850 if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
02851 ret = avpkt.size;
02852 avpkt.data += ret;
02853 avpkt.size -= ret;
02854 }
02855 if (!got_output) {
02856 continue;
02857 }
02858 }
02859
02860
02861 if (!ist->decoding_needed) {
02862 rate_emu_sleep(ist);
02863 ist->dts = ist->next_dts;
02864 switch (ist->st->codec->codec_type) {
02865 case AVMEDIA_TYPE_AUDIO:
02866 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
02867 ist->st->codec->sample_rate;
02868 break;
02869 case AVMEDIA_TYPE_VIDEO:
02870 if (pkt->duration) {
02871 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
02872 } else if(ist->st->codec->time_base.num != 0) {
02873 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
02874 ist->next_dts += ((int64_t)AV_TIME_BASE *
02875 ist->st->codec->time_base.num * ticks) /
02876 ist->st->codec->time_base.den;
02877 }
02878 break;
02879 }
02880 ist->pts = ist->dts;
02881 ist->next_pts = ist->next_dts;
02882 }
02883 for (i = 0; pkt && i < nb_output_streams; i++) {
02884 OutputStream *ost = output_streams[i];
02885
02886 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
02887 continue;
02888
02889 do_streamcopy(ist, ost, pkt);
02890 }
02891
02892 return 0;
02893 }
02894
02895 static void print_sdp(void)
02896 {
02897 char sdp[2048];
02898 int i;
02899 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
02900
02901 if (!avc)
02902 exit_program(1);
02903 for (i = 0; i < nb_output_files; i++)
02904 avc[i] = output_files[i]->ctx;
02905
02906 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
02907 printf("SDP:\n%s\n", sdp);
02908 fflush(stdout);
02909 av_freep(&avc);
02910 }
02911
02912 static int init_input_stream(int ist_index, char *error, int error_len)
02913 {
02914 InputStream *ist = input_streams[ist_index];
02915
02916 if (ist->decoding_needed) {
02917 AVCodec *codec = ist->dec;
02918 if (!codec) {
02919 snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
02920 avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
02921 return AVERROR(EINVAL);
02922 }
02923
02924 ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
02925 if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
02926 ist->st->codec->get_buffer = codec_get_buffer;
02927 ist->st->codec->release_buffer = codec_release_buffer;
02928 ist->st->codec->opaque = ist;
02929 }
02930
02931 if (!av_dict_get(ist->opts, "threads", NULL, 0))
02932 av_dict_set(&ist->opts, "threads", "auto", 0);
02933 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
02934 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
02935 ist->file_index, ist->st->index);
02936 return AVERROR(EINVAL);
02937 }
02938 assert_codec_experimental(ist->st->codec, 0);
02939 assert_avoptions(ist->opts);
02940 }
02941
02942 ist->next_pts = AV_NOPTS_VALUE;
02943 ist->next_dts = AV_NOPTS_VALUE;
02944 ist->is_start = 1;
02945
02946 return 0;
02947 }
02948
02949 static InputStream *get_input_stream(OutputStream *ost)
02950 {
02951 if (ost->source_index >= 0)
02952 return input_streams[ost->source_index];
02953
02954 if (ost->filter) {
02955 FilterGraph *fg = ost->filter->graph;
02956 int i;
02957
02958 for (i = 0; i < fg->nb_inputs; i++)
02959 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
02960 return fg->inputs[i]->ist;
02961 }
02962
02963 return NULL;
02964 }
02965
02966 static int transcode_init(void)
02967 {
02968 int ret = 0, i, j, k;
02969 AVFormatContext *oc;
02970 AVCodecContext *codec, *icodec;
02971 OutputStream *ost;
02972 InputStream *ist;
02973 char error[1024];
02974 int want_sdp = 1;
02975
02976
02977 for (i = 0; i < nb_input_files; i++) {
02978 InputFile *ifile = input_files[i];
02979 if (ifile->rate_emu)
02980 for (j = 0; j < ifile->nb_streams; j++)
02981 input_streams[j + ifile->ist_index]->start = av_gettime();
02982 }
02983
02984
02985 for (i = 0; i < nb_output_files; i++) {
02986 oc = output_files[i]->ctx;
02987 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
02988 av_dump_format(oc, i, oc->filename, 1);
02989 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
02990 return AVERROR(EINVAL);
02991 }
02992 }
02993
02994
02995 for (i = 0; i < nb_filtergraphs; i++)
02996 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
02997 return ret;
02998
02999
03000 for (i = 0; i < nb_output_streams; i++) {
03001 ost = output_streams[i];
03002 oc = output_files[ost->file_index]->ctx;
03003 ist = get_input_stream(ost);
03004
03005 if (ost->attachment_filename)
03006 continue;
03007
03008 codec = ost->st->codec;
03009
03010 if (ist) {
03011 icodec = ist->st->codec;
03012
03013 ost->st->disposition = ist->st->disposition;
03014 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
03015 codec->chroma_sample_location = icodec->chroma_sample_location;
03016 }
03017
03018 if (ost->stream_copy) {
03019 uint64_t extra_size;
03020
03021 av_assert0(ist && !ost->filter);
03022
03023 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
03024
03025 if (extra_size > INT_MAX) {
03026 return AVERROR(EINVAL);
03027 }
03028
03029
03030 codec->codec_id = icodec->codec_id;
03031 codec->codec_type = icodec->codec_type;
03032
03033 if (!codec->codec_tag) {
03034 if (!oc->oformat->codec_tag ||
03035 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
03036 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
03037 codec->codec_tag = icodec->codec_tag;
03038 }
03039
03040 codec->bit_rate = icodec->bit_rate;
03041 codec->rc_max_rate = icodec->rc_max_rate;
03042 codec->rc_buffer_size = icodec->rc_buffer_size;
03043 codec->field_order = icodec->field_order;
03044 codec->extradata = av_mallocz(extra_size);
03045 if (!codec->extradata) {
03046 return AVERROR(ENOMEM);
03047 }
03048 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
03049 codec->extradata_size= icodec->extradata_size;
03050 codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
03051
03052 codec->time_base = ist->st->time_base;
03053
03054
03055
03056
03057
03058 if(!strcmp(oc->oformat->name, "avi")) {
03059 if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
03060 && av_q2d(ist->st->time_base) < 1.0/500
03061 || copy_tb==0){
03062 codec->time_base = icodec->time_base;
03063 codec->time_base.num *= icodec->ticks_per_frame;
03064 codec->time_base.den *= 2;
03065 codec->ticks_per_frame = 2;
03066 }
03067 } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
03068 && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
03069 && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
03070 ) {
03071 if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
03072 && av_q2d(ist->st->time_base) < 1.0/500
03073 || copy_tb==0){
03074 codec->time_base = icodec->time_base;
03075 codec->time_base.num *= icodec->ticks_per_frame;
03076 }
03077 }
03078 av_reduce(&codec->time_base.num, &codec->time_base.den,
03079 codec->time_base.num, codec->time_base.den, INT_MAX);
03080
03081 switch (codec->codec_type) {
03082 case AVMEDIA_TYPE_AUDIO:
03083 if (audio_volume != 256) {
03084 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
03085 exit_program(1);
03086 }
03087 codec->channel_layout = icodec->channel_layout;
03088 codec->sample_rate = icodec->sample_rate;
03089 codec->channels = icodec->channels;
03090 codec->frame_size = icodec->frame_size;
03091 codec->audio_service_type = icodec->audio_service_type;
03092 codec->block_align = icodec->block_align;
03093 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
03094 codec->block_align= 0;
03095 if(codec->codec_id == CODEC_ID_AC3)
03096 codec->block_align= 0;
03097 break;
03098 case AVMEDIA_TYPE_VIDEO:
03099 codec->pix_fmt = icodec->pix_fmt;
03100 codec->width = icodec->width;
03101 codec->height = icodec->height;
03102 codec->has_b_frames = icodec->has_b_frames;
03103 if (!codec->sample_aspect_ratio.num) {
03104 codec->sample_aspect_ratio =
03105 ost->st->sample_aspect_ratio =
03106 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
03107 ist->st->codec->sample_aspect_ratio.num ?
03108 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
03109 }
03110 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
03111 break;
03112 case AVMEDIA_TYPE_SUBTITLE:
03113 codec->width = icodec->width;
03114 codec->height = icodec->height;
03115 break;
03116 case AVMEDIA_TYPE_DATA:
03117 case AVMEDIA_TYPE_ATTACHMENT:
03118 break;
03119 default:
03120 abort();
03121 }
03122 } else {
03123 if (!ost->enc)
03124 ost->enc = avcodec_find_encoder(codec->codec_id);
03125 if (!ost->enc) {
03126
03127 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
03128 avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
03129 ret = AVERROR(EINVAL);
03130 goto dump_format;
03131 }
03132
03133 if (ist)
03134 ist->decoding_needed = 1;
03135 ost->encoding_needed = 1;
03136
03137 if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
03138 if (ist && !ost->frame_rate.num)
03139 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
03140 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
03141 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
03142 ost->frame_rate = ost->enc->supported_framerates[idx];
03143 }
03144 }
03145
03146 if (!ost->filter &&
03147 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
03148 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
03149 FilterGraph *fg;
03150 fg = init_simple_filtergraph(ist, ost);
03151 if (configure_simple_filtergraph(fg)) {
03152 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
03153 exit(1);
03154 }
03155 }
03156
03157 switch (codec->codec_type) {
03158 case AVMEDIA_TYPE_AUDIO:
03159 codec->sample_fmt = ost->filter->filter->inputs[0]->format;
03160 codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
03161 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
03162 codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
03163 codec->time_base = (AVRational){ 1, codec->sample_rate };
03164 break;
03165 case AVMEDIA_TYPE_VIDEO:
03166 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
03167 if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
03168 && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
03169 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
03170 "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
03171 }
03172 for (j = 0; j < ost->forced_kf_count; j++)
03173 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
03174 AV_TIME_BASE_Q,
03175 codec->time_base);
03176
03177 codec->width = ost->filter->filter->inputs[0]->w;
03178 codec->height = ost->filter->filter->inputs[0]->h;
03179 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
03180 ost->frame_aspect_ratio ?
03181 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
03182 ost->filter->filter->inputs[0]->sample_aspect_ratio;
03183 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
03184
03185 if (codec->width != icodec->width ||
03186 codec->height != icodec->height ||
03187 codec->pix_fmt != icodec->pix_fmt) {
03188 codec->bits_per_raw_sample = frame_bits_per_raw_sample;
03189 }
03190
03191 break;
03192 case AVMEDIA_TYPE_SUBTITLE:
03193 codec->time_base = (AVRational){1, 1000};
03194 break;
03195 default:
03196 abort();
03197 break;
03198 }
03199
03200 if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
03201 char logfilename[1024];
03202 FILE *f;
03203
03204 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
03205 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
03206 i);
03207 if (!strcmp(ost->enc->name, "libx264")) {
03208 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
03209 } else {
03210 if (codec->flags & CODEC_FLAG_PASS2) {
03211 char *logbuffer;
03212 size_t logbuffer_size;
03213 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
03214 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
03215 logfilename);
03216 exit_program(1);
03217 }
03218 codec->stats_in = logbuffer;
03219 }
03220 if (codec->flags & CODEC_FLAG_PASS1) {
03221 f = fopen(logfilename, "wb");
03222 if (!f) {
03223 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
03224 logfilename, strerror(errno));
03225 exit_program(1);
03226 }
03227 ost->logfile = f;
03228 }
03229 }
03230 }
03231 }
03232 }
03233
03234
03235 for (i = 0; i < nb_output_streams; i++) {
03236 ost = output_streams[i];
03237 if (ost->encoding_needed) {
03238 AVCodec *codec = ost->enc;
03239 AVCodecContext *dec = NULL;
03240
03241 if ((ist = get_input_stream(ost)))
03242 dec = ist->st->codec;
03243 if (dec && dec->subtitle_header) {
03244 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
03245 if (!ost->st->codec->subtitle_header) {
03246 ret = AVERROR(ENOMEM);
03247 goto dump_format;
03248 }
03249 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
03250 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
03251 }
03252 if (!av_dict_get(ost->opts, "threads", NULL, 0))
03253 av_dict_set(&ost->opts, "threads", "auto", 0);
03254 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
03255 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
03256 ost->file_index, ost->index);
03257 ret = AVERROR(EINVAL);
03258 goto dump_format;
03259 }
03260 assert_codec_experimental(ost->st->codec, 1);
03261 assert_avoptions(ost->opts);
03262 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
03263 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
03264 " It takes bits/s as argument, not kbits/s\n");
03265 extra_size += ost->st->codec->extradata_size;
03266
03267 if (ost->st->codec->me_threshold)
03268 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
03269 }
03270 }
03271
03272
03273 for (i = 0; i < nb_input_streams; i++)
03274 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
03275 goto dump_format;
03276
03277
03278 for (i = 0; i < nb_input_files; i++) {
03279 InputFile *ifile = input_files[i];
03280 for (j = 0; j < ifile->ctx->nb_programs; j++) {
03281 AVProgram *p = ifile->ctx->programs[j];
03282 int discard = AVDISCARD_ALL;
03283
03284 for (k = 0; k < p->nb_stream_indexes; k++)
03285 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
03286 discard = AVDISCARD_DEFAULT;
03287 break;
03288 }
03289 p->discard = discard;
03290 }
03291 }
03292
03293
03294 for (i = 0; i < nb_output_files; i++) {
03295 oc = output_files[i]->ctx;
03296 oc->interrupt_callback = int_cb;
03297 if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
03298 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
03299 ret = AVERROR(EINVAL);
03300 goto dump_format;
03301 }
03302
03303 if (strcmp(oc->oformat->name, "rtp")) {
03304 want_sdp = 0;
03305 }
03306 }
03307
03308 dump_format:
03309
03310
03311 for (i = 0; i < nb_output_files; i++) {
03312 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
03313 }
03314
03315
03316 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
03317 for (i = 0; i < nb_input_streams; i++) {
03318 ist = input_streams[i];
03319
03320 for (j = 0; j < ist->nb_filters; j++) {
03321 AVFilterLink *link = ist->filters[j]->filter->outputs[0];
03322 if (ist->filters[j]->graph->graph_desc) {
03323 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
03324 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
03325 link->dst->filter->name);
03326 if (link->dst->input_count > 1)
03327 av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
03328 if (nb_filtergraphs > 1)
03329 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
03330 av_log(NULL, AV_LOG_INFO, "\n");
03331 }
03332 }
03333 }
03334
03335 for (i = 0; i < nb_output_streams; i++) {
03336 ost = output_streams[i];
03337
03338 if (ost->attachment_filename) {
03339
03340 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
03341 ost->attachment_filename, ost->file_index, ost->index);
03342 continue;
03343 }
03344
03345 if (ost->filter && ost->filter->graph->graph_desc) {
03346
03347 AVFilterLink *link = ost->filter->filter->inputs[0];
03348 av_log(NULL, AV_LOG_INFO, " %s", link->src->filter->name);
03349 if (link->src->output_count > 1)
03350 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
03351 if (nb_filtergraphs > 1)
03352 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
03353
03354 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
03355 ost->index, ost->enc ? ost->enc->name : "?");
03356 continue;
03357 }
03358
03359 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
03360 input_streams[ost->source_index]->file_index,
03361 input_streams[ost->source_index]->st->index,
03362 ost->file_index,
03363 ost->index);
03364 if (ost->sync_ist != input_streams[ost->source_index])
03365 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
03366 ost->sync_ist->file_index,
03367 ost->sync_ist->st->index);
03368 if (ost->stream_copy)
03369 av_log(NULL, AV_LOG_INFO, " (copy)");
03370 else
03371 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
03372 input_streams[ost->source_index]->dec->name : "?",
03373 ost->enc ? ost->enc->name : "?");
03374 av_log(NULL, AV_LOG_INFO, "\n");
03375 }
03376
03377 if (ret) {
03378 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
03379 return ret;
03380 }
03381
03382 if (want_sdp) {
03383 print_sdp();
03384 }
03385
03386 return 0;
03387 }
03388
03389
03390
03391
03392 static int transcode(void)
03393 {
03394 int ret, i;
03395 AVFormatContext *is, *os;
03396 OutputStream *ost;
03397 InputStream *ist;
03398 uint8_t *no_packet;
03399 int no_packet_count = 0;
03400 int64_t timer_start;
03401 int key;
03402
03403 if (!(no_packet = av_mallocz(nb_input_files)))
03404 exit_program(1);
03405
03406 ret = transcode_init();
03407 if (ret < 0)
03408 goto fail;
03409
03410 if (!using_stdin) {
03411 av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
03412 }
03413
03414 timer_start = av_gettime();
03415
03416 for (; received_sigterm == 0;) {
03417 int file_index, ist_index, past_recording_time = 1;
03418 AVPacket pkt;
03419 int64_t ipts_min;
03420 int64_t cur_time= av_gettime();
03421
03422 ipts_min = INT64_MAX;
03423
03424 if (!using_stdin) {
03425 static int64_t last_time;
03426 if (received_nb_signals)
03427 break;
03428
03429 if(cur_time - last_time >= 100000 && !run_as_daemon){
03430 key = read_key();
03431 last_time = cur_time;
03432 }else
03433 key = -1;
03434 if (key == 'q')
03435 break;
03436 if (key == '+') av_log_set_level(av_log_get_level()+10);
03437 if (key == '-') av_log_set_level(av_log_get_level()-10);
03438 if (key == 's') qp_hist ^= 1;
03439 if (key == 'h'){
03440 if (do_hex_dump){
03441 do_hex_dump = do_pkt_dump = 0;
03442 } else if(do_pkt_dump){
03443 do_hex_dump = 1;
03444 } else
03445 do_pkt_dump = 1;
03446 av_log_set_level(AV_LOG_DEBUG);
03447 }
03448 if (key == 'c' || key == 'C'){
03449 char buf[4096], target[64], command[256], arg[256] = {0};
03450 double time;
03451 int k, n = 0;
03452 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
03453 i = 0;
03454 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
03455 if (k > 0)
03456 buf[i++] = k;
03457 buf[i] = 0;
03458 if (k > 0 &&
03459 (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
03460 av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
03461 target, time, command, arg);
03462 for (i = 0; i < nb_filtergraphs; i++) {
03463 FilterGraph *fg = filtergraphs[i];
03464 if (fg->graph) {
03465 if (time < 0) {
03466 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
03467 key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
03468 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
03469 } else {
03470 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
03471 }
03472 }
03473 }
03474 } else {
03475 av_log(NULL, AV_LOG_ERROR,
03476 "Parse error, at least 3 arguments were expected, "
03477 "only %d given in string '%s'\n", n, buf);
03478 }
03479 }
03480 if (key == 'd' || key == 'D'){
03481 int debug=0;
03482 if(key == 'D') {
03483 debug = input_streams[0]->st->codec->debug<<1;
03484 if(!debug) debug = 1;
03485 while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE))
03486 debug += debug;
03487 }else
03488 if(scanf("%d", &debug)!=1)
03489 fprintf(stderr,"error parsing debug value\n");
03490 for(i=0;i<nb_input_streams;i++) {
03491 input_streams[i]->st->codec->debug = debug;
03492 }
03493 for(i=0;i<nb_output_streams;i++) {
03494 ost = output_streams[i];
03495 ost->st->codec->debug = debug;
03496 }
03497 if(debug) av_log_set_level(AV_LOG_DEBUG);
03498 fprintf(stderr,"debug=%d\n", debug);
03499 }
03500 if (key == '?'){
03501 fprintf(stderr, "key function\n"
03502 "? show this help\n"
03503 "+ increase verbosity\n"
03504 "- decrease verbosity\n"
03505 "c Send command to filtergraph\n"
03506 "D cycle through available debug modes\n"
03507 "h dump packets/hex press to cycle through the 3 states\n"
03508 "q quit\n"
03509 "s Show QP histogram\n"
03510 );
03511 }
03512 }
03513
03514
03515 for (i = 0; i < nb_output_streams; i++) {
03516 OutputFile *of;
03517 ost = output_streams[i];
03518 of = output_files[ost->file_index];
03519 os = output_files[ost->file_index]->ctx;
03520 if (ost->is_past_recording_time ||
03521 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
03522 continue;
03523 if (ost->frame_number >= ost->max_frames) {
03524 int j;
03525 for (j = 0; j < of->ctx->nb_streams; j++)
03526 output_streams[of->ost_index + j]->is_past_recording_time = 1;
03527 continue;
03528 }
03529 past_recording_time = 0;
03530 }
03531 if (past_recording_time)
03532 break;
03533
03534
03535
03536 file_index = -1;
03537 for (i = 0; i < nb_input_streams; i++) {
03538 int64_t ipts;
03539 ist = input_streams[i];
03540 ipts = ist->pts;
03541 if (ist->discard || no_packet[ist->file_index])
03542 continue;
03543 if (!input_files[ist->file_index]->eof_reached) {
03544 if (ipts < ipts_min) {
03545 ipts_min = ipts;
03546 file_index = ist->file_index;
03547 }
03548 }
03549 }
03550
03551 if (file_index < 0) {
03552 if (no_packet_count) {
03553 no_packet_count = 0;
03554 memset(no_packet, 0, nb_input_files);
03555 usleep(10000);
03556 continue;
03557 }
03558 break;
03559 }
03560
03561
03562 is = input_files[file_index]->ctx;
03563 ret = av_read_frame(is, &pkt);
03564 if (ret == AVERROR(EAGAIN)) {
03565 no_packet[file_index] = 1;
03566 no_packet_count++;
03567 continue;
03568 }
03569 if (ret < 0) {
03570 input_files[file_index]->eof_reached = 1;
03571
03572 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
03573 ist = input_streams[input_files[file_index]->ist_index + i];
03574 if (ist->decoding_needed)
03575 output_packet(ist, NULL);
03576 }
03577
03578 if (opt_shortest)
03579 break;
03580 else
03581 continue;
03582 }
03583
03584 no_packet_count = 0;
03585 memset(no_packet, 0, nb_input_files);
03586
03587 if (do_pkt_dump) {
03588 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
03589 is->streams[pkt.stream_index]);
03590 }
03591
03592
03593 if (pkt.stream_index >= input_files[file_index]->nb_streams)
03594 goto discard_packet;
03595 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
03596 ist = input_streams[ist_index];
03597 if (ist->discard)
03598 goto discard_packet;
03599
03600 if (pkt.dts != AV_NOPTS_VALUE)
03601 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
03602 if (pkt.pts != AV_NOPTS_VALUE)
03603 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
03604
03605 if (pkt.pts != AV_NOPTS_VALUE)
03606 pkt.pts *= ist->ts_scale;
03607 if (pkt.dts != AV_NOPTS_VALUE)
03608 pkt.dts *= ist->ts_scale;
03609
03610 if (debug_ts) {
03611 av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
03612 "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
03613 ist_index, av_get_media_type_string(ist->st->codec->codec_type),
03614 av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &ist->st->time_base),
03615 av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
03616 av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
03617 av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
03618 input_files[ist->file_index]->ts_offset);
03619 }
03620
03621 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
03622 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
03623 int64_t delta = pkt_dts - ist->next_dts;
03624 if (is->iformat->flags & AVFMT_TS_DISCONT) {
03625 if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
03626 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
03627 ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
03628 pkt_dts+1<ist->pts){
03629 input_files[ist->file_index]->ts_offset -= delta;
03630 av_log(NULL, AV_LOG_DEBUG,
03631 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
03632 delta, input_files[ist->file_index]->ts_offset);
03633 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03634 if (pkt.pts != AV_NOPTS_VALUE)
03635 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
03636 }
03637 } else {
03638 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
03639 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
03640 pkt_dts+1<ist->pts){
03641 av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
03642 pkt.dts = AV_NOPTS_VALUE;
03643 }
03644 if (pkt.pts != AV_NOPTS_VALUE){
03645 int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
03646 delta = pkt_pts - ist->next_dts;
03647 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
03648 (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
03649 pkt_pts+1<ist->pts) {
03650 av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
03651 pkt.pts = AV_NOPTS_VALUE;
03652 }
03653 }
03654 }
03655 }
03656
03657
03658 if (output_packet(ist, &pkt) < 0 ||
03659 ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
03660 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
03661 ist->file_index, ist->st->index);
03662 if (exit_on_error)
03663 exit_program(1);
03664 av_free_packet(&pkt);
03665 continue;
03666 }
03667
03668 discard_packet:
03669 av_free_packet(&pkt);
03670
03671
03672 print_report(0, timer_start, cur_time);
03673 }
03674
03675
03676 for (i = 0; i < nb_input_streams; i++) {
03677 ist = input_streams[i];
03678 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
03679 output_packet(ist, NULL);
03680 }
03681 }
03682 poll_filters();
03683 flush_encoders();
03684
03685 term_exit();
03686
03687
03688 for (i = 0; i < nb_output_files; i++) {
03689 os = output_files[i]->ctx;
03690 av_write_trailer(os);
03691 }
03692
03693
03694 print_report(1, timer_start, av_gettime());
03695
03696
03697 for (i = 0; i < nb_output_streams; i++) {
03698 ost = output_streams[i];
03699 if (ost->encoding_needed) {
03700 av_freep(&ost->st->codec->stats_in);
03701 avcodec_close(ost->st->codec);
03702 }
03703 }
03704
03705
03706 for (i = 0; i < nb_input_streams; i++) {
03707 ist = input_streams[i];
03708 if (ist->decoding_needed) {
03709 avcodec_close(ist->st->codec);
03710 }
03711 }
03712
03713
03714 ret = 0;
03715
03716 fail:
03717 av_freep(&no_packet);
03718
03719 if (output_streams) {
03720 for (i = 0; i < nb_output_streams; i++) {
03721 ost = output_streams[i];
03722 if (ost) {
03723 if (ost->stream_copy)
03724 av_freep(&ost->st->codec->extradata);
03725 if (ost->logfile) {
03726 fclose(ost->logfile);
03727 ost->logfile = NULL;
03728 }
03729 av_freep(&ost->st->codec->subtitle_header);
03730 av_free(ost->forced_kf_pts);
03731 av_dict_free(&ost->opts);
03732 }
03733 }
03734 }
03735 return ret;
03736 }
03737
03738 static int opt_frame_crop(const char *opt, const char *arg)
03739 {
03740 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
03741 return AVERROR(EINVAL);
03742 }
03743
03744 static int opt_pad(const char *opt, const char *arg)
03745 {
03746 av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
03747 return -1;
03748 }
03749
03750 static int opt_video_channel(const char *opt, const char *arg)
03751 {
03752 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
03753 return opt_default("channel", arg);
03754 }
03755
03756 static int opt_video_standard(const char *opt, const char *arg)
03757 {
03758 av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
03759 return opt_default("standard", arg);
03760 }
03761
03762 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
03763 {
03764 audio_codec_name = arg;
03765 return parse_option(o, "codec:a", arg, options);
03766 }
03767
03768 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
03769 {
03770 video_codec_name = arg;
03771 return parse_option(o, "codec:v", arg, options);
03772 }
03773
03774 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
03775 {
03776 subtitle_codec_name = arg;
03777 return parse_option(o, "codec:s", arg, options);
03778 }
03779
03780 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
03781 {
03782 return parse_option(o, "codec:d", arg, options);
03783 }
03784
03785 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
03786 {
03787 StreamMap *m = NULL;
03788 int i, negative = 0, file_idx;
03789 int sync_file_idx = -1, sync_stream_idx = 0;
03790 char *p, *sync;
03791 char *map;
03792
03793 if (*arg == '-') {
03794 negative = 1;
03795 arg++;
03796 }
03797 map = av_strdup(arg);
03798
03799
03800 if (sync = strchr(map, ',')) {
03801 *sync = 0;
03802 sync_file_idx = strtol(sync + 1, &sync, 0);
03803 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
03804 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
03805 exit_program(1);
03806 }
03807 if (*sync)
03808 sync++;
03809 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
03810 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
03811 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
03812 sync_stream_idx = i;
03813 break;
03814 }
03815 if (i == input_files[sync_file_idx]->nb_streams) {
03816 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
03817 "match any streams.\n", arg);
03818 exit_program(1);
03819 }
03820 }
03821
03822
03823 if (map[0] == '[') {
03824
03825 const char *c = map + 1;
03826 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
03827 &o->nb_stream_maps, o->nb_stream_maps + 1);
03828 m = &o->stream_maps[o->nb_stream_maps - 1];
03829 m->linklabel = av_get_token(&c, "]");
03830 if (!m->linklabel) {
03831 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
03832 exit_program(1);
03833 }
03834 } else {
03835 file_idx = strtol(map, &p, 0);
03836 if (file_idx >= nb_input_files || file_idx < 0) {
03837 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
03838 exit_program(1);
03839 }
03840 if (negative)
03841
03842 for (i = 0; i < o->nb_stream_maps; i++) {
03843 m = &o->stream_maps[i];
03844 if (file_idx == m->file_index &&
03845 check_stream_specifier(input_files[m->file_index]->ctx,
03846 input_files[m->file_index]->ctx->streams[m->stream_index],
03847 *p == ':' ? p + 1 : p) > 0)
03848 m->disabled = 1;
03849 }
03850 else
03851 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
03852 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
03853 *p == ':' ? p + 1 : p) <= 0)
03854 continue;
03855 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
03856 &o->nb_stream_maps, o->nb_stream_maps + 1);
03857 m = &o->stream_maps[o->nb_stream_maps - 1];
03858
03859 m->file_index = file_idx;
03860 m->stream_index = i;
03861
03862 if (sync_file_idx >= 0) {
03863 m->sync_file_index = sync_file_idx;
03864 m->sync_stream_index = sync_stream_idx;
03865 } else {
03866 m->sync_file_index = file_idx;
03867 m->sync_stream_index = i;
03868 }
03869 }
03870 }
03871
03872 if (!m) {
03873 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
03874 exit_program(1);
03875 }
03876
03877 av_freep(&map);
03878 return 0;
03879 }
03880
03881 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
03882 {
03883 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
03884 &o->nb_attachments, o->nb_attachments + 1);
03885 o->attachments[o->nb_attachments - 1] = arg;
03886 return 0;
03887 }
03888
03889 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
03890 {
03891 int n;
03892 AVStream *st;
03893 AudioChannelMap *m;
03894
03895 o->audio_channel_maps =
03896 grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
03897 &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
03898 m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
03899
03900
03901 n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
03902 if ((n == 1 || n == 3) && m->channel_idx == -1) {
03903 m->file_idx = m->stream_idx = -1;
03904 if (n == 1)
03905 m->ofile_idx = m->ostream_idx = -1;
03906 return 0;
03907 }
03908
03909
03910 n = sscanf(arg, "%d.%d.%d:%d.%d",
03911 &m->file_idx, &m->stream_idx, &m->channel_idx,
03912 &m->ofile_idx, &m->ostream_idx);
03913
03914 if (n != 3 && n != 5) {
03915 av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
03916 "[file.stream.channel|-1][:syncfile:syncstream]\n");
03917 exit_program(1);
03918 }
03919
03920 if (n != 5)
03921 m->ofile_idx = m->ostream_idx = -1;
03922
03923
03924 if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
03925 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
03926 m->file_idx);
03927 exit_program(1);
03928 }
03929 if (m->stream_idx < 0 ||
03930 m->stream_idx >= input_files[m->file_idx]->nb_streams) {
03931 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
03932 m->file_idx, m->stream_idx);
03933 exit_program(1);
03934 }
03935 st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
03936 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
03937 av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
03938 m->file_idx, m->stream_idx);
03939 exit_program(1);
03940 }
03941 if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
03942 av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
03943 m->file_idx, m->stream_idx, m->channel_idx);
03944 exit_program(1);
03945 }
03946 return 0;
03947 }
03948
03955 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
03956 {
03957 if (*arg) {
03958 *type = *arg;
03959 switch (*arg) {
03960 case 'g':
03961 break;
03962 case 's':
03963 if (*(++arg) && *arg != ':') {
03964 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
03965 exit_program(1);
03966 }
03967 *stream_spec = *arg == ':' ? arg + 1 : "";
03968 break;
03969 case 'c':
03970 case 'p':
03971 if (*(++arg) == ':')
03972 *index = strtol(++arg, NULL, 0);
03973 break;
03974 default:
03975 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
03976 exit_program(1);
03977 }
03978 } else
03979 *type = 'g';
03980 }
03981
03982 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
03983 {
03984 AVDictionary **meta_in = NULL;
03985 AVDictionary **meta_out = NULL;
03986 int i, ret = 0;
03987 char type_in, type_out;
03988 const char *istream_spec = NULL, *ostream_spec = NULL;
03989 int idx_in = 0, idx_out = 0;
03990
03991 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
03992 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
03993
03994 if (!ic) {
03995 if (type_out == 'g' || !*outspec)
03996 o->metadata_global_manual = 1;
03997 if (type_out == 's' || !*outspec)
03998 o->metadata_streams_manual = 1;
03999 if (type_out == 'c' || !*outspec)
04000 o->metadata_chapters_manual = 1;
04001 return 0;
04002 }
04003
04004 if (type_in == 'g' || type_out == 'g')
04005 o->metadata_global_manual = 1;
04006 if (type_in == 's' || type_out == 's')
04007 o->metadata_streams_manual = 1;
04008 if (type_in == 'c' || type_out == 'c')
04009 o->metadata_chapters_manual = 1;
04010
04011 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
04012 if ((index) < 0 || (index) >= (nb_elems)) {\
04013 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
04014 (desc), (index));\
04015 exit_program(1);\
04016 }
04017
04018 #define SET_DICT(type, meta, context, index)\
04019 switch (type) {\
04020 case 'g':\
04021 meta = &context->metadata;\
04022 break;\
04023 case 'c':\
04024 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
04025 meta = &context->chapters[index]->metadata;\
04026 break;\
04027 case 'p':\
04028 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
04029 meta = &context->programs[index]->metadata;\
04030 break;\
04031 }\
04032
04033 SET_DICT(type_in, meta_in, ic, idx_in);
04034 SET_DICT(type_out, meta_out, oc, idx_out);
04035
04036
04037 if (type_in == 's') {
04038 for (i = 0; i < ic->nb_streams; i++) {
04039 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
04040 meta_in = &ic->streams[i]->metadata;
04041 break;
04042 } else if (ret < 0)
04043 exit_program(1);
04044 }
04045 if (!meta_in) {
04046 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
04047 exit_program(1);
04048 }
04049 }
04050
04051 if (type_out == 's') {
04052 for (i = 0; i < oc->nb_streams; i++) {
04053 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
04054 meta_out = &oc->streams[i]->metadata;
04055 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
04056 } else if (ret < 0)
04057 exit_program(1);
04058 }
04059 } else
04060 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
04061
04062 return 0;
04063 }
04064
04065 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
04066 {
04067 char buf[128];
04068 int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
04069 struct tm time = *gmtime((time_t*)&recording_timestamp);
04070 strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
04071 parse_option(o, "metadata", buf, options);
04072
04073 av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
04074 "tag instead.\n", opt);
04075 return 0;
04076 }
04077
04078 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
04079 {
04080 const char *codec_string = encoder ? "encoder" : "decoder";
04081 AVCodec *codec;
04082
04083 codec = encoder ?
04084 avcodec_find_encoder_by_name(name) :
04085 avcodec_find_decoder_by_name(name);
04086 if (!codec) {
04087 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
04088 exit_program(1);
04089 }
04090 if (codec->type != type) {
04091 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
04092 exit_program(1);
04093 }
04094 return codec;
04095 }
04096
04097 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
04098 {
04099 char *codec_name = NULL;
04100
04101 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
04102 if (codec_name) {
04103 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
04104 st->codec->codec_id = codec->id;
04105 return codec;
04106 } else
04107 return avcodec_find_decoder(st->codec->codec_id);
04108 }
04109
04114 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
04115 {
04116 int i;
04117 char *next, *codec_tag = NULL;
04118
04119 for (i = 0; i < ic->nb_streams; i++) {
04120 AVStream *st = ic->streams[i];
04121 AVCodecContext *dec = st->codec;
04122 InputStream *ist = av_mallocz(sizeof(*ist));
04123
04124 if (!ist)
04125 exit_program(1);
04126
04127 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
04128 input_streams[nb_input_streams - 1] = ist;
04129
04130 ist->st = st;
04131 ist->file_index = nb_input_files;
04132 ist->discard = 1;
04133 st->discard = AVDISCARD_ALL;
04134 ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
04135
04136 ist->ts_scale = 1.0;
04137 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
04138
04139 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
04140 if (codec_tag) {
04141 uint32_t tag = strtol(codec_tag, &next, 0);
04142 if (*next)
04143 tag = AV_RL32(codec_tag);
04144 st->codec->codec_tag = tag;
04145 }
04146
04147 ist->dec = choose_decoder(o, ic, st);
04148
04149 switch (dec->codec_type) {
04150 case AVMEDIA_TYPE_VIDEO:
04151 if(!ist->dec)
04152 ist->dec = avcodec_find_decoder(dec->codec_id);
04153 if (dec->lowres) {
04154 dec->flags |= CODEC_FLAG_EMU_EDGE;
04155 }
04156
04157 ist->resample_height = dec->height;
04158 ist->resample_width = dec->width;
04159 ist->resample_pix_fmt = dec->pix_fmt;
04160
04161 break;
04162 case AVMEDIA_TYPE_AUDIO:
04163 guess_input_channel_layout(ist);
04164
04165 ist->resample_sample_fmt = dec->sample_fmt;
04166 ist->resample_sample_rate = dec->sample_rate;
04167 ist->resample_channels = dec->channels;
04168 ist->resample_channel_layout = dec->channel_layout;
04169
04170 break;
04171 case AVMEDIA_TYPE_DATA:
04172 case AVMEDIA_TYPE_SUBTITLE:
04173 if(!ist->dec)
04174 ist->dec = avcodec_find_decoder(dec->codec_id);
04175 break;
04176 case AVMEDIA_TYPE_ATTACHMENT:
04177 case AVMEDIA_TYPE_UNKNOWN:
04178 break;
04179 default:
04180 abort();
04181 }
04182 }
04183 }
04184
04185 static void assert_file_overwrite(const char *filename)
04186 {
04187 if ((!file_overwrite || no_file_overwrite) &&
04188 (strchr(filename, ':') == NULL || filename[1] == ':' ||
04189 av_strstart(filename, "file:", NULL))) {
04190 if (avio_check(filename, 0) == 0) {
04191 if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
04192 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
04193 fflush(stderr);
04194 term_exit();
04195 signal(SIGINT, SIG_DFL);
04196 if (!read_yesno()) {
04197 av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
04198 exit_program(1);
04199 }
04200 term_init();
04201 }
04202 else {
04203 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
04204 exit_program(1);
04205 }
04206 }
04207 }
04208 }
04209
04210 static void dump_attachment(AVStream *st, const char *filename)
04211 {
04212 int ret;
04213 AVIOContext *out = NULL;
04214 AVDictionaryEntry *e;
04215
04216 if (!st->codec->extradata_size) {
04217 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
04218 nb_input_files - 1, st->index);
04219 return;
04220 }
04221 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
04222 filename = e->value;
04223 if (!*filename) {
04224 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
04225 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
04226 exit_program(1);
04227 }
04228
04229 assert_file_overwrite(filename);
04230
04231 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
04232 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
04233 filename);
04234 exit_program(1);
04235 }
04236
04237 avio_write(out, st->codec->extradata, st->codec->extradata_size);
04238 avio_flush(out);
04239 avio_close(out);
04240 }
04241
04242 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
04243 {
04244 AVFormatContext *ic;
04245 AVInputFormat *file_iformat = NULL;
04246 int err, i, ret;
04247 int64_t timestamp;
04248 uint8_t buf[128];
04249 AVDictionary **opts;
04250 int orig_nb_streams;
04251
04252 if (o->format) {
04253 if (!(file_iformat = av_find_input_format(o->format))) {
04254 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
04255 exit_program(1);
04256 }
04257 }
04258
04259 if (!strcmp(filename, "-"))
04260 filename = "pipe:";
04261
04262 using_stdin |= !strncmp(filename, "pipe:", 5) ||
04263 !strcmp(filename, "/dev/stdin");
04264
04265
04266 ic = avformat_alloc_context();
04267 if (!ic) {
04268 print_error(filename, AVERROR(ENOMEM));
04269 exit_program(1);
04270 }
04271 if (o->nb_audio_sample_rate) {
04272 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
04273 av_dict_set(&format_opts, "sample_rate", buf, 0);
04274 }
04275 if (o->nb_audio_channels) {
04276
04277
04278
04279 if (file_iformat && file_iformat->priv_class &&
04280 av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
04281 AV_OPT_SEARCH_FAKE_OBJ)) {
04282 snprintf(buf, sizeof(buf), "%d",
04283 o->audio_channels[o->nb_audio_channels - 1].u.i);
04284 av_dict_set(&format_opts, "channels", buf, 0);
04285 }
04286 }
04287 if (o->nb_frame_rates) {
04288 av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
04289 }
04290 if (o->nb_frame_sizes) {
04291 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
04292 }
04293 if (o->nb_frame_pix_fmts)
04294 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
04295
04296 ic->video_codec_id = video_codec_name ?
04297 find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0)->id : CODEC_ID_NONE;
04298 ic->audio_codec_id = audio_codec_name ?
04299 find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0)->id : CODEC_ID_NONE;
04300 ic->subtitle_codec_id= subtitle_codec_name ?
04301 find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
04302 ic->flags |= AVFMT_FLAG_NONBLOCK;
04303 ic->interrupt_callback = int_cb;
04304
04305
04306 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
04307 if (err < 0) {
04308 print_error(filename, err);
04309 exit_program(1);
04310 }
04311 assert_avoptions(format_opts);
04312
04313
04314 for (i = 0; i < ic->nb_streams; i++)
04315 choose_decoder(o, ic, ic->streams[i]);
04316
04317
04318 opts = setup_find_stream_info_opts(ic, codec_opts);
04319 orig_nb_streams = ic->nb_streams;
04320
04321
04322
04323 ret = avformat_find_stream_info(ic, opts);
04324 if (ret < 0) {
04325 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
04326 avformat_close_input(&ic);
04327 exit_program(1);
04328 }
04329
04330 timestamp = o->start_time;
04331
04332 if (ic->start_time != AV_NOPTS_VALUE)
04333 timestamp += ic->start_time;
04334
04335
04336 if (o->start_time != 0) {
04337 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
04338 if (ret < 0) {
04339 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
04340 filename, (double)timestamp / AV_TIME_BASE);
04341 }
04342 }
04343
04344
04345 add_input_streams(o, ic);
04346
04347
04348 av_dump_format(ic, nb_input_files, filename, 0);
04349
04350 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
04351 if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
04352 exit_program(1);
04353
04354 input_files[nb_input_files - 1]->ctx = ic;
04355 input_files[nb_input_files - 1]->ist_index = nb_input_streams - ic->nb_streams;
04356 input_files[nb_input_files - 1]->ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
04357 input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
04358 input_files[nb_input_files - 1]->rate_emu = o->rate_emu;
04359
04360 for (i = 0; i < o->nb_dump_attachment; i++) {
04361 int j;
04362
04363 for (j = 0; j < ic->nb_streams; j++) {
04364 AVStream *st = ic->streams[j];
04365
04366 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
04367 dump_attachment(st, o->dump_attachment[i].u.str);
04368 }
04369 }
04370
04371 for (i = 0; i < orig_nb_streams; i++)
04372 av_dict_free(&opts[i]);
04373 av_freep(&opts);
04374
04375 reset_options(o, 1);
04376 return 0;
04377 }
04378
04379 static void parse_forced_key_frames(char *kf, OutputStream *ost)
04380 {
04381 char *p;
04382 int n = 1, i;
04383
04384 for (p = kf; *p; p++)
04385 if (*p == ',')
04386 n++;
04387 ost->forced_kf_count = n;
04388 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
04389 if (!ost->forced_kf_pts) {
04390 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
04391 exit_program(1);
04392 }
04393 p = kf;
04394 for (i = 0; i < n; i++) {
04395 char *next = strchr(p, ',');
04396 if (next) *next++ = 0;
04397 ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
04398 p = next;
04399 }
04400 }
04401
04402 static uint8_t *get_line(AVIOContext *s)
04403 {
04404 AVIOContext *line;
04405 uint8_t *buf;
04406 char c;
04407
04408 if (avio_open_dyn_buf(&line) < 0) {
04409 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
04410 exit_program(1);
04411 }
04412
04413 while ((c = avio_r8(s)) && c != '\n')
04414 avio_w8(line, c);
04415 avio_w8(line, 0);
04416 avio_close_dyn_buf(line, &buf);
04417
04418 return buf;
04419 }
04420
04421 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
04422 {
04423 int i, ret = 1;
04424 char filename[1000];
04425 const char *base[3] = { getenv("AVCONV_DATADIR"),
04426 getenv("HOME"),
04427 AVCONV_DATADIR,
04428 };
04429
04430 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
04431 if (!base[i])
04432 continue;
04433 if (codec_name) {
04434 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
04435 i != 1 ? "" : "/.avconv", codec_name, preset_name);
04436 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
04437 }
04438 if (ret) {
04439 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
04440 i != 1 ? "" : "/.avconv", preset_name);
04441 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
04442 }
04443 }
04444 return ret;
04445 }
04446
04447 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
04448 {
04449 char *codec_name = NULL;
04450
04451 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
04452 if (!codec_name) {
04453 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
04454 NULL, ost->st->codec->codec_type);
04455 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
04456 } else if (!strcmp(codec_name, "copy"))
04457 ost->stream_copy = 1;
04458 else {
04459 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
04460 ost->st->codec->codec_id = ost->enc->id;
04461 }
04462 }
04463
04464 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
04465 {
04466 OutputStream *ost;
04467 AVStream *st = avformat_new_stream(oc, NULL);
04468 int idx = oc->nb_streams - 1, ret = 0;
04469 char *bsf = NULL, *next, *codec_tag = NULL;
04470 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
04471 double qscale = -1;
04472 char *buf = NULL, *arg = NULL, *preset = NULL;
04473 AVIOContext *s = NULL;
04474
04475 if (!st) {
04476 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
04477 exit_program(1);
04478 }
04479
04480 if (oc->nb_streams - 1 < o->nb_streamid_map)
04481 st->id = o->streamid_map[oc->nb_streams - 1];
04482
04483 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
04484 nb_output_streams + 1);
04485 if (!(ost = av_mallocz(sizeof(*ost))))
04486 exit_program(1);
04487 output_streams[nb_output_streams - 1] = ost;
04488
04489 ost->file_index = nb_output_files;
04490 ost->index = idx;
04491 ost->st = st;
04492 st->codec->codec_type = type;
04493 choose_encoder(o, oc, ost);
04494 if (ost->enc) {
04495 ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
04496 }
04497
04498 avcodec_get_context_defaults3(st->codec, ost->enc);
04499 st->codec->codec_type = type;
04500
04501 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
04502 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
04503 do {
04504 buf = get_line(s);
04505 if (!buf[0] || buf[0] == '#') {
04506 av_free(buf);
04507 continue;
04508 }
04509 if (!(arg = strchr(buf, '='))) {
04510 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
04511 exit_program(1);
04512 }
04513 *arg++ = 0;
04514 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
04515 av_free(buf);
04516 } while (!s->eof_reached);
04517 avio_close(s);
04518 }
04519 if (ret) {
04520 av_log(NULL, AV_LOG_FATAL,
04521 "Preset %s specified for stream %d:%d, but could not be opened.\n",
04522 preset, ost->file_index, ost->index);
04523 exit_program(1);
04524 }
04525
04526 ost->max_frames = INT64_MAX;
04527 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
04528
04529 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
04530 while (bsf) {
04531 if (next = strchr(bsf, ','))
04532 *next++ = 0;
04533 if (!(bsfc = av_bitstream_filter_init(bsf))) {
04534 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
04535 exit_program(1);
04536 }
04537 if (bsfc_prev)
04538 bsfc_prev->next = bsfc;
04539 else
04540 ost->bitstream_filters = bsfc;
04541
04542 bsfc_prev = bsfc;
04543 bsf = next;
04544 }
04545
04546 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
04547 if (codec_tag) {
04548 uint32_t tag = strtol(codec_tag, &next, 0);
04549 if (*next)
04550 tag = AV_RL32(codec_tag);
04551 st->codec->codec_tag = tag;
04552 }
04553
04554 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
04555 if (qscale >= 0 || same_quant) {
04556 st->codec->flags |= CODEC_FLAG_QSCALE;
04557 st->codec->global_quality = FF_QP2LAMBDA * qscale;
04558 }
04559
04560 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
04561 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
04562
04563 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
04564 av_opt_get_int (swr_opts, "dither_method", 0, &ost->swr_dither_method);
04565 av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
04566
04567 ost->source_index = source_index;
04568 if (source_index >= 0) {
04569 ost->sync_ist = input_streams[source_index];
04570 input_streams[source_index]->discard = 0;
04571 input_streams[source_index]->st->discard = AVDISCARD_NONE;
04572 }
04573
04574 return ost;
04575 }
04576
04577 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
04578 {
04579 int i;
04580 const char *p = str;
04581 for (i = 0;; i++) {
04582 dest[i] = atoi(p);
04583 if (i == 63)
04584 break;
04585 p = strchr(p, ',');
04586 if (!p) {
04587 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
04588 exit_program(1);
04589 }
04590 p++;
04591 }
04592 }
04593
04594 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
04595 {
04596 AVStream *st;
04597 OutputStream *ost;
04598 AVCodecContext *video_enc;
04599
04600 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
04601 st = ost->st;
04602 video_enc = st->codec;
04603
04604 if (!ost->stream_copy) {
04605 const char *p = NULL;
04606 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
04607 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
04608 char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
04609 int i;
04610
04611 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
04612 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
04613 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
04614 exit_program(1);
04615 }
04616
04617 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
04618 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
04619 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
04620 exit_program(1);
04621 }
04622
04623 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
04624 if (frame_aspect_ratio) {
04625 AVRational q;
04626 if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
04627 q.num <= 0 || q.den <= 0) {
04628 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
04629 exit_program(1);
04630 }
04631 ost->frame_aspect_ratio = av_q2d(q);
04632 }
04633
04634 video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
04635 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
04636 if (frame_pix_fmt && *frame_pix_fmt == '+') {
04637 ost->keep_pix_fmt = 1;
04638 if (!*++frame_pix_fmt)
04639 frame_pix_fmt = NULL;
04640 }
04641 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
04642 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
04643 exit_program(1);
04644 }
04645 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
04646
04647 if (intra_only)
04648 video_enc->gop_size = 0;
04649 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
04650 if (intra_matrix) {
04651 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
04652 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
04653 exit_program(1);
04654 }
04655 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
04656 }
04657 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
04658 if (inter_matrix) {
04659 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
04660 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
04661 exit_program(1);
04662 }
04663 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
04664 }
04665
04666 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
04667 for (i = 0; p; i++) {
04668 int start, end, q;
04669 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
04670 if (e != 3) {
04671 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
04672 exit_program(1);
04673 }
04674
04675 video_enc->rc_override =
04676 av_realloc(video_enc->rc_override,
04677 sizeof(RcOverride) * (i + 1));
04678 video_enc->rc_override[i].start_frame = start;
04679 video_enc->rc_override[i].end_frame = end;
04680 if (q > 0) {
04681 video_enc->rc_override[i].qscale = q;
04682 video_enc->rc_override[i].quality_factor = 1.0;
04683 }
04684 else {
04685 video_enc->rc_override[i].qscale = 0;
04686 video_enc->rc_override[i].quality_factor = -q/100.0;
04687 }
04688 p = strchr(p, '/');
04689 if (p) p++;
04690 }
04691 video_enc->rc_override_count = i;
04692 if (!video_enc->rc_initial_buffer_occupancy)
04693 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
04694 video_enc->intra_dc_precision = intra_dc_precision - 8;
04695
04696 if (do_psnr)
04697 video_enc->flags|= CODEC_FLAG_PSNR;
04698
04699
04700 if (do_pass) {
04701 if (do_pass & 1) {
04702 video_enc->flags |= CODEC_FLAG_PASS1;
04703 }
04704 if (do_pass & 2) {
04705 video_enc->flags |= CODEC_FLAG_PASS2;
04706 }
04707 }
04708
04709 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
04710 if (forced_key_frames)
04711 parse_forced_key_frames(forced_key_frames, ost);
04712
04713 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
04714
04715 ost->top_field_first = -1;
04716 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
04717
04718 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
04719 if (filters)
04720 ost->avfilter = av_strdup(filters);
04721 } else {
04722 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
04723 }
04724
04725 return ost;
04726 }
04727
04728 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
04729 {
04730 int n;
04731 AVStream *st;
04732 OutputStream *ost;
04733 AVCodecContext *audio_enc;
04734
04735 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
04736 st = ost->st;
04737
04738 audio_enc = st->codec;
04739 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
04740
04741 if (!ost->stream_copy) {
04742 char *sample_fmt = NULL, *filters = NULL;
04743
04744 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
04745
04746 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
04747 if (sample_fmt &&
04748 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
04749 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
04750 exit_program(1);
04751 }
04752
04753 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
04754
04755 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
04756 if (filters)
04757 ost->avfilter = av_strdup(filters);
04758
04759
04760 for (n = 0; n < o->nb_audio_channel_maps; n++) {
04761 AudioChannelMap *map = &o->audio_channel_maps[n];
04762 InputStream *ist = input_streams[ost->source_index];
04763 if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
04764 (map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
04765 (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
04766 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
04767 ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
04768 else
04769 av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
04770 ost->file_index, ost->st->index);
04771 }
04772 }
04773 }
04774
04775 return ost;
04776 }
04777
04778 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
04779 {
04780 OutputStream *ost;
04781
04782 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
04783 if (!ost->stream_copy) {
04784 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
04785 exit_program(1);
04786 }
04787
04788 return ost;
04789 }
04790
04791 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
04792 {
04793 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
04794 ost->stream_copy = 1;
04795 return ost;
04796 }
04797
04798 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
04799 {
04800 AVStream *st;
04801 OutputStream *ost;
04802 AVCodecContext *subtitle_enc;
04803
04804 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
04805 st = ost->st;
04806 subtitle_enc = st->codec;
04807
04808 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
04809
04810 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
04811
04812 return ost;
04813 }
04814
04815
04816 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
04817 {
04818 int idx;
04819 char *p;
04820 char idx_str[16];
04821
04822 av_strlcpy(idx_str, arg, sizeof(idx_str));
04823 p = strchr(idx_str, ':');
04824 if (!p) {
04825 av_log(NULL, AV_LOG_FATAL,
04826 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
04827 arg, opt);
04828 exit_program(1);
04829 }
04830 *p++ = '\0';
04831 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
04832 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
04833 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
04834 return 0;
04835 }
04836
04837 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
04838 {
04839 AVFormatContext *is = ifile->ctx;
04840 AVFormatContext *os = ofile->ctx;
04841 int i;
04842
04843 for (i = 0; i < is->nb_chapters; i++) {
04844 AVChapter *in_ch = is->chapters[i], *out_ch;
04845 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
04846 AV_TIME_BASE_Q, in_ch->time_base);
04847 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
04848 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
04849
04850
04851 if (in_ch->end < ts_off)
04852 continue;
04853 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
04854 break;
04855
04856 out_ch = av_mallocz(sizeof(AVChapter));
04857 if (!out_ch)
04858 return AVERROR(ENOMEM);
04859
04860 out_ch->id = in_ch->id;
04861 out_ch->time_base = in_ch->time_base;
04862 out_ch->start = FFMAX(0, in_ch->start - ts_off);
04863 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
04864
04865 if (copy_metadata)
04866 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
04867
04868 os->nb_chapters++;
04869 os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
04870 if (!os->chapters)
04871 return AVERROR(ENOMEM);
04872 os->chapters[os->nb_chapters - 1] = out_ch;
04873 }
04874 return 0;
04875 }
04876
04877 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
04878 {
04879 int i, err;
04880 AVFormatContext *ic = avformat_alloc_context();
04881
04882 ic->interrupt_callback = int_cb;
04883 err = avformat_open_input(&ic, filename, NULL, NULL);
04884 if (err < 0)
04885 return err;
04886
04887 for(i=0;i<ic->nb_streams;i++) {
04888 AVStream *st;
04889 OutputStream *ost;
04890 AVCodec *codec;
04891 AVCodecContext *avctx;
04892
04893 codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
04894 ost = new_output_stream(o, s, codec->type, -1);
04895 st = ost->st;
04896 avctx = st->codec;
04897 ost->enc = codec;
04898
04899
04900 memcpy(st, ic->streams[i], sizeof(AVStream));
04901 st->cur_dts = 0;
04902 st->info = av_malloc(sizeof(*st->info));
04903 memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
04904 st->codec= avctx;
04905 avcodec_copy_context(st->codec, ic->streams[i]->codec);
04906
04907 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
04908 choose_sample_fmt(st, codec);
04909 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
04910 choose_pixel_fmt(st, codec, st->codec->pix_fmt);
04911 }
04912
04913 avformat_close_input(&ic);
04914 return 0;
04915 }
04916
04917 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
04918 AVFormatContext *oc)
04919 {
04920 OutputStream *ost;
04921
04922 switch (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type) {
04923 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
04924 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
04925 default:
04926 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
04927 "currently.\n");
04928 exit_program(1);
04929 }
04930
04931 ost->source_index = -1;
04932 ost->filter = ofilter;
04933
04934 ofilter->ost = ost;
04935
04936 if (ost->stream_copy) {
04937 av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
04938 "which is fed from a complex filtergraph. Filtering and streamcopy "
04939 "cannot be used together.\n", ost->file_index, ost->index);
04940 exit_program(1);
04941 }
04942
04943 if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
04944 av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
04945 exit_program(1);
04946 }
04947 avfilter_inout_free(&ofilter->out_tmp);
04948 }
04949
04950 static void opt_output_file(void *optctx, const char *filename)
04951 {
04952 OptionsContext *o = optctx;
04953 AVFormatContext *oc;
04954 int i, j, err;
04955 AVOutputFormat *file_oformat;
04956 OutputStream *ost;
04957 InputStream *ist;
04958
04959 if (configure_complex_filters() < 0) {
04960 av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
04961 exit_program(1);
04962 }
04963
04964 if (!strcmp(filename, "-"))
04965 filename = "pipe:";
04966
04967 err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
04968 if (!oc) {
04969 print_error(filename, err);
04970 exit_program(1);
04971 }
04972 file_oformat= oc->oformat;
04973 oc->interrupt_callback = int_cb;
04974
04975
04976 for (i = 0; i < nb_filtergraphs; i++) {
04977 FilterGraph *fg = filtergraphs[i];
04978 for (j = 0; j < fg->nb_outputs; j++) {
04979 OutputFilter *ofilter = fg->outputs[j];
04980
04981 if (!ofilter->out_tmp || ofilter->out_tmp->name)
04982 continue;
04983
04984 switch (ofilter->out_tmp->filter_ctx->output_pads[ofilter->out_tmp->pad_idx].type) {
04985 case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
04986 case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
04987 case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
04988 }
04989 init_output_filter(ofilter, o, oc);
04990 }
04991 }
04992
04993 if (!strcmp(file_oformat->name, "ffm") &&
04994 av_strstart(filename, "http:", NULL)) {
04995 int j;
04996
04997
04998 int err = read_ffserver_streams(o, oc, filename);
04999 if (err < 0) {
05000 print_error(filename, err);
05001 exit_program(1);
05002 }
05003 for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
05004 ost = output_streams[j];
05005 for (i = 0; i < nb_input_streams; i++) {
05006 ist = input_streams[i];
05007 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
05008 ost->sync_ist= ist;
05009 ost->source_index= i;
05010 ist->discard = 0;
05011 ist->st->discard = AVDISCARD_NONE;
05012 break;
05013 }
05014 }
05015 if(!ost->sync_ist){
05016 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
05017 exit_program(1);
05018 }
05019 }
05020 } else if (!o->nb_stream_maps) {
05021
05022
05023
05024 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
05025 int area = 0, idx = -1;
05026 for (i = 0; i < nb_input_streams; i++) {
05027 ist = input_streams[i];
05028 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
05029 ist->st->codec->width * ist->st->codec->height > area) {
05030 area = ist->st->codec->width * ist->st->codec->height;
05031 idx = i;
05032 }
05033 }
05034 if (idx >= 0)
05035 new_video_stream(o, oc, idx);
05036 }
05037
05038
05039 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
05040 int channels = 0, idx = -1;
05041 for (i = 0; i < nb_input_streams; i++) {
05042 ist = input_streams[i];
05043 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
05044 ist->st->codec->channels > channels) {
05045 channels = ist->st->codec->channels;
05046 idx = i;
05047 }
05048 }
05049 if (idx >= 0)
05050 new_audio_stream(o, oc, idx);
05051 }
05052
05053
05054 if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
05055 for (i = 0; i < nb_input_streams; i++)
05056 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
05057 new_subtitle_stream(o, oc, i);
05058 break;
05059 }
05060 }
05061
05062 } else {
05063 for (i = 0; i < o->nb_stream_maps; i++) {
05064 StreamMap *map = &o->stream_maps[i];
05065 int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
05066
05067 if (map->disabled)
05068 continue;
05069
05070 if (map->linklabel) {
05071 FilterGraph *fg;
05072 OutputFilter *ofilter = NULL;
05073 int j, k;
05074
05075 for (j = 0; j < nb_filtergraphs; j++) {
05076 fg = filtergraphs[j];
05077 for (k = 0; k < fg->nb_outputs; k++) {
05078 AVFilterInOut *out = fg->outputs[k]->out_tmp;
05079 if (out && !strcmp(out->name, map->linklabel)) {
05080 ofilter = fg->outputs[k];
05081 goto loop_end;
05082 }
05083 }
05084 }
05085 loop_end:
05086 if (!ofilter) {
05087 av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
05088 "in any defined filter graph.\n", map->linklabel);
05089 exit_program(1);
05090 }
05091 init_output_filter(ofilter, o, oc);
05092 } else {
05093 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
05094 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
05095 continue;
05096 if(o-> audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
05097 continue;
05098 if(o-> video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
05099 continue;
05100 if(o-> data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
05101 continue;
05102
05103 switch (ist->st->codec->codec_type) {
05104 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
05105 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
05106 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
05107 case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
05108 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
05109 default:
05110 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
05111 map->file_index, map->stream_index);
05112 exit_program(1);
05113 }
05114 }
05115 }
05116 }
05117
05118
05119 for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) {
05120 AVDictionaryEntry *e;
05121 ost = output_streams[i];
05122
05123 if ( ost->stream_copy
05124 && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
05125 && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
05126 if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
05127 exit_program(1);
05128 }
05129
05130
05131 for (i = 0; i < o->nb_attachments; i++) {
05132 AVIOContext *pb;
05133 uint8_t *attachment;
05134 const char *p;
05135 int64_t len;
05136
05137 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
05138 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
05139 o->attachments[i]);
05140 exit_program(1);
05141 }
05142 if ((len = avio_size(pb)) <= 0) {
05143 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
05144 o->attachments[i]);
05145 exit_program(1);
05146 }
05147 if (!(attachment = av_malloc(len))) {
05148 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
05149 o->attachments[i]);
05150 exit_program(1);
05151 }
05152 avio_read(pb, attachment, len);
05153
05154 ost = new_attachment_stream(o, oc, -1);
05155 ost->stream_copy = 0;
05156 ost->attachment_filename = o->attachments[i];
05157 ost->st->codec->extradata = attachment;
05158 ost->st->codec->extradata_size = len;
05159
05160 p = strrchr(o->attachments[i], '/');
05161 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
05162 avio_close(pb);
05163 }
05164
05165 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
05166 if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
05167 exit_program(1);
05168
05169 output_files[nb_output_files - 1]->ctx = oc;
05170 output_files[nb_output_files - 1]->ost_index = nb_output_streams - oc->nb_streams;
05171 output_files[nb_output_files - 1]->recording_time = o->recording_time;
05172 if (o->recording_time != INT64_MAX)
05173 oc->duration = o->recording_time;
05174 output_files[nb_output_files - 1]->start_time = o->start_time;
05175 output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
05176 av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
05177
05178
05179 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
05180 if (!av_filename_number_test(oc->filename)) {
05181 print_error(oc->filename, AVERROR(EINVAL));
05182 exit_program(1);
05183 }
05184 }
05185
05186 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
05187
05188 assert_file_overwrite(filename);
05189
05190
05191 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
05192 &oc->interrupt_callback,
05193 &output_files[nb_output_files - 1]->opts)) < 0) {
05194 print_error(filename, err);
05195 exit_program(1);
05196 }
05197 }
05198
05199 if (o->mux_preload) {
05200 uint8_t buf[64];
05201 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
05202 av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
05203 }
05204 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
05205
05206
05207 for (i = 0; i < o->nb_metadata_map; i++) {
05208 char *p;
05209 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
05210
05211 if (in_file_index >= nb_input_files) {
05212 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
05213 exit_program(1);
05214 }
05215 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
05216 }
05217
05218
05219 if (o->chapters_input_file >= nb_input_files) {
05220 if (o->chapters_input_file == INT_MAX) {
05221
05222 o->chapters_input_file = -1;
05223 for (i = 0; i < nb_input_files; i++)
05224 if (input_files[i]->ctx->nb_chapters) {
05225 o->chapters_input_file = i;
05226 break;
05227 }
05228 } else {
05229 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
05230 o->chapters_input_file);
05231 exit_program(1);
05232 }
05233 }
05234 if (o->chapters_input_file >= 0)
05235 copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
05236 !o->metadata_chapters_manual);
05237
05238
05239 if (!o->metadata_global_manual && nb_input_files){
05240 av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
05241 AV_DICT_DONT_OVERWRITE);
05242 if(o->recording_time != INT64_MAX)
05243 av_dict_set(&oc->metadata, "duration", NULL, 0);
05244 }
05245 if (!o->metadata_streams_manual)
05246 for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
05247 InputStream *ist;
05248 if (output_streams[i]->source_index < 0)
05249 continue;
05250 ist = input_streams[output_streams[i]->source_index];
05251 av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
05252 }
05253
05254
05255 for (i = 0; i < o->nb_metadata; i++) {
05256 AVDictionary **m;
05257 char type, *val;
05258 const char *stream_spec;
05259 int index = 0, j, ret = 0;
05260
05261 val = strchr(o->metadata[i].u.str, '=');
05262 if (!val) {
05263 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
05264 o->metadata[i].u.str);
05265 exit_program(1);
05266 }
05267 *val++ = 0;
05268
05269 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
05270 if (type == 's') {
05271 for (j = 0; j < oc->nb_streams; j++) {
05272 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
05273 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
05274 } else if (ret < 0)
05275 exit_program(1);
05276 }
05277 printf("ret %d, stream_spec %s\n", ret, stream_spec);
05278 }
05279 else {
05280 switch (type) {
05281 case 'g':
05282 m = &oc->metadata;
05283 break;
05284 case 'c':
05285 if (index < 0 || index >= oc->nb_chapters) {
05286 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
05287 exit_program(1);
05288 }
05289 m = &oc->chapters[index]->metadata;
05290 break;
05291 default:
05292 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
05293 exit_program(1);
05294 }
05295 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
05296 }
05297 }
05298
05299 reset_options(o, 0);
05300 }
05301
05302
05303 static int opt_pass(const char *opt, const char *arg)
05304 {
05305 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
05306 return 0;
05307 }
05308
05309 static int64_t getmaxrss(void)
05310 {
05311 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
05312 struct rusage rusage;
05313 getrusage(RUSAGE_SELF, &rusage);
05314 return (int64_t)rusage.ru_maxrss * 1024;
05315 #elif HAVE_GETPROCESSMEMORYINFO
05316 HANDLE proc;
05317 PROCESS_MEMORY_COUNTERS memcounters;
05318 proc = GetCurrentProcess();
05319 memcounters.cb = sizeof(memcounters);
05320 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
05321 return memcounters.PeakPagefileUsage;
05322 #else
05323 return 0;
05324 #endif
05325 }
05326
05327 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
05328 {
05329 return parse_option(o, "q:a", arg, options);
05330 }
05331
05332 static void show_usage(void)
05333 {
05334 av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
05335 av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
05336 av_log(NULL, AV_LOG_INFO, "\n");
05337 }
05338
05339 static int opt_help(const char *opt, const char *arg)
05340 {
05341 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
05342 av_log_set_callback(log_callback_help);
05343 show_usage();
05344 show_help_options(options, "Main options:\n",
05345 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
05346 show_help_options(options, "\nAdvanced options:\n",
05347 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
05348 OPT_EXPERT);
05349 show_help_options(options, "\nVideo options:\n",
05350 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
05351 OPT_VIDEO);
05352 show_help_options(options, "\nAdvanced Video options:\n",
05353 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
05354 OPT_VIDEO | OPT_EXPERT);
05355 show_help_options(options, "\nAudio options:\n",
05356 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
05357 OPT_AUDIO);
05358 show_help_options(options, "\nAdvanced Audio options:\n",
05359 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
05360 OPT_AUDIO | OPT_EXPERT);
05361 show_help_options(options, "\nSubtitle options:\n",
05362 OPT_SUBTITLE | OPT_GRAB,
05363 OPT_SUBTITLE);
05364 show_help_options(options, "\nAudio/Video grab options:\n",
05365 OPT_GRAB,
05366 OPT_GRAB);
05367 printf("\n");
05368 show_help_children(avcodec_get_class(), flags);
05369 show_help_children(avformat_get_class(), flags);
05370 show_help_children(sws_get_class(), flags);
05371
05372 return 0;
05373 }
05374
05375 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
05376 {
05377 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
05378 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
05379
05380 if (!strncmp(arg, "pal-", 4)) {
05381 norm = PAL;
05382 arg += 4;
05383 } else if (!strncmp(arg, "ntsc-", 5)) {
05384 norm = NTSC;
05385 arg += 5;
05386 } else if (!strncmp(arg, "film-", 5)) {
05387 norm = FILM;
05388 arg += 5;
05389 } else {
05390
05391 if (nb_input_files) {
05392 int i, j, fr;
05393 for (j = 0; j < nb_input_files; j++) {
05394 for (i = 0; i < input_files[j]->nb_streams; i++) {
05395 AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
05396 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
05397 continue;
05398 fr = c->time_base.den * 1000 / c->time_base.num;
05399 if (fr == 25000) {
05400 norm = PAL;
05401 break;
05402 } else if ((fr == 29970) || (fr == 23976)) {
05403 norm = NTSC;
05404 break;
05405 }
05406 }
05407 if (norm != UNKNOWN)
05408 break;
05409 }
05410 }
05411 if (norm != UNKNOWN)
05412 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
05413 }
05414
05415 if (norm == UNKNOWN) {
05416 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
05417 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
05418 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
05419 exit_program(1);
05420 }
05421
05422 if (!strcmp(arg, "vcd")) {
05423 opt_video_codec(o, "c:v", "mpeg1video");
05424 opt_audio_codec(o, "c:a", "mp2");
05425 parse_option(o, "f", "vcd", options);
05426
05427 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
05428 parse_option(o, "r", frame_rates[norm], options);
05429 opt_default("g", norm == PAL ? "15" : "18");
05430
05431 opt_default("b:v", "1150000");
05432 opt_default("maxrate", "1150000");
05433 opt_default("minrate", "1150000");
05434 opt_default("bufsize", "327680");
05435
05436 opt_default("b:a", "224000");
05437 parse_option(o, "ar", "44100", options);
05438 parse_option(o, "ac", "2", options);
05439
05440 opt_default("packetsize", "2324");
05441 opt_default("muxrate", "1411200");
05442
05443
05444
05445
05446
05447
05448 o->mux_preload = (36000 + 3 * 1200) / 90000.0;
05449 } else if (!strcmp(arg, "svcd")) {
05450
05451 opt_video_codec(o, "c:v", "mpeg2video");
05452 opt_audio_codec(o, "c:a", "mp2");
05453 parse_option(o, "f", "svcd", options);
05454
05455 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
05456 parse_option(o, "r", frame_rates[norm], options);
05457 parse_option(o, "pix_fmt", "yuv420p", options);
05458 opt_default("g", norm == PAL ? "15" : "18");
05459
05460 opt_default("b:v", "2040000");
05461 opt_default("maxrate", "2516000");
05462 opt_default("minrate", "0");
05463 opt_default("bufsize", "1835008");
05464 opt_default("scan_offset", "1");
05465
05466
05467 opt_default("b:a", "224000");
05468 parse_option(o, "ar", "44100", options);
05469
05470 opt_default("packetsize", "2324");
05471
05472 } else if (!strcmp(arg, "dvd")) {
05473
05474 opt_video_codec(o, "c:v", "mpeg2video");
05475 opt_audio_codec(o, "c:a", "ac3");
05476 parse_option(o, "f", "dvd", options);
05477
05478 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
05479 parse_option(o, "r", frame_rates[norm], options);
05480 parse_option(o, "pix_fmt", "yuv420p", options);
05481 opt_default("g", norm == PAL ? "15" : "18");
05482
05483 opt_default("b:v", "6000000");
05484 opt_default("maxrate", "9000000");
05485 opt_default("minrate", "0");
05486 opt_default("bufsize", "1835008");
05487
05488 opt_default("packetsize", "2048");
05489 opt_default("muxrate", "10080000");
05490
05491 opt_default("b:a", "448000");
05492 parse_option(o, "ar", "48000", options);
05493
05494 } else if (!strncmp(arg, "dv", 2)) {
05495
05496 parse_option(o, "f", "dv", options);
05497
05498 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
05499 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
05500 norm == PAL ? "yuv420p" : "yuv411p", options);
05501 parse_option(o, "r", frame_rates[norm], options);
05502
05503 parse_option(o, "ar", "48000", options);
05504 parse_option(o, "ac", "2", options);
05505
05506 } else {
05507 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
05508 return AVERROR(EINVAL);
05509 }
05510 return 0;
05511 }
05512
05513 static int opt_vstats_file(const char *opt, const char *arg)
05514 {
05515 av_free (vstats_filename);
05516 vstats_filename = av_strdup (arg);
05517 return 0;
05518 }
05519
05520 static int opt_vstats(const char *opt, const char *arg)
05521 {
05522 char filename[40];
05523 time_t today2 = time(NULL);
05524 struct tm *today = localtime(&today2);
05525
05526 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
05527 today->tm_sec);
05528 return opt_vstats_file(opt, filename);
05529 }
05530
05531 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
05532 {
05533 return parse_option(o, "frames:v", arg, options);
05534 }
05535
05536 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
05537 {
05538 return parse_option(o, "frames:a", arg, options);
05539 }
05540
05541 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
05542 {
05543 return parse_option(o, "frames:d", arg, options);
05544 }
05545
05546 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
05547 {
05548 FILE *f=NULL;
05549 char filename[1000], line[1000], tmp_line[1000];
05550 const char *codec_name = *opt == 'v' ? video_codec_name :
05551 *opt == 'a' ? audio_codec_name :
05552 subtitle_codec_name;
05553
05554 if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
05555 if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
05556 av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
05557 }else
05558 av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
05559 exit_program(1);
05560 }
05561
05562 while (fgets(line, sizeof(line), f)) {
05563 char *key = tmp_line, *value, *endptr;
05564
05565 if (strcspn(line, "#\n\r") == 0)
05566 continue;
05567 strcpy(tmp_line, line);
05568 if (!av_strtok(key, "=", &value) ||
05569 !av_strtok(value, "\r\n", &endptr)) {
05570 av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
05571 exit_program(1);
05572 }
05573 av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
05574
05575 if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
05576 else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
05577 else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
05578 else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
05579 else if (opt_default(key, value) < 0) {
05580 av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
05581 filename, line, key, value);
05582 exit_program(1);
05583 }
05584 }
05585
05586 fclose(f);
05587
05588 return 0;
05589 }
05590
05591 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
05592 {
05593 }
05594
05595 static int opt_passlogfile(const char *opt, const char *arg)
05596 {
05597 pass_logfilename_prefix = arg;
05598 #if CONFIG_LIBX264_ENCODER
05599 return opt_default(opt, arg);
05600 #else
05601 return 0;
05602 #endif
05603 }
05604
05605 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
05606 {
05607 char *s = av_asprintf("%s:%c", opt + 1, *opt);
05608 int ret = parse_option(o, s, arg, options);
05609 av_free(s);
05610 return ret;
05611 }
05612
05613 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
05614 {
05615 if(!strcmp(opt, "b")){
05616 av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
05617 return parse_option(o, "b:v", arg, options);
05618 }
05619 return opt_default(opt, arg);
05620 }
05621
05622 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
05623 {
05624 char *s;
05625 int ret;
05626 if(!strcmp(opt, "qscale")){
05627 av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
05628 return parse_option(o, "q:v", arg, options);
05629 }
05630 s = av_asprintf("q%s", opt + 6);
05631 ret = parse_option(o, s, arg, options);
05632 av_free(s);
05633 return ret;
05634 }
05635
05636 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
05637 {
05638 if(!strcmp(opt, "profile")){
05639 av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
05640 return parse_option(o, "profile:v", arg, options);
05641 }
05642 return opt_default(opt, arg);
05643 }
05644
05645 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
05646 {
05647 return parse_option(o, "filter:v", arg, options);
05648 }
05649
05650 static int opt_audio_filters(OptionsContext *o, const char *opt, const char *arg)
05651 {
05652 return parse_option(o, "filter:a", arg, options);
05653 }
05654
05655 static int opt_vsync(const char *opt, const char *arg)
05656 {
05657 if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
05658 else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
05659 else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
05660 else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
05661
05662 if (video_sync_method == VSYNC_AUTO)
05663 video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
05664 return 0;
05665 }
05666
05667 static int opt_deinterlace(const char *opt, const char *arg)
05668 {
05669 av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
05670 do_deinterlace = 1;
05671 return 0;
05672 }
05673
05674 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
05675 {
05676 int idx = locate_option(argc, argv, options, "cpuflags");
05677 if (idx && argv[idx + 1])
05678 opt_cpuflags("cpuflags", argv[idx + 1]);
05679 }
05680
05681 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
05682 {
05683 char layout_str[32];
05684 char *stream_str;
05685 char *ac_str;
05686 int ret, channels, ac_str_size;
05687 uint64_t layout;
05688
05689 layout = av_get_channel_layout(arg);
05690 if (!layout) {
05691 av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
05692 return AVERROR(EINVAL);
05693 }
05694 snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
05695 ret = opt_default(opt, layout_str);
05696 if (ret < 0)
05697 return ret;
05698
05699
05700 channels = av_get_channel_layout_nb_channels(layout);
05701 snprintf(layout_str, sizeof(layout_str), "%d", channels);
05702 stream_str = strchr(opt, ':');
05703 ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
05704 ac_str = av_mallocz(ac_str_size);
05705 if (!ac_str)
05706 return AVERROR(ENOMEM);
05707 av_strlcpy(ac_str, "ac", 3);
05708 if (stream_str)
05709 av_strlcat(ac_str, stream_str, ac_str_size);
05710 ret = parse_option(o, ac_str, layout_str, options);
05711 av_free(ac_str);
05712
05713 return ret;
05714 }
05715
05716 static int opt_filter_complex(const char *opt, const char *arg)
05717 {
05718 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
05719 &nb_filtergraphs, nb_filtergraphs + 1);
05720 if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
05721 return AVERROR(ENOMEM);
05722 filtergraphs[nb_filtergraphs - 1]->index = nb_filtergraphs - 1;
05723 filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
05724 return 0;
05725 }
05726
05727 #define OFFSET(x) offsetof(OptionsContext, x)
05728 static const OptionDef options[] = {
05729
05730 #include "cmdutils_common_opts.h"
05731 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
05732 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
05733 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
05734 { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
05735 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
05736 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
05737 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
05738 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
05739 { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
05740 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
05741 "outfile[,metadata]:infile[,metadata]" },
05742 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
05743 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
05744 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" },
05745 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
05746 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
05747 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
05748 { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
05749 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
05750 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
05751 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
05752 "add timings for benchmarking" },
05753 { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
05754 "add timings for each task" },
05755 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
05756 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
05757 "dump each input packet" },
05758 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
05759 "when dumping packets, also dump the payload" },
05760 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
05761 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
05762 { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
05763 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
05764 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
05765 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
05766 { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying", "mode" },
05767 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" },
05768 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
05769 { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
05770 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
05771 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
05772 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
05773 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
05774 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
05775 { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
05776 { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
05777 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
05778 { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
05779 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
05780 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
05781 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
05782 { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
05783
05784
05785 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
05786 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
05787 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
05788 { "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" },
05789 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
05790 { "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" },
05791 { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
05792 { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
05793 { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
05794 { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
05795 { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
05796 { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
05797 { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
05798 { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
05799 { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
05800 { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
05801 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
05802 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
05803 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
05804 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
05805 { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
05806 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
05807 "use same quantizer as source (implies VBR)" },
05808 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
05809 { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
05810 { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
05811 "this option is deprecated, use the yadif filter instead" },
05812 { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
05813 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
05814 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
05815 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
05816 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
05817 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
05818 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
05819 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
05820 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
05821 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
05822 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
05823 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
05824 { "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" },
05825 { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
05826
05827
05828 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
05829 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
05830 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
05831 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
05832 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
05833 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
05834 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
05835 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" },
05836 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
05837 { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
05838 { "af", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_filters}, "audio filters", "filter list" },
05839
05840
05841 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
05842 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
05843 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
05844
05845
05846 { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
05847 { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
05848 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
05849
05850
05851 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
05852 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
05853
05854 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
05855 { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
05856 { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
05857
05858 { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
05859 { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
05860 { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
05861 { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
05862
05863 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
05864 { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
05865
05866 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
05867 { NULL, },
05868 };
05869
05870 int main(int argc, char **argv)
05871 {
05872 OptionsContext o = { 0 };
05873 int64_t ti;
05874
05875 reset_options(&o, 0);
05876
05877 av_log_set_flags(AV_LOG_SKIP_REPEATED);
05878 parse_loglevel(argc, argv, options);
05879
05880 if(argc>1 && !strcmp(argv[1], "-d")){
05881 run_as_daemon=1;
05882 av_log_set_callback(log_callback_null);
05883 argc--;
05884 argv++;
05885 }
05886
05887 avcodec_register_all();
05888 #if CONFIG_AVDEVICE
05889 avdevice_register_all();
05890 #endif
05891 avfilter_register_all();
05892 av_register_all();
05893 avformat_network_init();
05894
05895 show_banner(argc, argv, options);
05896
05897 term_init();
05898
05899 parse_cpuflags(argc, argv, options);
05900
05901
05902 parse_options(&o, argc, argv, options, opt_output_file);
05903
05904 if (nb_output_files <= 0 && nb_input_files == 0) {
05905 show_usage();
05906 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
05907 exit_program(1);
05908 }
05909
05910
05911 if (nb_output_files <= 0) {
05912 av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
05913 exit_program(1);
05914 }
05915
05916 if (nb_input_files == 0) {
05917 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
05918 exit_program(1);
05919 }
05920
05921 current_time = ti = getutime();
05922 if (transcode() < 0)
05923 exit_program(1);
05924 ti = getutime() - ti;
05925 if (do_benchmark) {
05926 int maxrss = getmaxrss() / 1024;
05927 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
05928 }
05929
05930 exit_program(0);
05931 return 0;
05932 }