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