3 * Copyright (c) 2000-2011 The libav developers.
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 #include "libavformat/avformat.h"
31 #include "libavdevice/avdevice.h"
32 #include "libswscale/swscale.h"
33 #include "libavresample/avresample.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/audioconvert.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/samplefmt.h"
38 #include "libavutil/colorspace.h"
39 #include "libavutil/fifo.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/pixdesc.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/imgutils.h"
47 #include "libavutil/time.h"
48 #include "libavformat/os_support.h"
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersrc.h"
53 # include "libavfilter/buffersink.h"
54 # include "libavfilter/vsrc_buffer.h"
56 #if HAVE_SYS_RESOURCE_H
57 #include <sys/types.h>
58 #include <sys/resource.h>
59 #elif HAVE_GETPROCESSTIMES
62 #if HAVE_GETPROCESSMEMORYINFO
68 #include <sys/select.h>
79 #include "libavutil/avassert.h"
82 #define VSYNC_PASSTHROUGH 0
86 const char program_name[] = "avconv";
87 const int program_birth_year = 2000;
89 /* select an input stream for an output stream */
90 typedef struct StreamMap {
91 int disabled; /** 1 is this mapping is disabled by a negative map */
95 int sync_stream_index;
96 char *linklabel; /** name of an output link, for mapping lavfi outputs */
100 * select an input file for an output file
102 typedef struct MetadataMap {
103 int file; ///< file index
104 char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
105 int index; ///< stream/chapter/program number
108 static const OptionDef options[];
110 static int video_discard = 0;
111 static int same_quant = 0;
112 static int do_deinterlace = 0;
113 static int intra_dc_precision = 8;
114 static int qp_hist = 0;
116 static int file_overwrite = 0;
117 static int do_benchmark = 0;
118 static int do_hex_dump = 0;
119 static int do_pkt_dump = 0;
120 static int do_pass = 0;
121 static char *pass_logfilename_prefix = NULL;
122 static int video_sync_method = VSYNC_AUTO;
123 static int audio_sync_method = 0;
124 static float audio_drift_threshold = 0.1;
125 static int copy_ts = 0;
126 static int copy_tb = 1;
127 static int opt_shortest = 0;
128 static char *vstats_filename;
129 static FILE *vstats_file;
131 static int audio_volume = 256;
133 static int exit_on_error = 0;
134 static int using_stdin = 0;
135 static int64_t video_size = 0;
136 static int64_t audio_size = 0;
137 static int64_t extra_size = 0;
138 static int nb_frames_dup = 0;
139 static int nb_frames_drop = 0;
140 static int input_sync;
142 static float dts_delta_threshold = 10;
144 static int print_stats = 1;
147 /* signal to input threads that they should exit; set by the main thread */
148 static int transcoding_finished;
151 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
153 typedef struct InputFilter {
154 AVFilterContext *filter;
155 struct InputStream *ist;
156 struct FilterGraph *graph;
160 typedef struct OutputFilter {
161 AVFilterContext *filter;
162 struct OutputStream *ost;
163 struct FilterGraph *graph;
166 /* temporary storage until stream maps are processed */
167 AVFilterInOut *out_tmp;
170 typedef struct FilterGraph {
172 const char *graph_desc;
174 AVFilterGraph *graph;
176 InputFilter **inputs;
178 OutputFilter **outputs;
182 typedef struct InputStream {
185 int discard; /* true if stream data should be discarded */
186 int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
188 AVFrame *decoded_frame;
190 int64_t start; /* time when read started */
191 /* predicted dts of the next packet read for this stream or (when there are
192 * several frames in a packet) of the next frame in current packet */
194 /* dts of the last packet read for this stream */
196 PtsCorrectionContext pts_ctx;
198 int is_start; /* is 1 at the start and after a discontinuity */
199 int showed_multi_packet_warning;
201 AVRational framerate; /* framerate forced with -r */
205 int resample_pix_fmt;
207 int resample_sample_fmt;
208 int resample_sample_rate;
209 int resample_channels;
210 uint64_t resample_channel_layout;
212 /* a pool of free buffers for decoded data */
213 FrameBuffer *buffer_pool;
215 /* decoded data from this stream goes into all those filters
216 * currently video and audio only */
217 InputFilter **filters;
221 typedef struct InputFile {
222 AVFormatContext *ctx;
223 int eof_reached; /* true if eof reached */
224 int ist_index; /* index of first stream in ist_table */
225 int buffer_size; /* current total buffer size */
227 int nb_streams; /* number of stream that avconv is aware of; may be different
228 from ctx.nb_streams if new streams appear during av_read_frame() */
232 pthread_t thread; /* thread reading from this file */
233 int finished; /* the thread has exited */
234 int joined; /* the thread has been joined */
235 pthread_mutex_t fifo_lock; /* lock for access to fifo */
236 pthread_cond_t fifo_cond; /* the main thread will signal on this cond after reading from fifo */
237 AVFifoBuffer *fifo; /* demuxed packets are stored here; freed by the main thread */
241 typedef struct OutputStream {
242 int file_index; /* file index */
243 int index; /* stream index in the output file */
244 int source_index; /* InputStream index */
245 AVStream *st; /* stream in the output file */
246 int encoding_needed; /* true if encoding needed for this stream */
248 /* input pts and corresponding output pts
250 // double sync_ipts; /* dts from the AVPacket of the demuxer in second units */
251 struct InputStream *sync_ist; /* input stream to sync against */
252 int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
253 /* pts of the first frame encoded for this stream, used for limiting
256 AVBitStreamFilterContext *bitstream_filters;
259 AVFrame *filtered_frame;
262 AVRational frame_rate;
266 float frame_aspect_ratio;
269 /* forced key frames */
270 int64_t *forced_kf_pts;
276 OutputFilter *filter;
281 int is_past_recording_time;
283 const char *attachment_filename;
284 int copy_initial_nonkeyframes;
286 enum PixelFormat pix_fmts[2];
290 typedef struct OutputFile {
291 AVFormatContext *ctx;
293 int ost_index; /* index of the first stream in output_streams */
294 int64_t recording_time; /* desired length of the resulting file in microseconds */
295 int64_t start_time; /* start time in microseconds */
296 uint64_t limit_filesize;
299 static InputStream **input_streams = NULL;
300 static int nb_input_streams = 0;
301 static InputFile **input_files = NULL;
302 static int nb_input_files = 0;
304 static OutputStream **output_streams = NULL;
305 static int nb_output_streams = 0;
306 static OutputFile **output_files = NULL;
307 static int nb_output_files = 0;
309 static FilterGraph **filtergraphs;
312 typedef struct OptionsContext {
313 /* input/output options */
317 SpecifierOpt *codec_names;
319 SpecifierOpt *audio_channels;
320 int nb_audio_channels;
321 SpecifierOpt *audio_sample_rate;
322 int nb_audio_sample_rate;
323 SpecifierOpt *frame_rates;
325 SpecifierOpt *frame_sizes;
327 SpecifierOpt *frame_pix_fmts;
328 int nb_frame_pix_fmts;
331 int64_t input_ts_offset;
334 SpecifierOpt *ts_scale;
336 SpecifierOpt *dump_attachment;
337 int nb_dump_attachment;
340 StreamMap *stream_maps;
342 /* first item specifies output metadata, second is input */
343 MetadataMap (*meta_data_maps)[2];
344 int nb_meta_data_maps;
345 int metadata_global_manual;
346 int metadata_streams_manual;
347 int metadata_chapters_manual;
348 const char **attachments;
351 int chapters_input_file;
353 int64_t recording_time;
354 uint64_t limit_filesize;
360 int subtitle_disable;
363 /* indexed by output file stream index */
367 SpecifierOpt *metadata;
369 SpecifierOpt *max_frames;
371 SpecifierOpt *bitstream_filters;
372 int nb_bitstream_filters;
373 SpecifierOpt *codec_tags;
375 SpecifierOpt *sample_fmts;
377 SpecifierOpt *qscale;
379 SpecifierOpt *forced_key_frames;
380 int nb_forced_key_frames;
381 SpecifierOpt *force_fps;
383 SpecifierOpt *frame_aspect_ratios;
384 int nb_frame_aspect_ratios;
385 SpecifierOpt *rc_overrides;
387 SpecifierOpt *intra_matrices;
388 int nb_intra_matrices;
389 SpecifierOpt *inter_matrices;
390 int nb_inter_matrices;
391 SpecifierOpt *top_field_first;
392 int nb_top_field_first;
393 SpecifierOpt *metadata_map;
395 SpecifierOpt *presets;
397 SpecifierOpt *copy_initial_nonkeyframes;
398 int nb_copy_initial_nonkeyframes;
399 SpecifierOpt *filters;
403 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
406 for (i = 0; i < o->nb_ ## name; i++) {\
407 char *spec = o->name[i].specifier;\
408 if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
409 outvar = o->name[i].u.type;\
415 static void reset_options(OptionsContext *o)
417 const OptionDef *po = options;
420 /* all OPT_SPEC and OPT_STRING can be freed in generic way */
422 void *dst = (uint8_t*)o + po->u.off;
424 if (po->flags & OPT_SPEC) {
425 SpecifierOpt **so = dst;
426 int i, *count = (int*)(so + 1);
427 for (i = 0; i < *count; i++) {
428 av_freep(&(*so)[i].specifier);
429 if (po->flags & OPT_STRING)
430 av_freep(&(*so)[i].u.str);
434 } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
439 for (i = 0; i < o->nb_stream_maps; i++)
440 av_freep(&o->stream_maps[i].linklabel);
441 av_freep(&o->stream_maps);
442 av_freep(&o->meta_data_maps);
443 av_freep(&o->streamid_map);
445 memset(o, 0, sizeof(*o));
447 o->mux_max_delay = 0.7;
448 o->recording_time = INT64_MAX;
449 o->limit_filesize = UINT64_MAX;
450 o->chapters_input_file = INT_MAX;
457 * Define a function for building a string containing a list of
460 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
461 static char *choose_ ## var ## s(OutputStream *ost) \
463 if (ost->st->codec->var != none) { \
464 get_name(ost->st->codec->var); \
465 return av_strdup(name); \
466 } else if (ost->enc->supported_list) { \
468 AVIOContext *s = NULL; \
472 if (avio_open_dyn_buf(&s) < 0) \
475 for (p = ost->enc->supported_list; *p != none; p++) { \
477 avio_printf(s, "%s" separator, name); \
479 len = avio_close_dyn_buf(s, &ret); \
486 #define GET_PIX_FMT_NAME(pix_fmt)\
487 const char *name = av_get_pix_fmt_name(pix_fmt);
489 DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
490 GET_PIX_FMT_NAME, ":")
492 #define GET_SAMPLE_FMT_NAME(sample_fmt)\
493 const char *name = av_get_sample_fmt_name(sample_fmt)
495 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
496 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
498 #define GET_SAMPLE_RATE_NAME(rate)\
500 snprintf(name, sizeof(name), "%d", rate);
502 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
503 GET_SAMPLE_RATE_NAME, ",")
505 #define GET_CH_LAYOUT_NAME(ch_layout)\
507 snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
509 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
510 GET_CH_LAYOUT_NAME, ",")
512 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
514 FilterGraph *fg = av_mallocz(sizeof(*fg));
518 fg->index = nb_filtergraphs;
520 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
522 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
524 fg->outputs[0]->ost = ost;
525 fg->outputs[0]->graph = fg;
527 ost->filter = fg->outputs[0];
529 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
531 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
533 fg->inputs[0]->ist = ist;
534 fg->inputs[0]->graph = fg;
536 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
537 &ist->nb_filters, ist->nb_filters + 1);
538 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
540 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
541 &nb_filtergraphs, nb_filtergraphs + 1);
542 filtergraphs[nb_filtergraphs - 1] = fg;
547 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
550 enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
553 // TODO: support other filter types
554 if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
555 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
564 int file_idx = strtol(in->name, &p, 0);
566 if (file_idx < 0 || file_idx >= nb_input_files) {
567 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
568 file_idx, fg->graph_desc);
571 s = input_files[file_idx]->ctx;
573 for (i = 0; i < s->nb_streams; i++) {
574 if (s->streams[i]->codec->codec_type != type)
576 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
582 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
583 "matches no streams.\n", p, fg->graph_desc);
586 ist = input_streams[input_files[file_idx]->ist_index + st->index];
588 /* find the first unused stream of corresponding type */
589 for (i = 0; i < nb_input_streams; i++) {
590 ist = input_streams[i];
591 if (ist->st->codec->codec_type == type && ist->discard)
594 if (i == nb_input_streams) {
595 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
596 "unlabeled input pad %d on filter %s", in->pad_idx,
597 in->filter_ctx->name);
602 ist->decoding_needed = 1;
603 ist->st->discard = AVDISCARD_NONE;
605 fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
606 &fg->nb_inputs, fg->nb_inputs + 1);
607 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
609 fg->inputs[fg->nb_inputs - 1]->ist = ist;
610 fg->inputs[fg->nb_inputs - 1]->graph = fg;
612 ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
613 &ist->nb_filters, ist->nb_filters + 1);
614 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
617 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
620 OutputStream *ost = ofilter->ost;
621 AVCodecContext *codec = ost->st->codec;
622 AVFilterContext *last_filter = out->filter_ctx;
623 int pad_idx = out->pad_idx;
627 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
628 ret = avfilter_graph_create_filter(&ofilter->filter,
629 avfilter_get_by_name("buffersink"),
630 name, NULL, pix_fmts, fg->graph);
634 if (codec->width || codec->height) {
636 AVFilterContext *filter;
638 snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
641 (unsigned)ost->sws_flags);
642 snprintf(name, sizeof(name), "scaler for output stream %d:%d",
643 ost->file_index, ost->index);
644 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
645 name, args, NULL, fg->graph)) < 0)
647 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
650 last_filter = filter;
654 if ((pix_fmts = choose_pix_fmts(ost))) {
655 AVFilterContext *filter;
656 snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
657 ost->file_index, ost->index);
658 if ((ret = avfilter_graph_create_filter(&filter,
659 avfilter_get_by_name("format"),
660 "format", pix_fmts, NULL,
663 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
666 last_filter = filter;
671 if (ost->frame_rate.num) {
672 AVFilterContext *fps;
675 snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
676 ost->frame_rate.den);
677 snprintf(name, sizeof(name), "fps for output stream %d:%d",
678 ost->file_index, ost->index);
679 ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
680 name, args, NULL, fg->graph);
684 ret = avfilter_link(last_filter, pad_idx, fps, 0);
691 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
697 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
699 OutputStream *ost = ofilter->ost;
700 AVCodecContext *codec = ost->st->codec;
701 AVFilterContext *last_filter = out->filter_ctx;
702 int pad_idx = out->pad_idx;
703 char *sample_fmts, *sample_rates, *channel_layouts;
708 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
709 ret = avfilter_graph_create_filter(&ofilter->filter,
710 avfilter_get_by_name("abuffersink"),
711 name, NULL, NULL, fg->graph);
715 if (codec->channels && !codec->channel_layout)
716 codec->channel_layout = av_get_default_channel_layout(codec->channels);
718 sample_fmts = choose_sample_fmts(ost);
719 sample_rates = choose_sample_rates(ost);
720 channel_layouts = choose_channel_layouts(ost);
721 if (sample_fmts || sample_rates || channel_layouts) {
722 AVFilterContext *format;
727 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
730 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
733 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
737 av_freep(&sample_fmts);
738 av_freep(&sample_rates);
739 av_freep(&channel_layouts);
741 snprintf(name, sizeof(name), "audio format for output stream %d:%d",
742 ost->file_index, ost->index);
743 ret = avfilter_graph_create_filter(&format,
744 avfilter_get_by_name("aformat"),
745 name, args, NULL, fg->graph);
749 ret = avfilter_link(last_filter, pad_idx, format, 0);
753 last_filter = format;
757 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
763 #define DESCRIBE_FILTER_LINK(f, inout, in) \
765 AVFilterContext *ctx = inout->filter_ctx; \
766 AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
767 int nb_pads = in ? ctx->input_count : ctx->output_count; \
770 if (avio_open_dyn_buf(&pb) < 0) \
773 avio_printf(pb, "%s", ctx->filter->name); \
775 avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
777 avio_close_dyn_buf(pb, &f->name); \
780 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
782 av_freep(&ofilter->name);
783 DESCRIBE_FILTER_LINK(ofilter, out, 0);
785 switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
786 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
787 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
788 default: av_assert0(0);
792 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
795 AVFilterContext *first_filter = in->filter_ctx;
796 AVFilter *filter = avfilter_get_by_name("buffer");
797 InputStream *ist = ifilter->ist;
798 AVRational tb = ist->framerate.num ? (AVRational){ist->framerate.den,
799 ist->framerate.num} :
802 char args[255], name[255];
803 int pad_idx = in->pad_idx;
806 sar = ist->st->sample_aspect_ratio.num ?
807 ist->st->sample_aspect_ratio :
808 ist->st->codec->sample_aspect_ratio;
809 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
810 ist->st->codec->height, ist->st->codec->pix_fmt,
811 tb.num, tb.den, sar.num, sar.den);
812 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
813 ist->file_index, ist->st->index);
815 if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
816 args, NULL, fg->graph)) < 0)
819 if (ist->framerate.num) {
820 AVFilterContext *setpts;
822 snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
823 ist->file_index, ist->st->index);
824 if ((ret = avfilter_graph_create_filter(&setpts,
825 avfilter_get_by_name("setpts"),
830 if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
833 first_filter = setpts;
837 if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
842 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
845 AVFilterContext *first_filter = in->filter_ctx;
846 AVFilter *filter = avfilter_get_by_name("abuffer");
847 InputStream *ist = ifilter->ist;
848 int pad_idx = in->pad_idx;
849 char args[255], name[255];
852 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
853 ":channel_layout=0x%"PRIx64,
854 ist->st->time_base.num, ist->st->time_base.den,
855 ist->st->codec->sample_rate,
856 av_get_sample_fmt_name(ist->st->codec->sample_fmt),
857 ist->st->codec->channel_layout);
858 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
859 ist->file_index, ist->st->index);
861 if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
866 if (audio_sync_method > 0) {
867 AVFilterContext *async;
871 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
872 "asyncts audio filter instead.\n");
874 if (audio_sync_method > 1)
875 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
876 "max_comp=%d:", audio_sync_method);
877 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
878 audio_drift_threshold);
880 snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
881 fg->index, ist->file_index, ist->st->index);
882 ret = avfilter_graph_create_filter(&async,
883 avfilter_get_by_name("asyncts"),
884 name, args, NULL, fg->graph);
888 ret = avfilter_link(async, 0, first_filter, pad_idx);
892 first_filter = async;
895 if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
901 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
904 av_freep(&ifilter->name);
905 DESCRIBE_FILTER_LINK(ifilter, in, 1);
907 switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
908 case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
909 case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
910 default: av_assert0(0);
914 static int configure_filtergraph(FilterGraph *fg)
916 AVFilterInOut *inputs, *outputs, *cur;
917 int ret, i, init = !fg->graph, simple = !fg->graph_desc;
918 const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
921 avfilter_graph_free(&fg->graph);
922 if (!(fg->graph = avfilter_graph_alloc()))
923 return AVERROR(ENOMEM);
926 OutputStream *ost = fg->outputs[0]->ost;
928 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
929 fg->graph->scale_sws_opts = av_strdup(args);
932 if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
935 if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
936 av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
937 "exactly one input and output.\n", graph_desc);
938 return AVERROR(EINVAL);
941 for (cur = inputs; !simple && init && cur; cur = cur->next)
942 init_input_filter(fg, cur);
944 for (cur = inputs, i = 0; cur; cur = cur->next, i++)
945 if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
947 avfilter_inout_free(&inputs);
949 if (!init || simple) {
950 /* we already know the mappings between lavfi outputs and output streams,
951 * so we can finish the setup */
952 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
953 configure_output_filter(fg, fg->outputs[i], cur);
954 avfilter_inout_free(&outputs);
956 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
959 /* wait until output mappings are processed */
960 for (cur = outputs; cur;) {
961 fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
962 &fg->nb_outputs, fg->nb_outputs + 1);
963 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
965 fg->outputs[fg->nb_outputs - 1]->graph = fg;
966 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
968 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
975 static int configure_complex_filters(void)
979 for (i = 0; i < nb_filtergraphs; i++)
980 if (!filtergraphs[i]->graph &&
981 (ret = configure_filtergraph(filtergraphs[i])) < 0)
986 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
989 for (i = 0; i < fg->nb_inputs; i++)
990 if (fg->inputs[i]->ist == ist)
995 static void term_exit(void)
997 av_log(NULL, AV_LOG_QUIET, "");
1000 static volatile int received_sigterm = 0;
1001 static volatile int received_nb_signals = 0;
1004 sigterm_handler(int sig)
1006 received_sigterm = sig;
1007 received_nb_signals++;
1011 static void term_init(void)
1013 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
1014 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
1016 signal(SIGXCPU, sigterm_handler);
1020 static int decode_interrupt_cb(void *ctx)
1022 return received_nb_signals > 1;
1025 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1027 void exit_program(int ret)
1031 for (i = 0; i < nb_filtergraphs; i++) {
1032 avfilter_graph_free(&filtergraphs[i]->graph);
1033 for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
1034 av_freep(&filtergraphs[i]->inputs[j]->name);
1035 av_freep(&filtergraphs[i]->inputs[j]);
1037 av_freep(&filtergraphs[i]->inputs);
1038 for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
1039 av_freep(&filtergraphs[i]->outputs[j]->name);
1040 av_freep(&filtergraphs[i]->outputs[j]);
1042 av_freep(&filtergraphs[i]->outputs);
1043 av_freep(&filtergraphs[i]);
1045 av_freep(&filtergraphs);
1048 for (i = 0; i < nb_output_files; i++) {
1049 AVFormatContext *s = output_files[i]->ctx;
1050 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1052 avformat_free_context(s);
1053 av_dict_free(&output_files[i]->opts);
1054 av_freep(&output_files[i]);
1056 for (i = 0; i < nb_output_streams; i++) {
1057 AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1059 AVBitStreamFilterContext *next = bsfc->next;
1060 av_bitstream_filter_close(bsfc);
1063 output_streams[i]->bitstream_filters = NULL;
1065 av_freep(&output_streams[i]->avfilter);
1066 av_freep(&output_streams[i]->filtered_frame);
1067 av_freep(&output_streams[i]);
1069 for (i = 0; i < nb_input_files; i++) {
1070 avformat_close_input(&input_files[i]->ctx);
1071 av_freep(&input_files[i]);
1073 for (i = 0; i < nb_input_streams; i++) {
1074 av_freep(&input_streams[i]->decoded_frame);
1075 av_dict_free(&input_streams[i]->opts);
1076 free_buffer_pool(&input_streams[i]->buffer_pool);
1077 av_freep(&input_streams[i]->filters);
1078 av_freep(&input_streams[i]);
1082 fclose(vstats_file);
1083 av_free(vstats_filename);
1085 av_freep(&input_streams);
1086 av_freep(&input_files);
1087 av_freep(&output_streams);
1088 av_freep(&output_files);
1093 avformat_network_deinit();
1095 if (received_sigterm) {
1096 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1097 (int) received_sigterm);
1104 static void assert_avoptions(AVDictionary *m)
1106 AVDictionaryEntry *t;
1107 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1108 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1113 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1115 const char *codec_string = encoder ? "encoder" : "decoder";
1117 if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1118 c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1119 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1120 "results.\nAdd '-strict experimental' if you want to use it.\n",
1121 codec_string, c->codec->name);
1122 codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1123 if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1124 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1125 codec_string, codec->name);
1131 * Update the requested input sample format based on the output sample format.
1132 * This is currently only used to request float output from decoders which
1133 * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
1134 * Ideally this will be removed in the future when decoders do not do format
1135 * conversion and only output in their native format.
1137 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
1138 AVCodecContext *enc)
1140 /* if sample formats match or a decoder sample format has already been
1141 requested, just return */
1142 if (enc->sample_fmt == dec->sample_fmt ||
1143 dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
1146 /* if decoder supports more than one output format */
1147 if (dec_codec && dec_codec->sample_fmts &&
1148 dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
1149 dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
1150 const enum AVSampleFormat *p;
1151 int min_dec = -1, min_inc = -1;
1153 /* find a matching sample format in the encoder */
1154 for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
1155 if (*p == enc->sample_fmt) {
1156 dec->request_sample_fmt = *p;
1158 } else if (*p > enc->sample_fmt) {
1159 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
1161 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
1164 /* if none match, provide the one that matches quality closest */
1165 dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
1166 enc->sample_fmt - min_dec;
1170 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1172 AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1173 AVCodecContext *avctx = ost->st->codec;
1177 * Audio encoders may split the packets -- #frames in != #packets out.
1178 * But there is no reordering, so we can limit the number of output packets
1179 * by simply dropping them here.
1180 * Counting encoded video frames needs to be done separately because of
1181 * reordering, see do_video_out()
1183 if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1184 if (ost->frame_number >= ost->max_frames) {
1185 av_free_packet(pkt);
1188 ost->frame_number++;
1192 AVPacket new_pkt = *pkt;
1193 int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1194 &new_pkt.data, &new_pkt.size,
1195 pkt->data, pkt->size,
1196 pkt->flags & AV_PKT_FLAG_KEY);
1198 av_free_packet(pkt);
1199 new_pkt.destruct = av_destruct_packet;
1201 av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
1202 bsfc->filter->name, pkt->stream_index,
1203 avctx->codec ? avctx->codec->name : "copy");
1213 pkt->stream_index = ost->index;
1214 ret = av_interleaved_write_frame(s, pkt);
1216 print_error("av_interleaved_write_frame()", ret);
1221 static int check_recording_time(OutputStream *ost)
1223 OutputFile *of = output_files[ost->file_index];
1225 if (of->recording_time != INT64_MAX &&
1226 av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
1227 AV_TIME_BASE_Q) >= 0) {
1228 ost->is_past_recording_time = 1;
1234 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1237 AVCodecContext *enc = ost->st->codec;
1241 av_init_packet(&pkt);
1245 if (!check_recording_time(ost))
1248 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1249 frame->pts = ost->sync_opts;
1250 ost->sync_opts = frame->pts + frame->nb_samples;
1252 if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1253 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1258 if (pkt.pts != AV_NOPTS_VALUE)
1259 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1260 if (pkt.dts != AV_NOPTS_VALUE)
1261 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1262 if (pkt.duration > 0)
1263 pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1265 write_frame(s, &pkt, ost);
1267 audio_size += pkt.size;
1271 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1273 AVCodecContext *dec;
1274 AVPicture *picture2;
1275 AVPicture picture_tmp;
1278 dec = ist->st->codec;
1280 /* deinterlace : must be done before any resize */
1281 if (do_deinterlace) {
1284 /* create temporary picture */
1285 size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1286 buf = av_malloc(size);
1290 picture2 = &picture_tmp;
1291 avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1293 if (avpicture_deinterlace(picture2, picture,
1294 dec->pix_fmt, dec->width, dec->height) < 0) {
1295 /* if error, do not deinterlace */
1296 av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1305 if (picture != picture2)
1306 *picture = *picture2;
1310 static void do_subtitle_out(AVFormatContext *s,
1316 static uint8_t *subtitle_out = NULL;
1317 int subtitle_out_max_size = 1024 * 1024;
1318 int subtitle_out_size, nb, i;
1319 AVCodecContext *enc;
1322 if (pts == AV_NOPTS_VALUE) {
1323 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1329 enc = ost->st->codec;
1331 if (!subtitle_out) {
1332 subtitle_out = av_malloc(subtitle_out_max_size);
1335 /* Note: DVB subtitle need one packet to draw them and one other
1336 packet to clear them */
1337 /* XXX: signal it in the codec context ? */
1338 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1343 for (i = 0; i < nb; i++) {
1344 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1345 if (!check_recording_time(ost))
1348 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1349 // start_display_time is required to be 0
1350 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1351 sub->end_display_time -= sub->start_display_time;
1352 sub->start_display_time = 0;
1353 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1354 subtitle_out_max_size, sub);
1355 if (subtitle_out_size < 0) {
1356 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1360 av_init_packet(&pkt);
1361 pkt.data = subtitle_out;
1362 pkt.size = subtitle_out_size;
1363 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1364 if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1365 /* XXX: the pts correction is handled here. Maybe handling
1366 it in the codec would be better */
1368 pkt.pts += 90 * sub->start_display_time;
1370 pkt.pts += 90 * sub->end_display_time;
1372 write_frame(s, &pkt, ost);
1376 static void do_video_out(AVFormatContext *s,
1378 AVFrame *in_picture,
1379 int *frame_size, float quality)
1381 int ret, format_video_sync;
1383 AVCodecContext *enc = ost->st->codec;
1387 format_video_sync = video_sync_method;
1388 if (format_video_sync == VSYNC_AUTO)
1389 format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1390 (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
1391 if (format_video_sync != VSYNC_PASSTHROUGH &&
1392 ost->frame_number &&
1393 in_picture->pts != AV_NOPTS_VALUE &&
1394 in_picture->pts < ost->sync_opts) {
1396 av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1400 if (in_picture->pts == AV_NOPTS_VALUE)
1401 in_picture->pts = ost->sync_opts;
1402 ost->sync_opts = in_picture->pts;
1405 if (!ost->frame_number)
1406 ost->first_pts = in_picture->pts;
1408 av_init_packet(&pkt);
1412 if (!check_recording_time(ost) ||
1413 ost->frame_number >= ost->max_frames)
1416 if (s->oformat->flags & AVFMT_RAWPICTURE &&
1417 enc->codec->id == CODEC_ID_RAWVIDEO) {
1418 /* raw pictures are written as AVPicture structure to
1419 avoid any copies. We support temporarily the older
1421 enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1422 enc->coded_frame->top_field_first = in_picture->top_field_first;
1423 pkt.data = (uint8_t *)in_picture;
1424 pkt.size = sizeof(AVPicture);
1425 pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1426 pkt.flags |= AV_PKT_FLAG_KEY;
1428 write_frame(s, &pkt, ost);
1431 AVFrame big_picture;
1433 big_picture = *in_picture;
1434 /* better than nothing: use input picture interlaced
1436 big_picture.interlaced_frame = in_picture->interlaced_frame;
1437 if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1438 if (ost->top_field_first == -1)
1439 big_picture.top_field_first = in_picture->top_field_first;
1441 big_picture.top_field_first = !!ost->top_field_first;
1444 /* handles same_quant here. This is not correct because it may
1445 not be a global option */
1446 big_picture.quality = quality;
1447 if (!enc->me_threshold)
1448 big_picture.pict_type = 0;
1449 if (ost->forced_kf_index < ost->forced_kf_count &&
1450 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1451 big_picture.pict_type = AV_PICTURE_TYPE_I;
1452 ost->forced_kf_index++;
1454 ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1456 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1461 if (pkt.pts != AV_NOPTS_VALUE)
1462 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1463 if (pkt.dts != AV_NOPTS_VALUE)
1464 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1466 write_frame(s, &pkt, ost);
1467 *frame_size = pkt.size;
1468 video_size += pkt.size;
1470 /* if two pass, output log */
1471 if (ost->logfile && enc->stats_out) {
1472 fprintf(ost->logfile, "%s", enc->stats_out);
1478 * For video, number of frames in == number of packets out.
1479 * But there may be reordering, so we can't throw away frames on encoder
1480 * flush, we need to limit them here, before they go into encoder.
1482 ost->frame_number++;
1485 static double psnr(double d)
1487 return -10.0 * log(d) / log(10.0);
1490 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1493 AVCodecContext *enc;
1495 double ti1, bitrate, avg_bitrate;
1497 /* this is executed just the first time do_video_stats is called */
1499 vstats_file = fopen(vstats_filename, "w");
1506 enc = ost->st->codec;
1507 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1508 frame_number = ost->frame_number;
1509 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1510 if (enc->flags&CODEC_FLAG_PSNR)
1511 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1513 fprintf(vstats_file,"f_size= %6d ", frame_size);
1514 /* compute pts value */
1515 ti1 = ost->sync_opts * av_q2d(enc->time_base);
1519 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1520 avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1521 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1522 (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1523 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1527 /* check for new output on any of the filtergraphs */
1528 static int poll_filters(void)
1530 AVFilterBufferRef *picref;
1531 AVFrame *filtered_frame = NULL;
1534 for (i = 0; i < nb_output_streams; i++) {
1535 OutputStream *ost = output_streams[i];
1536 OutputFile *of = output_files[ost->file_index];
1542 if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1543 return AVERROR(ENOMEM);
1545 avcodec_get_frame_defaults(ost->filtered_frame);
1546 filtered_frame = ost->filtered_frame;
1548 while (ret >= 0 && !ost->is_past_recording_time) {
1549 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1550 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1551 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
1552 ost->st->codec->frame_size);
1554 ret = av_buffersink_read(ost->filter->filter, &picref);
1559 avfilter_copy_buf_props(filtered_frame, picref);
1560 if (picref->pts != AV_NOPTS_VALUE)
1561 filtered_frame->pts = av_rescale_q(picref->pts,
1562 ost->filter->filter->inputs[0]->time_base,
1563 ost->st->codec->time_base) -
1564 av_rescale_q(of->start_time,
1566 ost->st->codec->time_base);
1568 if (of->start_time && filtered_frame->pts < of->start_time) {
1569 avfilter_unref_buffer(picref);
1573 switch (ost->filter->filter->inputs[0]->type) {
1574 case AVMEDIA_TYPE_VIDEO:
1575 if (!ost->frame_aspect_ratio)
1576 ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
1578 do_video_out(of->ctx, ost, filtered_frame, &frame_size,
1579 same_quant ? ost->last_quality :
1580 ost->st->codec->global_quality);
1581 if (vstats_filename && frame_size)
1582 do_video_stats(of->ctx, ost, frame_size);
1584 case AVMEDIA_TYPE_AUDIO:
1585 do_audio_out(of->ctx, ost, filtered_frame);
1588 // TODO support subtitle filters
1592 avfilter_unref_buffer(picref);
1598 static void print_report(int is_last_report, int64_t timer_start)
1602 AVFormatContext *oc;
1604 AVCodecContext *enc;
1605 int frame_number, vid, i;
1606 double bitrate, ti1, pts;
1607 static int64_t last_time = -1;
1608 static int qp_histogram[52];
1610 if (!print_stats && !is_last_report)
1613 if (!is_last_report) {
1615 /* display the report every 0.5 seconds */
1616 cur_time = av_gettime();
1617 if (last_time == -1) {
1618 last_time = cur_time;
1621 if ((cur_time - last_time) < 500000)
1623 last_time = cur_time;
1627 oc = output_files[0]->ctx;
1629 total_size = avio_size(oc->pb);
1630 if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1631 total_size = avio_tell(oc->pb);
1636 for (i = 0; i < nb_output_streams; i++) {
1638 ost = output_streams[i];
1639 enc = ost->st->codec;
1640 if (!ost->stream_copy && enc->coded_frame)
1641 q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1642 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1643 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1645 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1646 float t = (av_gettime() - timer_start) / 1000000.0;
1648 frame_number = ost->frame_number;
1649 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1650 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1652 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1656 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1658 for (j = 0; j < 32; j++)
1659 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1661 if (enc->flags&CODEC_FLAG_PSNR) {
1663 double error, error_sum = 0;
1664 double scale, scale_sum = 0;
1665 char type[3] = { 'Y','U','V' };
1666 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1667 for (j = 0; j < 3; j++) {
1668 if (is_last_report) {
1669 error = enc->error[j];
1670 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1672 error = enc->coded_frame->error[j];
1673 scale = enc->width * enc->height * 255.0 * 255.0;
1679 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1681 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1685 /* compute min output value */
1686 pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1687 if ((pts < ti1) && (pts > 0))
1693 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1695 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1696 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1697 (double)total_size / 1024, ti1, bitrate);
1699 if (nb_frames_dup || nb_frames_drop)
1700 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1701 nb_frames_dup, nb_frames_drop);
1703 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1707 if (is_last_report) {
1708 int64_t raw= audio_size + video_size + extra_size;
1709 av_log(NULL, AV_LOG_INFO, "\n");
1710 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1711 video_size / 1024.0,
1712 audio_size / 1024.0,
1713 extra_size / 1024.0,
1714 100.0 * (total_size - raw) / raw
1719 static void flush_encoders(void)
1723 for (i = 0; i < nb_output_streams; i++) {
1724 OutputStream *ost = output_streams[i];
1725 AVCodecContext *enc = ost->st->codec;
1726 AVFormatContext *os = output_files[ost->file_index]->ctx;
1727 int stop_encoding = 0;
1729 if (!ost->encoding_needed)
1732 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1734 if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1738 int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1742 switch (ost->st->codec->codec_type) {
1743 case AVMEDIA_TYPE_AUDIO:
1744 encode = avcodec_encode_audio2;
1748 case AVMEDIA_TYPE_VIDEO:
1749 encode = avcodec_encode_video2;
1760 av_init_packet(&pkt);
1764 ret = encode(enc, &pkt, NULL, &got_packet);
1766 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1770 if (ost->logfile && enc->stats_out) {
1771 fprintf(ost->logfile, "%s", enc->stats_out);
1777 if (pkt.pts != AV_NOPTS_VALUE)
1778 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1779 if (pkt.dts != AV_NOPTS_VALUE)
1780 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1781 write_frame(os, &pkt, ost);
1791 * Check whether a packet from ist should be written into ost at this time
1793 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1795 OutputFile *of = output_files[ost->file_index];
1796 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1798 if (ost->source_index != ist_index)
1801 if (of->start_time && ist->last_dts < of->start_time)
1807 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1809 OutputFile *of = output_files[ost->file_index];
1810 int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1813 av_init_packet(&opkt);
1815 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1816 !ost->copy_initial_nonkeyframes)
1819 if (of->recording_time != INT64_MAX &&
1820 ist->last_dts >= of->recording_time + of->start_time) {
1821 ost->is_past_recording_time = 1;
1825 /* force the input stream PTS */
1826 if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1827 audio_size += pkt->size;
1828 else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1829 video_size += pkt->size;
1833 if (pkt->pts != AV_NOPTS_VALUE)
1834 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1836 opkt.pts = AV_NOPTS_VALUE;
1838 if (pkt->dts == AV_NOPTS_VALUE)
1839 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
1841 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1842 opkt.dts -= ost_tb_start_time;
1844 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1845 opkt.flags = pkt->flags;
1847 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1848 if ( ost->st->codec->codec_id != CODEC_ID_H264
1849 && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1850 && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1851 && ost->st->codec->codec_id != CODEC_ID_VC1
1853 if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1854 opkt.destruct = av_destruct_packet;
1856 opkt.data = pkt->data;
1857 opkt.size = pkt->size;
1860 write_frame(of->ctx, &opkt, ost);
1861 ost->st->codec->frame_number++;
1862 av_free_packet(&opkt);
1865 static void rate_emu_sleep(InputStream *ist)
1867 if (input_files[ist->file_index]->rate_emu) {
1868 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
1869 int64_t now = av_gettime() - ist->start;
1871 av_usleep(pts - now);
1875 static int guess_input_channel_layout(InputStream *ist)
1877 AVCodecContext *dec = ist->st->codec;
1879 if (!dec->channel_layout) {
1880 char layout_name[256];
1882 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1883 if (!dec->channel_layout)
1885 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1886 dec->channels, dec->channel_layout);
1887 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1888 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1893 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1895 AVFrame *decoded_frame;
1896 AVCodecContext *avctx = ist->st->codec;
1897 int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1898 int i, ret, resample_changed;
1900 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1901 return AVERROR(ENOMEM);
1903 avcodec_get_frame_defaults(ist->decoded_frame);
1904 decoded_frame = ist->decoded_frame;
1906 ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1912 /* no audio frame */
1914 for (i = 0; i < ist->nb_filters; i++)
1915 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1919 /* if the decoder provides a pts, use it instead of the last packet pts.
1920 the decoder could be delaying output by a packet or more. */
1921 if (decoded_frame->pts != AV_NOPTS_VALUE)
1922 ist->next_dts = decoded_frame->pts;
1923 else if (pkt->pts != AV_NOPTS_VALUE) {
1924 decoded_frame->pts = pkt->pts;
1925 pkt->pts = AV_NOPTS_VALUE;
1928 // preprocess audio (volume)
1929 if (audio_volume != 256) {
1930 int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1931 void *samples = decoded_frame->data[0];
1932 switch (avctx->sample_fmt) {
1933 case AV_SAMPLE_FMT_U8:
1935 uint8_t *volp = samples;
1936 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1937 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1938 *volp++ = av_clip_uint8(v);
1942 case AV_SAMPLE_FMT_S16:
1944 int16_t *volp = samples;
1945 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1946 int v = ((*volp) * audio_volume + 128) >> 8;
1947 *volp++ = av_clip_int16(v);
1951 case AV_SAMPLE_FMT_S32:
1953 int32_t *volp = samples;
1954 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1955 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1956 *volp++ = av_clipl_int32(v);
1960 case AV_SAMPLE_FMT_FLT:
1962 float *volp = samples;
1963 float scale = audio_volume / 256.f;
1964 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1969 case AV_SAMPLE_FMT_DBL:
1971 double *volp = samples;
1972 double scale = audio_volume / 256.;
1973 for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1979 av_log(NULL, AV_LOG_FATAL,
1980 "Audio volume adjustment on sample format %s is not supported.\n",
1981 av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1986 rate_emu_sleep(ist);
1988 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1989 ist->resample_channels != avctx->channels ||
1990 ist->resample_channel_layout != decoded_frame->channel_layout ||
1991 ist->resample_sample_rate != decoded_frame->sample_rate;
1992 if (resample_changed) {
1993 char layout1[64], layout2[64];
1995 if (!guess_input_channel_layout(ist)) {
1996 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1997 "layout for Input Stream #%d.%d\n", ist->file_index,
2001 decoded_frame->channel_layout = avctx->channel_layout;
2003 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
2004 ist->resample_channel_layout);
2005 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
2006 decoded_frame->channel_layout);
2008 av_log(NULL, AV_LOG_INFO,
2009 "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
2010 ist->file_index, ist->st->index,
2011 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
2012 ist->resample_channels, layout1,
2013 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
2014 avctx->channels, layout2);
2016 ist->resample_sample_fmt = decoded_frame->format;
2017 ist->resample_sample_rate = decoded_frame->sample_rate;
2018 ist->resample_channel_layout = decoded_frame->channel_layout;
2019 ist->resample_channels = avctx->channels;
2021 for (i = 0; i < nb_filtergraphs; i++)
2022 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2023 configure_filtergraph(filtergraphs[i]) < 0) {
2024 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2029 for (i = 0; i < ist->nb_filters; i++)
2030 av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2035 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
2037 AVFrame *decoded_frame;
2038 void *buffer_to_free = NULL;
2039 int i, ret = 0, resample_changed;
2042 if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2043 return AVERROR(ENOMEM);
2045 avcodec_get_frame_defaults(ist->decoded_frame);
2046 decoded_frame = ist->decoded_frame;
2048 ret = avcodec_decode_video2(ist->st->codec,
2049 decoded_frame, got_output, pkt);
2053 quality = same_quant ? decoded_frame->quality : 0;
2055 /* no picture yet */
2057 for (i = 0; i < ist->nb_filters; i++)
2058 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2061 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
2062 decoded_frame->pkt_dts);
2064 pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2066 rate_emu_sleep(ist);
2068 if (ist->st->sample_aspect_ratio.num)
2069 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2071 resample_changed = ist->resample_width != decoded_frame->width ||
2072 ist->resample_height != decoded_frame->height ||
2073 ist->resample_pix_fmt != decoded_frame->format;
2074 if (resample_changed) {
2075 av_log(NULL, AV_LOG_INFO,
2076 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2077 ist->file_index, ist->st->index,
2078 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
2079 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2081 ist->resample_width = decoded_frame->width;
2082 ist->resample_height = decoded_frame->height;
2083 ist->resample_pix_fmt = decoded_frame->format;
2085 for (i = 0; i < nb_filtergraphs; i++)
2086 if (ist_in_filtergraph(filtergraphs[i], ist) &&
2087 configure_filtergraph(filtergraphs[i]) < 0) {
2088 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2093 for (i = 0; i < ist->nb_filters; i++) {
2094 // XXX what an ugly hack
2095 if (ist->filters[i]->graph->nb_outputs == 1)
2096 ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2098 if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2099 FrameBuffer *buf = decoded_frame->opaque;
2100 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2101 decoded_frame->data, decoded_frame->linesize,
2102 AV_PERM_READ | AV_PERM_PRESERVE,
2103 ist->st->codec->width, ist->st->codec->height,
2104 ist->st->codec->pix_fmt);
2106 avfilter_copy_frame_props(fb, decoded_frame);
2107 fb->buf->priv = buf;
2108 fb->buf->free = filter_release_buffer;
2111 av_buffersrc_buffer(ist->filters[i]->filter, fb);
2113 av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2116 av_free(buffer_to_free);
2120 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2122 AVSubtitle subtitle;
2123 int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2124 &subtitle, got_output, pkt);
2130 rate_emu_sleep(ist);
2132 for (i = 0; i < nb_output_streams; i++) {
2133 OutputStream *ost = output_streams[i];
2135 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2138 do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2141 avsubtitle_free(&subtitle);
2145 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2146 static int output_packet(InputStream *ist, const AVPacket *pkt)
2152 if (ist->next_dts == AV_NOPTS_VALUE)
2153 ist->next_dts = ist->last_dts;
2157 av_init_packet(&avpkt);
2165 if (pkt->dts != AV_NOPTS_VALUE)
2166 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2168 // while we have more to decode or while the decoder did output something on EOF
2169 while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2173 ist->last_dts = ist->next_dts;
2175 if (avpkt.size && avpkt.size != pkt->size) {
2176 av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2177 "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2178 ist->showed_multi_packet_warning = 1;
2181 switch (ist->st->codec->codec_type) {
2182 case AVMEDIA_TYPE_AUDIO:
2183 ret = decode_audio (ist, &avpkt, &got_output);
2185 case AVMEDIA_TYPE_VIDEO:
2186 ret = decode_video (ist, &avpkt, &got_output);
2188 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2189 else if (ist->st->r_frame_rate.num)
2190 ist->next_dts += av_rescale_q(1, (AVRational){ist->st->r_frame_rate.den,
2191 ist->st->r_frame_rate.num},
2193 else if (ist->st->codec->time_base.num != 0) {
2194 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
2195 ist->st->codec->ticks_per_frame;
2196 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
2199 case AVMEDIA_TYPE_SUBTITLE:
2200 ret = transcode_subtitles(ist, &avpkt, &got_output);
2208 // touch data and size only if not EOF
2218 /* handle stream copy */
2219 if (!ist->decoding_needed) {
2220 rate_emu_sleep(ist);
2221 ist->last_dts = ist->next_dts;
2222 switch (ist->st->codec->codec_type) {
2223 case AVMEDIA_TYPE_AUDIO:
2224 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2225 ist->st->codec->sample_rate;
2227 case AVMEDIA_TYPE_VIDEO:
2228 if (ist->st->codec->time_base.num != 0) {
2229 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2230 ist->next_dts += ((int64_t)AV_TIME_BASE *
2231 ist->st->codec->time_base.num * ticks) /
2232 ist->st->codec->time_base.den;
2237 for (i = 0; pkt && i < nb_output_streams; i++) {
2238 OutputStream *ost = output_streams[i];
2240 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2243 do_streamcopy(ist, ost, pkt);
2249 static void print_sdp(void)
2253 AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2257 for (i = 0; i < nb_output_files; i++)
2258 avc[i] = output_files[i]->ctx;
2260 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2261 printf("SDP:\n%s\n", sdp);
2266 static int init_input_stream(int ist_index, char *error, int error_len)
2269 InputStream *ist = input_streams[ist_index];
2270 if (ist->decoding_needed) {
2271 AVCodec *codec = ist->dec;
2273 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2274 ist->st->codec->codec_id, ist->file_index, ist->st->index);
2275 return AVERROR(EINVAL);
2278 /* update requested sample format for the decoder based on the
2279 corresponding encoder sample format */
2280 for (i = 0; i < nb_output_streams; i++) {
2281 OutputStream *ost = output_streams[i];
2282 if (ost->source_index == ist_index) {
2283 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
2288 if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2289 ist->st->codec->get_buffer = codec_get_buffer;
2290 ist->st->codec->release_buffer = codec_release_buffer;
2291 ist->st->codec->opaque = &ist->buffer_pool;
2294 if (!av_dict_get(ist->opts, "threads", NULL, 0))
2295 av_dict_set(&ist->opts, "threads", "auto", 0);
2296 if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2297 snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2298 ist->file_index, ist->st->index);
2299 return AVERROR(EINVAL);
2301 assert_codec_experimental(ist->st->codec, 0);
2302 assert_avoptions(ist->opts);
2305 ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
2306 ist->next_dts = AV_NOPTS_VALUE;
2307 init_pts_correction(&ist->pts_ctx);
2313 static InputStream *get_input_stream(OutputStream *ost)
2315 if (ost->source_index >= 0)
2316 return input_streams[ost->source_index];
2319 FilterGraph *fg = ost->filter->graph;
2322 for (i = 0; i < fg->nb_inputs; i++)
2323 if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2324 return fg->inputs[i]->ist;
2330 static int transcode_init(void)
2332 int ret = 0, i, j, k;
2333 AVFormatContext *oc;
2334 AVCodecContext *codec, *icodec;
2340 /* init framerate emulation */
2341 for (i = 0; i < nb_input_files; i++) {
2342 InputFile *ifile = input_files[i];
2343 if (ifile->rate_emu)
2344 for (j = 0; j < ifile->nb_streams; j++)
2345 input_streams[j + ifile->ist_index]->start = av_gettime();
2348 /* output stream init */
2349 for (i = 0; i < nb_output_files; i++) {
2350 oc = output_files[i]->ctx;
2351 if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2352 av_dump_format(oc, i, oc->filename, 1);
2353 av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2354 return AVERROR(EINVAL);
2358 /* init complex filtergraphs */
2359 for (i = 0; i < nb_filtergraphs; i++)
2360 if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2363 /* for each output stream, we compute the right encoding parameters */
2364 for (i = 0; i < nb_output_streams; i++) {
2365 ost = output_streams[i];
2366 oc = output_files[ost->file_index]->ctx;
2367 ist = get_input_stream(ost);
2369 if (ost->attachment_filename)
2372 codec = ost->st->codec;
2375 icodec = ist->st->codec;
2377 ost->st->disposition = ist->st->disposition;
2378 codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2379 codec->chroma_sample_location = icodec->chroma_sample_location;
2382 if (ost->stream_copy) {
2383 uint64_t extra_size;
2385 av_assert0(ist && !ost->filter);
2387 extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2389 if (extra_size > INT_MAX) {
2390 return AVERROR(EINVAL);
2393 /* if stream_copy is selected, no need to decode or encode */
2394 codec->codec_id = icodec->codec_id;
2395 codec->codec_type = icodec->codec_type;
2397 if (!codec->codec_tag) {
2398 if (!oc->oformat->codec_tag ||
2399 av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2400 av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2401 codec->codec_tag = icodec->codec_tag;
2404 codec->bit_rate = icodec->bit_rate;
2405 codec->rc_max_rate = icodec->rc_max_rate;
2406 codec->rc_buffer_size = icodec->rc_buffer_size;
2407 codec->field_order = icodec->field_order;
2408 codec->extradata = av_mallocz(extra_size);
2409 if (!codec->extradata) {
2410 return AVERROR(ENOMEM);
2412 memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2413 codec->extradata_size = icodec->extradata_size;
2415 codec->time_base = icodec->time_base;
2416 codec->time_base.num *= icodec->ticks_per_frame;
2417 av_reduce(&codec->time_base.num, &codec->time_base.den,
2418 codec->time_base.num, codec->time_base.den, INT_MAX);
2420 codec->time_base = ist->st->time_base;
2422 switch (codec->codec_type) {
2423 case AVMEDIA_TYPE_AUDIO:
2424 if (audio_volume != 256) {
2425 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2428 codec->channel_layout = icodec->channel_layout;
2429 codec->sample_rate = icodec->sample_rate;
2430 codec->channels = icodec->channels;
2431 codec->frame_size = icodec->frame_size;
2432 codec->audio_service_type = icodec->audio_service_type;
2433 codec->block_align = icodec->block_align;
2435 case AVMEDIA_TYPE_VIDEO:
2436 codec->pix_fmt = icodec->pix_fmt;
2437 codec->width = icodec->width;
2438 codec->height = icodec->height;
2439 codec->has_b_frames = icodec->has_b_frames;
2440 if (!codec->sample_aspect_ratio.num) {
2441 codec->sample_aspect_ratio =
2442 ost->st->sample_aspect_ratio =
2443 ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2444 ist->st->codec->sample_aspect_ratio.num ?
2445 ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2448 case AVMEDIA_TYPE_SUBTITLE:
2449 codec->width = icodec->width;
2450 codec->height = icodec->height;
2452 case AVMEDIA_TYPE_DATA:
2453 case AVMEDIA_TYPE_ATTACHMENT:
2460 /* should only happen when a default codec is not present. */
2461 snprintf(error, sizeof(error), "Automatic encoder selection "
2462 "failed for output stream #%d:%d. Default encoder for "
2463 "format %s is probably disabled. Please choose an "
2464 "encoder manually.\n", ost->file_index, ost->index,
2466 ret = AVERROR(EINVAL);
2471 ist->decoding_needed = 1;
2472 ost->encoding_needed = 1;
2475 * We want CFR output if and only if one of those is true:
2476 * 1) user specified output framerate with -r
2477 * 2) user specified -vsync cfr
2478 * 3) output format is CFR and the user didn't force vsync to
2479 * something else than CFR
2481 * in such a case, set ost->frame_rate
2483 if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
2484 !ost->frame_rate.num && ist &&
2485 (video_sync_method == VSYNC_CFR ||
2486 (video_sync_method == VSYNC_AUTO &&
2487 !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
2488 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2489 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2490 int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2491 ost->frame_rate = ost->enc->supported_framerates[idx];
2496 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2497 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2499 fg = init_simple_filtergraph(ist, ost);
2500 if (configure_filtergraph(fg)) {
2501 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2506 switch (codec->codec_type) {
2507 case AVMEDIA_TYPE_AUDIO:
2508 codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2509 codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2510 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2511 codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
2512 codec->time_base = (AVRational){ 1, codec->sample_rate };
2514 case AVMEDIA_TYPE_VIDEO:
2515 codec->time_base = ost->filter->filter->inputs[0]->time_base;
2517 codec->width = ost->filter->filter->inputs[0]->w;
2518 codec->height = ost->filter->filter->inputs[0]->h;
2519 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2520 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2521 av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2522 ost->filter->filter->inputs[0]->sample_aspect_ratio;
2523 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2525 if (codec->width != icodec->width ||
2526 codec->height != icodec->height ||
2527 codec->pix_fmt != icodec->pix_fmt) {
2528 codec->bits_per_raw_sample = 0;
2532 case AVMEDIA_TYPE_SUBTITLE:
2533 codec->time_base = (AVRational){1, 1000};
2540 if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2541 char logfilename[1024];
2544 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2545 pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2547 if (!strcmp(ost->enc->name, "libx264")) {
2548 av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2550 if (codec->flags & CODEC_FLAG_PASS1) {
2551 f = fopen(logfilename, "wb");
2553 av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2554 logfilename, strerror(errno));
2560 size_t logbuffer_size;
2561 if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2562 av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2566 codec->stats_in = logbuffer;
2573 /* open each encoder */
2574 for (i = 0; i < nb_output_streams; i++) {
2575 ost = output_streams[i];
2576 if (ost->encoding_needed) {
2577 AVCodec *codec = ost->enc;
2578 AVCodecContext *dec = NULL;
2580 if ((ist = get_input_stream(ost)))
2581 dec = ist->st->codec;
2582 if (dec && dec->subtitle_header) {
2583 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2584 if (!ost->st->codec->subtitle_header) {
2585 ret = AVERROR(ENOMEM);
2588 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2589 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2591 if (!av_dict_get(ost->opts, "threads", NULL, 0))
2592 av_dict_set(&ost->opts, "threads", "auto", 0);
2593 if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2594 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2595 ost->file_index, ost->index);
2596 ret = AVERROR(EINVAL);
2599 assert_codec_experimental(ost->st->codec, 1);
2600 assert_avoptions(ost->opts);
2601 if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2602 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2603 "It takes bits/s as argument, not kbits/s\n");
2604 extra_size += ost->st->codec->extradata_size;
2606 if (ost->st->codec->me_threshold)
2607 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2611 /* init input streams */
2612 for (i = 0; i < nb_input_streams; i++)
2613 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2616 /* discard unused programs */
2617 for (i = 0; i < nb_input_files; i++) {
2618 InputFile *ifile = input_files[i];
2619 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2620 AVProgram *p = ifile->ctx->programs[j];
2621 int discard = AVDISCARD_ALL;
2623 for (k = 0; k < p->nb_stream_indexes; k++)
2624 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2625 discard = AVDISCARD_DEFAULT;
2628 p->discard = discard;
2632 /* open files and write file headers */
2633 for (i = 0; i < nb_output_files; i++) {
2634 oc = output_files[i]->ctx;
2635 oc->interrupt_callback = int_cb;
2636 if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2638 const char *errbuf_ptr = errbuf;
2639 if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2640 errbuf_ptr = strerror(AVUNERROR(ret));
2641 snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2642 ret = AVERROR(EINVAL);
2645 assert_avoptions(output_files[i]->opts);
2646 if (strcmp(oc->oformat->name, "rtp")) {
2652 /* dump the file output parameters - cannot be done before in case
2654 for (i = 0; i < nb_output_files; i++) {
2655 av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2658 /* dump the stream mapping */
2659 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2660 for (i = 0; i < nb_input_streams; i++) {
2661 ist = input_streams[i];
2663 for (j = 0; j < ist->nb_filters; j++) {
2664 if (ist->filters[j]->graph->graph_desc) {
2665 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2666 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2667 ist->filters[j]->name);
2668 if (nb_filtergraphs > 1)
2669 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2670 av_log(NULL, AV_LOG_INFO, "\n");
2675 for (i = 0; i < nb_output_streams; i++) {
2676 ost = output_streams[i];
2678 if (ost->attachment_filename) {
2679 /* an attached file */
2680 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2681 ost->attachment_filename, ost->file_index, ost->index);
2685 if (ost->filter && ost->filter->graph->graph_desc) {
2686 /* output from a complex graph */
2687 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2688 if (nb_filtergraphs > 1)
2689 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2691 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2692 ost->index, ost->enc ? ost->enc->name : "?");
2696 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2697 input_streams[ost->source_index]->file_index,
2698 input_streams[ost->source_index]->st->index,
2701 if (ost->sync_ist != input_streams[ost->source_index])
2702 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2703 ost->sync_ist->file_index,
2704 ost->sync_ist->st->index);
2705 if (ost->stream_copy)
2706 av_log(NULL, AV_LOG_INFO, " (copy)");
2708 av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2709 input_streams[ost->source_index]->dec->name : "?",
2710 ost->enc ? ost->enc->name : "?");
2711 av_log(NULL, AV_LOG_INFO, "\n");
2715 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2727 * @return 1 if there are still streams where more output is wanted,
2730 static int need_output(void)
2734 for (i = 0; i < nb_output_streams; i++) {
2735 OutputStream *ost = output_streams[i];
2736 OutputFile *of = output_files[ost->file_index];
2737 AVFormatContext *os = output_files[ost->file_index]->ctx;
2739 if (ost->is_past_recording_time ||
2740 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2742 if (ost->frame_number >= ost->max_frames) {
2744 for (j = 0; j < of->ctx->nb_streams; j++)
2745 output_streams[of->ost_index + j]->is_past_recording_time = 1;
2755 static int select_input_file(uint8_t *no_packet)
2757 int64_t ipts_min = INT64_MAX;
2758 int i, file_index = -1;
2760 for (i = 0; i < nb_input_streams; i++) {
2761 InputStream *ist = input_streams[i];
2762 int64_t ipts = ist->last_dts;
2764 if (ist->discard || no_packet[ist->file_index])
2766 if (!input_files[ist->file_index]->eof_reached) {
2767 if (ipts < ipts_min) {
2769 file_index = ist->file_index;
2778 static void *input_thread(void *arg)
2783 while (!transcoding_finished && ret >= 0) {
2785 ret = av_read_frame(f->ctx, &pkt);
2787 if (ret == AVERROR(EAGAIN)) {
2794 pthread_mutex_lock(&f->fifo_lock);
2795 while (!av_fifo_space(f->fifo))
2796 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2798 av_dup_packet(&pkt);
2799 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2801 pthread_mutex_unlock(&f->fifo_lock);
2808 static void free_input_threads(void)
2812 if (nb_input_files == 1)
2815 transcoding_finished = 1;
2817 for (i = 0; i < nb_input_files; i++) {
2818 InputFile *f = input_files[i];
2821 if (!f->fifo || f->joined)
2824 pthread_mutex_lock(&f->fifo_lock);
2825 while (av_fifo_size(f->fifo)) {
2826 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2827 av_free_packet(&pkt);
2829 pthread_cond_signal(&f->fifo_cond);
2830 pthread_mutex_unlock(&f->fifo_lock);
2832 pthread_join(f->thread, NULL);
2835 while (av_fifo_size(f->fifo)) {
2836 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2837 av_free_packet(&pkt);
2839 av_fifo_free(f->fifo);
2843 static int init_input_threads(void)
2847 if (nb_input_files == 1)
2850 for (i = 0; i < nb_input_files; i++) {
2851 InputFile *f = input_files[i];
2853 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2854 return AVERROR(ENOMEM);
2856 pthread_mutex_init(&f->fifo_lock, NULL);
2857 pthread_cond_init (&f->fifo_cond, NULL);
2859 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2860 return AVERROR(ret);
2865 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2869 pthread_mutex_lock(&f->fifo_lock);
2871 if (av_fifo_size(f->fifo)) {
2872 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2873 pthread_cond_signal(&f->fifo_cond);
2878 ret = AVERROR(EAGAIN);
2881 pthread_mutex_unlock(&f->fifo_lock);
2887 static int get_input_packet(InputFile *f, AVPacket *pkt)
2890 if (nb_input_files > 1)
2891 return get_input_packet_mt(f, pkt);
2893 return av_read_frame(f->ctx, pkt);
2897 * The following code is the main loop of the file converter
2899 static int transcode(void)
2902 AVFormatContext *is, *os;
2906 int no_packet_count = 0;
2907 int64_t timer_start;
2909 if (!(no_packet = av_mallocz(nb_input_files)))
2912 ret = transcode_init();
2916 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2919 timer_start = av_gettime();
2922 if ((ret = init_input_threads()) < 0)
2926 for (; received_sigterm == 0;) {
2927 int file_index, ist_index;
2930 /* check if there's any stream where output is still needed */
2931 if (!need_output()) {
2932 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2936 /* select the stream that we must read now */
2937 file_index = select_input_file(no_packet);
2938 /* if none, if is finished */
2939 if (file_index < 0) {
2940 if (no_packet_count) {
2941 no_packet_count = 0;
2942 memset(no_packet, 0, nb_input_files);
2946 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
2950 is = input_files[file_index]->ctx;
2951 ret = get_input_packet(input_files[file_index], &pkt);
2953 if (ret == AVERROR(EAGAIN)) {
2954 no_packet[file_index] = 1;
2959 input_files[file_index]->eof_reached = 1;
2961 for (i = 0; i < input_files[file_index]->nb_streams; i++) {
2962 ist = input_streams[input_files[file_index]->ist_index + i];
2963 if (ist->decoding_needed)
2964 output_packet(ist, NULL);
2973 no_packet_count = 0;
2974 memset(no_packet, 0, nb_input_files);
2977 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2978 is->streams[pkt.stream_index]);
2980 /* the following test is needed in case new streams appear
2981 dynamically in stream : we ignore them */
2982 if (pkt.stream_index >= input_files[file_index]->nb_streams)
2983 goto discard_packet;
2984 ist_index = input_files[file_index]->ist_index + pkt.stream_index;
2985 ist = input_streams[ist_index];
2987 goto discard_packet;
2989 if (pkt.dts != AV_NOPTS_VALUE)
2990 pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2991 if (pkt.pts != AV_NOPTS_VALUE)
2992 pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2994 if (pkt.pts != AV_NOPTS_VALUE)
2995 pkt.pts *= ist->ts_scale;
2996 if (pkt.dts != AV_NOPTS_VALUE)
2997 pkt.dts *= ist->ts_scale;
2999 //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
3001 // pkt.dts, input_files[ist->file_index].ts_offset,
3002 // ist->st->codec->codec_type);
3003 if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
3004 && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3005 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3006 int64_t delta = pkt_dts - ist->next_dts;
3007 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
3008 input_files[ist->file_index]->ts_offset -= delta;
3009 av_log(NULL, AV_LOG_DEBUG,
3010 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3011 delta, input_files[ist->file_index]->ts_offset);
3012 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3013 if (pkt.pts != AV_NOPTS_VALUE)
3014 pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3018 // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3019 if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
3020 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3021 ist->file_index, ist->st->index);
3024 av_free_packet(&pkt);
3029 av_free_packet(&pkt);
3031 /* dump report by using the output first video and audio streams */
3032 print_report(0, timer_start);
3035 free_input_threads();
3038 /* at the end of stream, we must flush the decoder buffers */
3039 for (i = 0; i < nb_input_streams; i++) {
3040 ist = input_streams[i];
3041 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3042 output_packet(ist, NULL);
3050 /* write the trailer if needed and close file */
3051 for (i = 0; i < nb_output_files; i++) {
3052 os = output_files[i]->ctx;
3053 av_write_trailer(os);
3056 /* dump report by using the first video and audio streams */
3057 print_report(1, timer_start);
3059 /* close each encoder */
3060 for (i = 0; i < nb_output_streams; i++) {
3061 ost = output_streams[i];
3062 if (ost->encoding_needed) {
3063 av_freep(&ost->st->codec->stats_in);
3064 avcodec_close(ost->st->codec);
3068 /* close each decoder */
3069 for (i = 0; i < nb_input_streams; i++) {
3070 ist = input_streams[i];
3071 if (ist->decoding_needed) {
3072 avcodec_close(ist->st->codec);
3080 av_freep(&no_packet);
3082 free_input_threads();
3085 if (output_streams) {
3086 for (i = 0; i < nb_output_streams; i++) {
3087 ost = output_streams[i];
3089 if (ost->stream_copy)
3090 av_freep(&ost->st->codec->extradata);
3092 fclose(ost->logfile);
3093 ost->logfile = NULL;
3095 av_freep(&ost->st->codec->subtitle_header);
3096 av_free(ost->forced_kf_pts);
3097 av_dict_free(&ost->opts);
3104 static double parse_frame_aspect_ratio(const char *arg)
3111 p = strchr(arg, ':');
3113 x = strtol(arg, &end, 10);
3115 y = strtol(end + 1, &end, 10);
3117 ar = (double)x / (double)y;
3119 ar = strtod(arg, NULL);
3122 av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
3128 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3130 return parse_option(o, "codec:a", arg, options);
3133 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3135 return parse_option(o, "codec:v", arg, options);
3138 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3140 return parse_option(o, "codec:s", arg, options);
3143 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3145 return parse_option(o, "codec:d", arg, options);
3148 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3150 StreamMap *m = NULL;
3151 int i, negative = 0, file_idx;
3152 int sync_file_idx = -1, sync_stream_idx;
3160 map = av_strdup(arg);
3162 /* parse sync stream first, just pick first matching stream */
3163 if (sync = strchr(map, ',')) {
3165 sync_file_idx = strtol(sync + 1, &sync, 0);
3166 if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3167 av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3172 for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3173 if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3174 input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3175 sync_stream_idx = i;
3178 if (i == input_files[sync_file_idx]->nb_streams) {
3179 av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3180 "match any streams.\n", arg);
3186 if (map[0] == '[') {
3187 /* this mapping refers to lavfi output */
3188 const char *c = map + 1;
3189 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3190 &o->nb_stream_maps, o->nb_stream_maps + 1);
3191 m = &o->stream_maps[o->nb_stream_maps - 1];
3192 m->linklabel = av_get_token(&c, "]");
3193 if (!m->linklabel) {
3194 av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3198 file_idx = strtol(map, &p, 0);
3199 if (file_idx >= nb_input_files || file_idx < 0) {
3200 av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3204 /* disable some already defined maps */
3205 for (i = 0; i < o->nb_stream_maps; i++) {
3206 m = &o->stream_maps[i];
3207 if (file_idx == m->file_index &&
3208 check_stream_specifier(input_files[m->file_index]->ctx,
3209 input_files[m->file_index]->ctx->streams[m->stream_index],
3210 *p == ':' ? p + 1 : p) > 0)
3214 for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3215 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3216 *p == ':' ? p + 1 : p) <= 0)
3218 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3219 &o->nb_stream_maps, o->nb_stream_maps + 1);
3220 m = &o->stream_maps[o->nb_stream_maps - 1];
3222 m->file_index = file_idx;
3223 m->stream_index = i;
3225 if (sync_file_idx >= 0) {
3226 m->sync_file_index = sync_file_idx;
3227 m->sync_stream_index = sync_stream_idx;
3229 m->sync_file_index = file_idx;
3230 m->sync_stream_index = i;
3236 av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3244 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3246 o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3247 &o->nb_attachments, o->nb_attachments + 1);
3248 o->attachments[o->nb_attachments - 1] = arg;
3253 * Parse a metadata specifier in arg.
3254 * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3255 * @param index for type c/p, chapter/program index is written here
3256 * @param stream_spec for type s, the stream specifier is written here
3258 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3266 if (*(++arg) && *arg != ':') {
3267 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3270 *stream_spec = *arg == ':' ? arg + 1 : "";
3274 if (*(++arg) == ':')
3275 *index = strtol(++arg, NULL, 0);
3278 av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3285 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3287 AVDictionary **meta_in = NULL;
3288 AVDictionary **meta_out;
3290 char type_in, type_out;
3291 const char *istream_spec = NULL, *ostream_spec = NULL;
3292 int idx_in = 0, idx_out = 0;
3294 parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
3295 parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3297 if (type_in == 'g' || type_out == 'g')
3298 o->metadata_global_manual = 1;
3299 if (type_in == 's' || type_out == 's')
3300 o->metadata_streams_manual = 1;
3301 if (type_in == 'c' || type_out == 'c')
3302 o->metadata_chapters_manual = 1;
3304 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3305 if ((index) < 0 || (index) >= (nb_elems)) {\
3306 av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3311 #define SET_DICT(type, meta, context, index)\
3314 meta = &context->metadata;\
3317 METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3318 meta = &context->chapters[index]->metadata;\
3321 METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3322 meta = &context->programs[index]->metadata;\
3326 SET_DICT(type_in, meta_in, ic, idx_in);
3327 SET_DICT(type_out, meta_out, oc, idx_out);
3329 /* for input streams choose first matching stream */
3330 if (type_in == 's') {
3331 for (i = 0; i < ic->nb_streams; i++) {
3332 if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3333 meta_in = &ic->streams[i]->metadata;
3339 av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
3344 if (type_out == 's') {
3345 for (i = 0; i < oc->nb_streams; i++) {
3346 if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3347 meta_out = &oc->streams[i]->metadata;
3348 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3353 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3358 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3360 const char *codec_string = encoder ? "encoder" : "decoder";
3364 avcodec_find_encoder_by_name(name) :
3365 avcodec_find_decoder_by_name(name);
3367 av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3370 if (codec->type != type) {
3371 av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3377 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3379 char *codec_name = NULL;
3381 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3383 AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3384 st->codec->codec_id = codec->id;
3387 return avcodec_find_decoder(st->codec->codec_id);
3391 * Add all the streams from the given input file to the global
3392 * list of input streams.
3394 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3398 for (i = 0; i < ic->nb_streams; i++) {
3399 AVStream *st = ic->streams[i];
3400 AVCodecContext *dec = st->codec;
3401 InputStream *ist = av_mallocz(sizeof(*ist));
3402 char *framerate = NULL;
3407 input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3408 input_streams[nb_input_streams - 1] = ist;
3411 ist->file_index = nb_input_files;
3413 st->discard = AVDISCARD_ALL;
3414 ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
3416 ist->ts_scale = 1.0;
3417 MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3419 ist->dec = choose_decoder(o, ic, st);
3421 switch (dec->codec_type) {
3422 case AVMEDIA_TYPE_VIDEO:
3423 ist->resample_height = dec->height;
3424 ist->resample_width = dec->width;
3425 ist->resample_pix_fmt = dec->pix_fmt;
3427 MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
3428 if (framerate && av_parse_video_rate(&ist->framerate,
3430 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
3436 case AVMEDIA_TYPE_AUDIO:
3437 guess_input_channel_layout(ist);
3439 ist->resample_sample_fmt = dec->sample_fmt;
3440 ist->resample_sample_rate = dec->sample_rate;
3441 ist->resample_channels = dec->channels;
3442 ist->resample_channel_layout = dec->channel_layout;
3445 case AVMEDIA_TYPE_DATA:
3446 case AVMEDIA_TYPE_SUBTITLE:
3447 case AVMEDIA_TYPE_ATTACHMENT:
3448 case AVMEDIA_TYPE_UNKNOWN:
3456 static void assert_file_overwrite(const char *filename)
3458 if (!file_overwrite &&
3459 (strchr(filename, ':') == NULL || filename[1] == ':' ||
3460 av_strstart(filename, "file:", NULL))) {
3461 if (avio_check(filename, 0) == 0) {
3463 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3465 if (!read_yesno()) {
3466 fprintf(stderr, "Not overwriting - exiting\n");
3471 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3478 static void dump_attachment(AVStream *st, const char *filename)
3481 AVIOContext *out = NULL;
3482 AVDictionaryEntry *e;
3484 if (!st->codec->extradata_size) {
3485 av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3486 nb_input_files - 1, st->index);
3489 if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3490 filename = e->value;
3492 av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3493 "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3497 assert_file_overwrite(filename);
3499 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3500 av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3505 avio_write(out, st->codec->extradata, st->codec->extradata_size);
3510 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3512 AVFormatContext *ic;
3513 AVInputFormat *file_iformat = NULL;
3517 AVDictionary **opts;
3518 int orig_nb_streams; // number of streams before avformat_find_stream_info
3521 if (!(file_iformat = av_find_input_format(o->format))) {
3522 av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3527 if (!strcmp(filename, "-"))
3530 using_stdin |= !strncmp(filename, "pipe:", 5) ||
3531 !strcmp(filename, "/dev/stdin");
3533 /* get default parameters from command line */
3534 ic = avformat_alloc_context();
3536 print_error(filename, AVERROR(ENOMEM));
3539 if (o->nb_audio_sample_rate) {
3540 snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3541 av_dict_set(&format_opts, "sample_rate", buf, 0);
3543 if (o->nb_audio_channels) {
3544 /* because we set audio_channels based on both the "ac" and
3545 * "channel_layout" options, we need to check that the specified
3546 * demuxer actually has the "channels" option before setting it */
3547 if (file_iformat && file_iformat->priv_class &&
3548 av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
3549 AV_OPT_SEARCH_FAKE_OBJ)) {
3550 snprintf(buf, sizeof(buf), "%d",
3551 o->audio_channels[o->nb_audio_channels - 1].u.i);
3552 av_dict_set(&format_opts, "channels", buf, 0);
3555 if (o->nb_frame_rates) {
3556 /* set the format-level framerate option;
3557 * this is important for video grabbers, e.g. x11 */
3558 if (file_iformat && file_iformat->priv_class &&
3559 av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
3560 AV_OPT_SEARCH_FAKE_OBJ)) {
3561 av_dict_set(&format_opts, "framerate",
3562 o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3565 if (o->nb_frame_sizes) {
3566 av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3568 if (o->nb_frame_pix_fmts)
3569 av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3571 ic->flags |= AVFMT_FLAG_NONBLOCK;
3572 ic->interrupt_callback = int_cb;
3574 /* open the input file with generic libav function */
3575 err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3577 print_error(filename, err);
3580 assert_avoptions(format_opts);
3582 /* apply forced codec ids */
3583 for (i = 0; i < ic->nb_streams; i++)
3584 choose_decoder(o, ic, ic->streams[i]);
3586 /* Set AVCodecContext options for avformat_find_stream_info */
3587 opts = setup_find_stream_info_opts(ic, codec_opts);
3588 orig_nb_streams = ic->nb_streams;
3590 /* If not enough info to get the stream parameters, we decode the
3591 first frames to get it. (used in mpeg case for example) */
3592 ret = avformat_find_stream_info(ic, opts);
3594 av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3595 avformat_close_input(&ic);
3599 timestamp = o->start_time;
3600 /* add the stream start time */
3601 if (ic->start_time != AV_NOPTS_VALUE)
3602 timestamp += ic->start_time;
3604 /* if seeking requested, we execute it */
3605 if (o->start_time != 0) {
3606 ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3608 av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3609 filename, (double)timestamp / AV_TIME_BASE);
3613 /* update the current parameters so that they match the one of the input stream */
3614 add_input_streams(o, ic);
3616 /* dump the file content */
3617 av_dump_format(ic, nb_input_files, filename, 0);
3619 input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3620 if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
3623 input_files[nb_input_files - 1]->ctx = ic;
3624 input_files[nb_input_files - 1]->ist_index = nb_input_streams - ic->nb_streams;
3625 input_files[nb_input_files - 1]->ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3626 input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
3627 input_files[nb_input_files - 1]->rate_emu = o->rate_emu;
3629 for (i = 0; i < o->nb_dump_attachment; i++) {
3632 for (j = 0; j < ic->nb_streams; j++) {
3633 AVStream *st = ic->streams[j];
3635 if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3636 dump_attachment(st, o->dump_attachment[i].u.str);
3640 for (i = 0; i < orig_nb_streams; i++)
3641 av_dict_free(&opts[i]);
3648 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3649 AVCodecContext *avctx)
3655 for (p = kf; *p; p++)
3658 ost->forced_kf_count = n;
3659 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3660 if (!ost->forced_kf_pts) {
3661 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3664 for (i = 0; i < n; i++) {
3665 p = i ? strchr(p, ',') + 1 : kf;
3666 t = parse_time_or_die("force_key_frames", p, 1);
3667 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3671 static uint8_t *get_line(AVIOContext *s)
3677 if (avio_open_dyn_buf(&line) < 0) {
3678 av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3682 while ((c = avio_r8(s)) && c != '\n')
3685 avio_close_dyn_buf(line, &buf);
3690 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3693 char filename[1000];
3694 const char *base[3] = { getenv("AVCONV_DATADIR"),
3699 for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3703 snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3704 i != 1 ? "" : "/.avconv", codec_name, preset_name);
3705 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3708 snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3709 i != 1 ? "" : "/.avconv", preset_name);
3710 ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3716 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3718 char *codec_name = NULL;
3720 MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3722 ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3723 NULL, ost->st->codec->codec_type);
3724 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3725 } else if (!strcmp(codec_name, "copy"))
3726 ost->stream_copy = 1;
3728 ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3729 ost->st->codec->codec_id = ost->enc->id;
3733 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3736 AVStream *st = avformat_new_stream(oc, NULL);
3737 int idx = oc->nb_streams - 1, ret = 0;
3738 char *bsf = NULL, *next, *codec_tag = NULL;
3739 AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3741 char *buf = NULL, *arg = NULL, *preset = NULL;
3742 AVIOContext *s = NULL;
3745 av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3749 if (oc->nb_streams - 1 < o->nb_streamid_map)
3750 st->id = o->streamid_map[oc->nb_streams - 1];
3752 output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3753 nb_output_streams + 1);
3754 if (!(ost = av_mallocz(sizeof(*ost))))
3756 output_streams[nb_output_streams - 1] = ost;
3758 ost->file_index = nb_output_files;
3761 st->codec->codec_type = type;
3762 choose_encoder(o, oc, ost);
3764 ost->opts = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
3767 avcodec_get_context_defaults3(st->codec, ost->enc);
3768 st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3770 MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3771 if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3774 if (!buf[0] || buf[0] == '#') {
3778 if (!(arg = strchr(buf, '='))) {
3779 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3783 av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3785 } while (!s->eof_reached);
3789 av_log(NULL, AV_LOG_FATAL,
3790 "Preset %s specified for stream %d:%d, but could not be opened.\n",
3791 preset, ost->file_index, ost->index);
3795 ost->max_frames = INT64_MAX;
3796 MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3798 MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3800 if (next = strchr(bsf, ','))
3802 if (!(bsfc = av_bitstream_filter_init(bsf))) {
3803 av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3807 bsfc_prev->next = bsfc;
3809 ost->bitstream_filters = bsfc;
3815 MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
3817 uint32_t tag = strtol(codec_tag, &next, 0);
3819 tag = AV_RL32(codec_tag);
3820 st->codec->codec_tag = tag;
3823 MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
3824 if (qscale >= 0 || same_quant) {
3825 st->codec->flags |= CODEC_FLAG_QSCALE;
3826 st->codec->global_quality = FF_QP2LAMBDA * qscale;
3829 if (oc->oformat->flags & AVFMT_GLOBALHEADER)
3830 st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
3832 av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
3834 ost->pix_fmts[0] = ost->pix_fmts[1] = PIX_FMT_NONE;
3839 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3842 const char *p = str;
3849 av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3856 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
3860 AVCodecContext *video_enc;
3862 ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
3864 video_enc = st->codec;
3866 if (!ost->stream_copy) {
3867 const char *p = NULL;
3868 char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
3869 char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
3870 char *intra_matrix = NULL, *inter_matrix = NULL;
3871 const char *filters = "null";
3874 MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
3875 if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
3876 av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
3880 MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
3881 if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
3882 av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
3886 MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
3887 if (frame_aspect_ratio)
3888 ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
3890 MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3891 if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
3892 av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
3895 st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
3897 MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
3899 if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
3900 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
3903 parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
3905 MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
3907 if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
3908 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
3911 parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
3914 MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
3915 for (i = 0; p; i++) {
3917 int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
3919 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
3922 video_enc->rc_override =
3923 av_realloc(video_enc->rc_override,
3924 sizeof(RcOverride) * (i + 1));
3925 video_enc->rc_override[i].start_frame = start;
3926 video_enc->rc_override[i].end_frame = end;
3928 video_enc->rc_override[i].qscale = q;
3929 video_enc->rc_override[i].quality_factor = 1.0;
3932 video_enc->rc_override[i].qscale = 0;
3933 video_enc->rc_override[i].quality_factor = -q/100.0;
3938 video_enc->rc_override_count = i;
3939 if (!video_enc->rc_initial_buffer_occupancy)
3940 video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
3941 video_enc->intra_dc_precision = intra_dc_precision - 8;
3946 video_enc->flags |= CODEC_FLAG_PASS1;
3948 video_enc->flags |= CODEC_FLAG_PASS2;
3952 MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
3953 if (forced_key_frames)
3954 parse_forced_key_frames(forced_key_frames, ost, video_enc);
3956 MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
3958 ost->top_field_first = -1;
3959 MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
3961 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3962 ost->avfilter = av_strdup(filters);
3964 MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
3970 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
3974 AVCodecContext *audio_enc;
3976 ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
3979 audio_enc = st->codec;
3980 audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
3982 if (!ost->stream_copy) {
3983 char *sample_fmt = NULL;
3984 const char *filters = "anull";
3986 MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
3988 MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
3990 (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
3991 av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
3995 MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
3997 MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
3998 ost->avfilter = av_strdup(filters);
4004 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
4008 ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
4009 if (!ost->stream_copy) {
4010 av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
4017 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
4019 OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
4020 ost->stream_copy = 1;
4024 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
4028 AVCodecContext *subtitle_enc;
4030 ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
4032 subtitle_enc = st->codec;
4034 subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4039 /* arg format is "output-stream-index:streamid-value". */
4040 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
4046 av_strlcpy(idx_str, arg, sizeof(idx_str));
4047 p = strchr(idx_str, ':');
4049 av_log(NULL, AV_LOG_FATAL,
4050 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
4055 idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
4056 o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
4057 o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
4061 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
4063 AVFormatContext *is = ifile->ctx;
4064 AVFormatContext *os = ofile->ctx;
4067 for (i = 0; i < is->nb_chapters; i++) {
4068 AVChapter *in_ch = is->chapters[i], *out_ch;
4069 int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
4070 AV_TIME_BASE_Q, in_ch->time_base);
4071 int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
4072 av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
4075 if (in_ch->end < ts_off)
4077 if (rt != INT64_MAX && in_ch->start > rt + ts_off)
4080 out_ch = av_mallocz(sizeof(AVChapter));
4082 return AVERROR(ENOMEM);
4084 out_ch->id = in_ch->id;
4085 out_ch->time_base = in_ch->time_base;
4086 out_ch->start = FFMAX(0, in_ch->start - ts_off);
4087 out_ch->end = FFMIN(rt, in_ch->end - ts_off);
4090 av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
4093 os->chapters = av_realloc(os->chapters, sizeof(AVChapter) * os->nb_chapters);
4095 return AVERROR(ENOMEM);
4096 os->chapters[os->nb_chapters - 1] = out_ch;
4101 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
4102 AVFormatContext *oc)
4106 switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
4107 ofilter->out_tmp->pad_idx)) {
4108 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
4109 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
4111 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
4116 ost->source_index = -1;
4117 ost->filter = ofilter;
4121 if (ost->stream_copy) {
4122 av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
4123 "which is fed from a complex filtergraph. Filtering and streamcopy "
4124 "cannot be used together.\n", ost->file_index, ost->index);
4128 if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
4129 av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
4132 avfilter_inout_free(&ofilter->out_tmp);
4135 static void opt_output_file(void *optctx, const char *filename)
4137 OptionsContext *o = optctx;
4138 AVFormatContext *oc;
4140 AVOutputFormat *file_oformat;
4144 if (configure_complex_filters() < 0) {
4145 av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
4149 if (!strcmp(filename, "-"))
4152 oc = avformat_alloc_context();
4154 print_error(filename, AVERROR(ENOMEM));
4159 file_oformat = av_guess_format(o->format, NULL, NULL);
4160 if (!file_oformat) {
4161 av_log(NULL, AV_LOG_FATAL, "Requested output format '%s' is not a suitable output format\n", o->format);
4165 file_oformat = av_guess_format(NULL, filename, NULL);
4166 if (!file_oformat) {
4167 av_log(NULL, AV_LOG_FATAL, "Unable to find a suitable output format for '%s'\n",
4173 oc->oformat = file_oformat;
4174 oc->interrupt_callback = int_cb;
4175 av_strlcpy(oc->filename, filename, sizeof(oc->filename));
4177 /* create streams for all unlabeled output pads */
4178 for (i = 0; i < nb_filtergraphs; i++) {
4179 FilterGraph *fg = filtergraphs[i];
4180 for (j = 0; j < fg->nb_outputs; j++) {
4181 OutputFilter *ofilter = fg->outputs[j];
4183 if (!ofilter->out_tmp || ofilter->out_tmp->name)
4186 switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
4187 ofilter->out_tmp->pad_idx)) {
4188 case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
4189 case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
4190 case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
4192 init_output_filter(ofilter, o, oc);
4196 if (!o->nb_stream_maps) {
4197 /* pick the "best" stream of each type */
4198 #define NEW_STREAM(type, index)\
4200 ost = new_ ## type ## _stream(o, oc);\
4201 ost->source_index = index;\
4202 ost->sync_ist = input_streams[index];\
4203 input_streams[index]->discard = 0;\
4204 input_streams[index]->st->discard = AVDISCARD_NONE;\
4207 /* video: highest resolution */
4208 if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
4209 int area = 0, idx = -1;
4210 for (i = 0; i < nb_input_streams; i++) {
4211 ist = input_streams[i];
4212 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4213 ist->st->codec->width * ist->st->codec->height > area) {
4214 area = ist->st->codec->width * ist->st->codec->height;
4218 NEW_STREAM(video, idx);
4221 /* audio: most channels */
4222 if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
4223 int channels = 0, idx = -1;
4224 for (i = 0; i < nb_input_streams; i++) {
4225 ist = input_streams[i];
4226 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
4227 ist->st->codec->channels > channels) {
4228 channels = ist->st->codec->channels;
4232 NEW_STREAM(audio, idx);
4235 /* subtitles: pick first */
4236 if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
4237 for (i = 0; i < nb_input_streams; i++)
4238 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4239 NEW_STREAM(subtitle, i);
4243 /* do something with data? */
4245 for (i = 0; i < o->nb_stream_maps; i++) {
4246 StreamMap *map = &o->stream_maps[i];
4251 if (map->linklabel) {
4253 OutputFilter *ofilter = NULL;
4256 for (j = 0; j < nb_filtergraphs; j++) {
4257 fg = filtergraphs[j];
4258 for (k = 0; k < fg->nb_outputs; k++) {
4259 AVFilterInOut *out = fg->outputs[k]->out_tmp;
4260 if (out && !strcmp(out->name, map->linklabel)) {
4261 ofilter = fg->outputs[k];
4268 av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
4269 "in any defined filter graph.\n", map->linklabel);
4272 init_output_filter(ofilter, o, oc);
4274 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
4275 switch (ist->st->codec->codec_type) {
4276 case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
4277 case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
4278 case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
4279 case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
4280 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
4282 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
4283 map->file_index, map->stream_index);
4287 ost->source_index = input_files[map->file_index]->ist_index + map->stream_index;
4288 ost->sync_ist = input_streams[input_files[map->sync_file_index]->ist_index +
4289 map->sync_stream_index];
4291 ist->st->discard = AVDISCARD_NONE;
4296 /* handle attached files */
4297 for (i = 0; i < o->nb_attachments; i++) {
4299 uint8_t *attachment;
4303 if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
4304 av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
4308 if ((len = avio_size(pb)) <= 0) {
4309 av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
4313 if (!(attachment = av_malloc(len))) {
4314 av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
4318 avio_read(pb, attachment, len);
4320 ost = new_attachment_stream(o, oc);
4321 ost->stream_copy = 0;
4322 ost->source_index = -1;
4323 ost->attachment_filename = o->attachments[i];
4324 ost->st->codec->extradata = attachment;
4325 ost->st->codec->extradata_size = len;
4327 p = strrchr(o->attachments[i], '/');
4328 av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
4332 output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
4333 if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
4336 output_files[nb_output_files - 1]->ctx = oc;
4337 output_files[nb_output_files - 1]->ost_index = nb_output_streams - oc->nb_streams;
4338 output_files[nb_output_files - 1]->recording_time = o->recording_time;
4339 if (o->recording_time != INT64_MAX)
4340 oc->duration = o->recording_time;
4341 output_files[nb_output_files - 1]->start_time = o->start_time;
4342 output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
4343 av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
4345 /* check filename in case of an image number is expected */
4346 if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
4347 if (!av_filename_number_test(oc->filename)) {
4348 print_error(oc->filename, AVERROR(EINVAL));
4353 if (!(oc->oformat->flags & AVFMT_NOFILE)) {
4354 /* test if it already exists to avoid losing precious files */
4355 assert_file_overwrite(filename);
4358 if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
4359 &oc->interrupt_callback,
4360 &output_files[nb_output_files - 1]->opts)) < 0) {
4361 print_error(filename, err);
4366 if (o->mux_preload) {
4368 snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
4369 av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
4371 oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
4372 oc->flags |= AVFMT_FLAG_NONBLOCK;
4375 for (i = 0; i < o->nb_metadata_map; i++) {
4377 int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
4379 if (in_file_index < 0)
4381 if (in_file_index >= nb_input_files) {
4382 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
4385 copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index]->ctx, o);
4389 if (o->chapters_input_file >= nb_input_files) {
4390 if (o->chapters_input_file == INT_MAX) {
4391 /* copy chapters from the first input file that has them*/
4392 o->chapters_input_file = -1;
4393 for (i = 0; i < nb_input_files; i++)
4394 if (input_files[i]->ctx->nb_chapters) {
4395 o->chapters_input_file = i;
4399 av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
4400 o->chapters_input_file);
4404 if (o->chapters_input_file >= 0)
4405 copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
4406 !o->metadata_chapters_manual);
4408 /* copy global metadata by default */
4409 if (!o->metadata_global_manual && nb_input_files)
4410 av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
4411 AV_DICT_DONT_OVERWRITE);
4412 if (!o->metadata_streams_manual)
4413 for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
4415 if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
4417 ist = input_streams[output_streams[i]->source_index];
4418 av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
4421 /* process manually set metadata */
4422 for (i = 0; i < o->nb_metadata; i++) {
4425 const char *stream_spec;
4426 int index = 0, j, ret;
4428 val = strchr(o->metadata[i].u.str, '=');
4430 av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
4431 o->metadata[i].u.str);
4436 parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
4438 for (j = 0; j < oc->nb_streams; j++) {
4439 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
4440 av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
4451 if (index < 0 || index >= oc->nb_chapters) {
4452 av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
4455 m = &oc->chapters[index]->metadata;
4458 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
4461 av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
4468 /* same option as mencoder */
4469 static int opt_pass(const char *opt, const char *arg)
4471 do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
4475 static int64_t getutime(void)
4478 struct rusage rusage;
4480 getrusage(RUSAGE_SELF, &rusage);
4481 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4482 #elif HAVE_GETPROCESSTIMES
4484 FILETIME c, e, k, u;
4485 proc = GetCurrentProcess();
4486 GetProcessTimes(proc, &c, &e, &k, &u);
4487 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4489 return av_gettime();
4493 static int64_t getmaxrss(void)
4495 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4496 struct rusage rusage;
4497 getrusage(RUSAGE_SELF, &rusage);
4498 return (int64_t)rusage.ru_maxrss * 1024;
4499 #elif HAVE_GETPROCESSMEMORYINFO
4501 PROCESS_MEMORY_COUNTERS memcounters;
4502 proc = GetCurrentProcess();
4503 memcounters.cb = sizeof(memcounters);
4504 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4505 return memcounters.PeakPagefileUsage;
4511 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4513 return parse_option(o, "q:a", arg, options);
4516 static void show_usage(void)
4518 printf("Hyper fast Audio and Video encoder\n");
4519 printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4523 static void show_help(void)
4525 int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4526 av_log_set_callback(log_callback_help);
4528 show_help_options(options, "Main options:\n",
4529 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4530 show_help_options(options, "\nAdvanced options:\n",
4531 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4533 show_help_options(options, "\nVideo options:\n",
4534 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4536 show_help_options(options, "\nAdvanced Video options:\n",
4537 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4538 OPT_VIDEO | OPT_EXPERT);
4539 show_help_options(options, "\nAudio options:\n",
4540 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4542 show_help_options(options, "\nAdvanced Audio options:\n",
4543 OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4544 OPT_AUDIO | OPT_EXPERT);
4545 show_help_options(options, "\nSubtitle options:\n",
4546 OPT_SUBTITLE | OPT_GRAB,
4548 show_help_options(options, "\nAudio/Video grab options:\n",
4552 show_help_children(avcodec_get_class(), flags);
4553 show_help_children(avformat_get_class(), flags);
4554 show_help_children(sws_get_class(), flags);
4557 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4559 enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4560 static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
4562 if (!strncmp(arg, "pal-", 4)) {
4565 } else if (!strncmp(arg, "ntsc-", 5)) {
4568 } else if (!strncmp(arg, "film-", 5)) {
4572 /* Try to determine PAL/NTSC by peeking in the input files */
4573 if (nb_input_files) {
4575 for (j = 0; j < nb_input_files; j++) {
4576 for (i = 0; i < input_files[j]->nb_streams; i++) {
4577 AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
4578 if (c->codec_type != AVMEDIA_TYPE_VIDEO)
4580 fr = c->time_base.den * 1000 / c->time_base.num;
4584 } else if ((fr == 29970) || (fr == 23976)) {
4589 if (norm != UNKNOWN)
4593 if (norm != UNKNOWN)
4594 av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4597 if (norm == UNKNOWN) {
4598 av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4599 av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4600 av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4604 if (!strcmp(arg, "vcd")) {
4605 opt_video_codec(o, "c:v", "mpeg1video");
4606 opt_audio_codec(o, "c:a", "mp2");
4607 parse_option(o, "f", "vcd", options);
4609 parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4610 parse_option(o, "r", frame_rates[norm], options);
4611 opt_default("g", norm == PAL ? "15" : "18");
4613 opt_default("b", "1150000");
4614 opt_default("maxrate", "1150000");
4615 opt_default("minrate", "1150000");
4616 opt_default("bufsize", "327680"); // 40*1024*8;
4618 opt_default("b:a", "224000");
4619 parse_option(o, "ar", "44100", options);
4620 parse_option(o, "ac", "2", options);
4622 opt_default("packetsize", "2324");
4623 opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4625 /* We have to offset the PTS, so that it is consistent with the SCR.
4626 SCR starts at 36000, but the first two packs contain only padding
4627 and the first pack from the other stream, respectively, may also have
4628 been written before.
4629 So the real data starts at SCR 36000+3*1200. */
4630 o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
4631 } else if (!strcmp(arg, "svcd")) {
4633 opt_video_codec(o, "c:v", "mpeg2video");
4634 opt_audio_codec(o, "c:a", "mp2");
4635 parse_option(o, "f", "svcd", options);
4637 parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4638 parse_option(o, "r", frame_rates[norm], options);
4639 opt_default("g", norm == PAL ? "15" : "18");
4641 opt_default("b", "2040000");
4642 opt_default("maxrate", "2516000");
4643 opt_default("minrate", "0"); // 1145000;
4644 opt_default("bufsize", "1835008"); // 224*1024*8;
4645 opt_default("flags", "+scan_offset");
4648 opt_default("b:a", "224000");
4649 parse_option(o, "ar", "44100", options);
4651 opt_default("packetsize", "2324");
4653 } else if (!strcmp(arg, "dvd")) {
4655 opt_video_codec(o, "c:v", "mpeg2video");
4656 opt_audio_codec(o, "c:a", "ac3");
4657 parse_option(o, "f", "dvd", options);
4659 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4660 parse_option(o, "r", frame_rates[norm], options);
4661 opt_default("g", norm == PAL ? "15" : "18");
4663 opt_default("b", "6000000");
4664 opt_default("maxrate", "9000000");
4665 opt_default("minrate", "0"); // 1500000;
4666 opt_default("bufsize", "1835008"); // 224*1024*8;
4668 opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4669 opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4671 opt_default("b:a", "448000");
4672 parse_option(o, "ar", "48000", options);
4674 } else if (!strncmp(arg, "dv", 2)) {
4676 parse_option(o, "f", "dv", options);
4678 parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4679 parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4680 norm == PAL ? "yuv420p" : "yuv411p", options);
4681 parse_option(o, "r", frame_rates[norm], options);
4683 parse_option(o, "ar", "48000", options);
4684 parse_option(o, "ac", "2", options);
4687 av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4688 return AVERROR(EINVAL);
4693 static int opt_vstats_file(const char *opt, const char *arg)
4695 av_free (vstats_filename);
4696 vstats_filename = av_strdup (arg);
4700 static int opt_vstats(const char *opt, const char *arg)
4703 time_t today2 = time(NULL);
4704 struct tm *today = localtime(&today2);
4706 snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4708 return opt_vstats_file(opt, filename);
4711 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4713 return parse_option(o, "frames:v", arg, options);
4716 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4718 return parse_option(o, "frames:a", arg, options);
4721 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4723 return parse_option(o, "frames:d", arg, options);
4726 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
4728 return parse_option(o, "tag:v", arg, options);
4731 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
4733 return parse_option(o, "tag:a", arg, options);
4736 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
4738 return parse_option(o, "tag:s", arg, options);
4741 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
4743 return parse_option(o, "filter:v", arg, options);
4746 static int opt_audio_filters(OptionsContext *o, const char *opt, const char *arg)
4748 return parse_option(o, "filter:a", arg, options);
4751 static int opt_vsync(const char *opt, const char *arg)
4753 if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
4754 else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
4755 else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
4757 if (video_sync_method == VSYNC_AUTO)
4758 video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
4762 static int opt_deinterlace(const char *opt, const char *arg)
4764 av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
4769 static int opt_cpuflags(const char *opt, const char *arg)
4771 int flags = av_parse_cpu_flags(arg);
4776 av_set_cpu_flags_mask(flags);
4780 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
4782 int idx = locate_option(argc, argv, options, "cpuflags");
4783 if (idx && argv[idx + 1])
4784 opt_cpuflags("cpuflags", argv[idx + 1]);
4787 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
4789 char layout_str[32];
4792 int ret, channels, ac_str_size;
4795 layout = av_get_channel_layout(arg);
4797 av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
4798 return AVERROR(EINVAL);
4800 snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
4801 ret = opt_default(opt, layout_str);
4805 /* set 'ac' option based on channel layout */
4806 channels = av_get_channel_layout_nb_channels(layout);
4807 snprintf(layout_str, sizeof(layout_str), "%d", channels);
4808 stream_str = strchr(opt, ':');
4809 ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
4810 ac_str = av_mallocz(ac_str_size);
4812 return AVERROR(ENOMEM);
4813 av_strlcpy(ac_str, "ac", 3);
4815 av_strlcat(ac_str, stream_str, ac_str_size);
4816 ret = parse_option(o, ac_str, layout_str, options);
4822 static int opt_filter_complex(const char *opt, const char *arg)
4824 filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
4825 &nb_filtergraphs, nb_filtergraphs + 1);
4826 if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
4827 return AVERROR(ENOMEM);
4828 filtergraphs[nb_filtergraphs - 1]->index = nb_filtergraphs - 1;
4829 filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
4833 #define OFFSET(x) offsetof(OptionsContext, x)
4834 static const OptionDef options[] = {
4836 #include "cmdutils_common_opts.h"
4837 { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
4838 { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
4839 { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
4840 { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4841 { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
4842 { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
4843 { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
4844 { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
4845 "outfile[,metadata]:infile[,metadata]" },
4846 { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
4847 { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
4848 { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
4849 { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
4850 { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
4851 { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
4852 { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
4853 { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
4854 { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
4855 "add timings for benchmarking" },
4856 { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
4857 { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
4858 "dump each input packet" },
4859 { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
4860 "when dumping packets, also dump the payload" },
4861 { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
4862 { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
4863 { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
4864 { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
4865 { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
4866 { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)©_ts}, "copy timestamps" },
4867 { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)©_tb}, "copy input stream time base when stream copying" },
4868 { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
4869 { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
4870 { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
4871 { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
4872 { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
4873 { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
4874 { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4875 { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
4876 { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
4877 { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
4878 { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
4879 { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
4880 { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
4881 { "cpuflags", HAS_ARG | OPT_EXPERT, {(void*)opt_cpuflags}, "set CPU flags mask", "mask" },
4884 { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
4885 { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4886 { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
4887 { "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" },
4888 { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
4889 { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
4890 { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4891 { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
4892 { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4893 { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
4894 "use same quantizer as source (implies VBR)" },
4895 { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
4896 { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
4897 { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
4898 "this option is deprecated, use the yadif filter instead" },
4899 { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
4900 { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
4901 { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
4902 { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
4903 { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
4904 { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
4905 { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4906 { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4907 { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4908 { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
4909 { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
4910 { "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" },
4913 { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
4914 { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
4915 { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
4916 { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
4917 { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
4918 { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4919 { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4920 { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4921 { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
4922 { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
4923 { "af", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_filters}, "audio filters", "filter list" },
4925 /* subtitle options */
4926 { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
4927 { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4928 { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
4931 { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
4934 { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
4935 { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
4937 { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
4939 /* data codec support */
4940 { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
4942 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4946 int main(int argc, char **argv)
4948 OptionsContext o = { 0 };
4953 av_log_set_flags(AV_LOG_SKIP_REPEATED);
4954 parse_loglevel(argc, argv, options);
4956 avcodec_register_all();
4958 avdevice_register_all();
4960 avfilter_register_all();
4962 avformat_network_init();
4966 parse_cpuflags(argc, argv, options);
4969 parse_options(&o, argc, argv, options, opt_output_file);
4971 if (nb_output_files <= 0 && nb_input_files == 0) {
4973 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
4977 /* file converter / grab */
4978 if (nb_output_files <= 0) {
4979 fprintf(stderr, "At least one output file must be specified\n");
4983 if (nb_input_files == 0) {
4984 av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
4989 if (transcode() < 0)
4991 ti = getutime() - ti;
4993 int maxrss = getmaxrss() / 1024;
4994 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);