2 * avconv filter configuration
4 * This file is part of Libav.
6 * Libav is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libav is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with Libav; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavfilter/avfilter.h"
27 #include "libavresample/avresample.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/channel_layout.h"
32 #include "libavutil/display.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/pixfmt.h"
36 #include "libavutil/samplefmt.h"
38 /* Define a function for building a string containing a list of
40 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name) \
41 static char *choose_ ## var ## s(OutputStream *ost) \
43 if (ost->enc_ctx->var != none) { \
44 get_name(ost->enc_ctx->var); \
45 return av_strdup(name); \
46 } else if (ost->enc && ost->enc->supported_list) { \
48 AVIOContext *s = NULL; \
52 if (avio_open_dyn_buf(&s) < 0) \
55 for (p = ost->enc->supported_list; *p != none; p++) { \
57 avio_printf(s, "%s|", name); \
59 len = avio_close_dyn_buf(s, &ret); \
66 DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
69 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
70 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
72 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
75 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
78 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
80 FilterGraph *fg = av_mallocz(sizeof(*fg));
84 fg->index = nb_filtergraphs;
86 GROW_ARRAY(fg->outputs, fg->nb_outputs);
87 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
89 fg->outputs[0]->ost = ost;
90 fg->outputs[0]->graph = fg;
92 ost->filter = fg->outputs[0];
94 GROW_ARRAY(fg->inputs, fg->nb_inputs);
95 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
97 fg->inputs[0]->ist = ist;
98 fg->inputs[0]->graph = fg;
100 GROW_ARRAY(ist->filters, ist->nb_filters);
101 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
103 GROW_ARRAY(filtergraphs, nb_filtergraphs);
104 filtergraphs[nb_filtergraphs - 1] = fg;
109 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
111 InputStream *ist = NULL;
112 enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
115 // TODO: support other filter types
116 if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
117 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
126 int file_idx = strtol(in->name, &p, 0);
128 if (file_idx < 0 || file_idx >= nb_input_files) {
129 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
130 file_idx, fg->graph_desc);
133 s = input_files[file_idx]->ctx;
135 for (i = 0; i < s->nb_streams; i++) {
136 if (s->streams[i]->codec->codec_type != type)
138 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
144 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
145 "matches no streams.\n", p, fg->graph_desc);
148 ist = input_streams[input_files[file_idx]->ist_index + st->index];
150 /* find the first unused stream of corresponding type */
151 for (i = 0; i < nb_input_streams; i++) {
152 ist = input_streams[i];
153 if (ist->dec_ctx->codec_type == type && ist->discard)
156 if (i == nb_input_streams) {
157 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
158 "unlabeled input pad %d on filter %s\n", in->pad_idx,
159 in->filter_ctx->name);
166 ist->decoding_needed = 1;
167 ist->st->discard = AVDISCARD_NONE;
169 GROW_ARRAY(fg->inputs, fg->nb_inputs);
170 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
172 fg->inputs[fg->nb_inputs - 1]->ist = ist;
173 fg->inputs[fg->nb_inputs - 1]->graph = fg;
175 GROW_ARRAY(ist->filters, ist->nb_filters);
176 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
179 static int insert_trim(int64_t start_time, int64_t duration,
180 AVFilterContext **last_filter, int *pad_idx,
181 const char *filter_name)
183 AVFilterGraph *graph = (*last_filter)->graph;
184 AVFilterContext *ctx;
185 const AVFilter *trim;
186 enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
187 const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
190 if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
193 trim = avfilter_get_by_name(name);
195 av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
196 "recording time.\n", name);
197 return AVERROR_FILTER_NOT_FOUND;
200 ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
202 return AVERROR(ENOMEM);
204 if (duration != INT64_MAX) {
205 ret = av_opt_set_double(ctx, "duration", (double)duration / 1e6,
206 AV_OPT_SEARCH_CHILDREN);
208 if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
209 ret = av_opt_set_double(ctx, "start", (double)start_time / 1e6,
210 AV_OPT_SEARCH_CHILDREN);
213 av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
217 ret = avfilter_init_str(ctx, NULL);
221 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
230 static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
231 const char *filter_name, const char *args)
233 AVFilterGraph *graph = (*last_filter)->graph;
234 AVFilterContext *ctx;
237 ret = avfilter_graph_create_filter(&ctx,
238 avfilter_get_by_name(filter_name),
239 filter_name, args, NULL, graph);
243 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
252 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
255 OutputStream *ost = ofilter->ost;
256 OutputFile *of = output_files[ost->file_index];
257 AVCodecContext *codec = ost->enc_ctx;
258 AVFilterContext *last_filter = out->filter_ctx;
259 int pad_idx = out->pad_idx;
263 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
264 ret = avfilter_graph_create_filter(&ofilter->filter,
265 avfilter_get_by_name("buffersink"),
266 name, NULL, NULL, fg->graph);
270 if (codec->width || codec->height) {
272 AVFilterContext *filter;
274 snprintf(args, sizeof(args), "%d:%d:0x%X",
277 (unsigned)ost->sws_flags);
278 snprintf(name, sizeof(name), "scaler for output stream %d:%d",
279 ost->file_index, ost->index);
280 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
281 name, args, NULL, fg->graph)) < 0)
283 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
286 last_filter = filter;
290 if ((pix_fmts = choose_pix_fmts(ost))) {
291 AVFilterContext *filter;
292 snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
293 ost->file_index, ost->index);
294 ret = avfilter_graph_create_filter(&filter,
295 avfilter_get_by_name("format"),
296 "format", pix_fmts, NULL, fg->graph);
300 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
303 last_filter = filter;
307 if (ost->frame_rate.num) {
308 AVFilterContext *fps;
311 snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
312 ost->frame_rate.den);
313 snprintf(name, sizeof(name), "fps for output stream %d:%d",
314 ost->file_index, ost->index);
315 ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
316 name, args, NULL, fg->graph);
320 ret = avfilter_link(last_filter, pad_idx, fps, 0);
327 snprintf(name, sizeof(name), "trim for output stream %d:%d",
328 ost->file_index, ost->index);
329 ret = insert_trim(of->start_time, of->recording_time,
330 &last_filter, &pad_idx, name);
335 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
341 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
343 OutputStream *ost = ofilter->ost;
344 OutputFile *of = output_files[ost->file_index];
345 AVCodecContext *codec = ost->enc_ctx;
346 AVFilterContext *last_filter = out->filter_ctx;
347 int pad_idx = out->pad_idx;
348 char *sample_fmts, *sample_rates, *channel_layouts;
353 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
354 ret = avfilter_graph_create_filter(&ofilter->filter,
355 avfilter_get_by_name("abuffersink"),
356 name, NULL, NULL, fg->graph);
360 if (codec->channels && !codec->channel_layout)
361 codec->channel_layout = av_get_default_channel_layout(codec->channels);
363 sample_fmts = choose_sample_fmts(ost);
364 sample_rates = choose_sample_rates(ost);
365 channel_layouts = choose_channel_layouts(ost);
366 if (sample_fmts || sample_rates || channel_layouts) {
367 AVFilterContext *format;
372 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
375 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
378 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
382 av_freep(&sample_fmts);
383 av_freep(&sample_rates);
384 av_freep(&channel_layouts);
386 snprintf(name, sizeof(name), "audio format for output stream %d:%d",
387 ost->file_index, ost->index);
388 ret = avfilter_graph_create_filter(&format,
389 avfilter_get_by_name("aformat"),
390 name, args, NULL, fg->graph);
394 ret = avfilter_link(last_filter, pad_idx, format, 0);
398 last_filter = format;
402 snprintf(name, sizeof(name), "trim for output stream %d:%d",
403 ost->file_index, ost->index);
404 ret = insert_trim(of->start_time, of->recording_time,
405 &last_filter, &pad_idx, name);
409 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
415 #define DESCRIBE_FILTER_LINK(f, inout, in) \
417 AVFilterContext *ctx = inout->filter_ctx; \
418 AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
419 int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs; \
422 if (avio_open_dyn_buf(&pb) < 0) \
425 avio_printf(pb, "%s", ctx->filter->name); \
427 avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
429 avio_close_dyn_buf(pb, &f->name); \
432 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
434 av_freep(&ofilter->name);
435 DESCRIBE_FILTER_LINK(ofilter, out, 0);
437 switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
438 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
439 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
440 default: av_assert0(0);
444 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
447 AVFilterContext *last_filter;
448 const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
449 InputStream *ist = ifilter->ist;
450 InputFile *f = input_files[ist->file_index];
451 AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
454 char args[255], name[255];
455 int ret, pad_idx = 0;
457 sar = ist->st->sample_aspect_ratio.num ?
458 ist->st->sample_aspect_ratio :
459 ist->dec_ctx->sample_aspect_ratio;
460 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->dec_ctx->width,
461 ist->dec_ctx->height,
462 ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->dec_ctx->pix_fmt,
463 tb.num, tb.den, sar.num, sar.den);
464 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
465 ist->file_index, ist->st->index);
467 if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
468 args, NULL, fg->graph)) < 0)
470 last_filter = ifilter->filter;
472 if (ist->autorotate) {
473 uint8_t* displaymatrix = av_stream_get_side_data(ist->st,
474 AV_PKT_DATA_DISPLAYMATRIX, NULL);
476 double rot = av_display_rotation_get((int32_t*) displaymatrix);
477 if (rot < -135 || rot > 135) {
478 ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
481 ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
482 } else if (rot < -45) {
483 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=clock");
484 } else if (rot > 45) {
485 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=cclock");
492 if (ist->framerate.num) {
493 AVFilterContext *setpts;
495 snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
496 ist->file_index, ist->st->index);
497 if ((ret = avfilter_graph_create_filter(&setpts,
498 avfilter_get_by_name("setpts"),
503 if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
506 last_filter = setpts;
509 snprintf(name, sizeof(name), "trim for input stream %d:%d",
510 ist->file_index, ist->st->index);
511 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
512 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
516 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
521 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
524 AVFilterContext *last_filter;
525 const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
526 InputStream *ist = ifilter->ist;
527 InputFile *f = input_files[ist->file_index];
528 char args[255], name[255];
529 int ret, pad_idx = 0;
531 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
532 ":channel_layout=0x%"PRIx64,
533 1, ist->dec_ctx->sample_rate,
534 ist->dec_ctx->sample_rate,
535 av_get_sample_fmt_name(ist->dec_ctx->sample_fmt),
536 ist->dec_ctx->channel_layout);
537 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
538 ist->file_index, ist->st->index);
540 if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
544 last_filter = ifilter->filter;
546 if (audio_sync_method > 0) {
547 AVFilterContext *async;
550 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
551 "asyncts audio filter instead.\n");
553 if (audio_sync_method > 1)
554 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
555 "max_comp=%d:", audio_sync_method);
556 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
557 audio_drift_threshold);
559 snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
560 fg->index, ist->file_index, ist->st->index);
561 ret = avfilter_graph_create_filter(&async,
562 avfilter_get_by_name("asyncts"),
563 name, args, NULL, fg->graph);
567 ret = avfilter_link(last_filter, 0, async, 0);
573 if (audio_volume != 256) {
574 AVFilterContext *volume;
576 av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
577 "audio filter instead.\n");
579 snprintf(args, sizeof(args), "volume=%f", audio_volume / 256.0);
581 snprintf(name, sizeof(name), "graph %d volume for input stream %d:%d",
582 fg->index, ist->file_index, ist->st->index);
583 ret = avfilter_graph_create_filter(&volume,
584 avfilter_get_by_name("volume"),
585 name, args, NULL, fg->graph);
589 ret = avfilter_link(last_filter, 0, volume, 0);
593 last_filter = volume;
596 snprintf(name, sizeof(name), "trim for input stream %d:%d",
597 ist->file_index, ist->st->index);
598 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
599 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
603 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
609 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
612 av_freep(&ifilter->name);
613 DESCRIBE_FILTER_LINK(ifilter, in, 1);
615 switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
616 case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
617 case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
618 default: av_assert0(0);
622 int configure_filtergraph(FilterGraph *fg)
624 AVFilterInOut *inputs, *outputs, *cur;
625 int ret, i, init = !fg->graph, simple = !fg->graph_desc;
626 const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
629 avfilter_graph_free(&fg->graph);
630 if (!(fg->graph = avfilter_graph_alloc()))
631 return AVERROR(ENOMEM);
634 OutputStream *ost = fg->outputs[0]->ost;
636 AVDictionaryEntry *e = NULL;
638 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
639 fg->graph->scale_sws_opts = av_strdup(args);
642 while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
643 AV_DICT_IGNORE_SUFFIX))) {
644 av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
647 args[strlen(args) - 1] = '\0';
648 fg->graph->resample_lavr_opts = av_strdup(args);
651 if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
654 if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
655 av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
656 "exactly one input and output.\n", graph_desc);
657 return AVERROR(EINVAL);
660 for (cur = inputs; !simple && init && cur; cur = cur->next)
661 init_input_filter(fg, cur);
663 for (cur = inputs, i = 0; cur; cur = cur->next, i++)
664 if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
666 avfilter_inout_free(&inputs);
668 if (!init || simple) {
669 /* we already know the mappings between lavfi outputs and output streams,
670 * so we can finish the setup */
671 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
672 configure_output_filter(fg, fg->outputs[i], cur);
673 avfilter_inout_free(&outputs);
675 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
678 /* wait until output mappings are processed */
679 for (cur = outputs; cur;) {
680 GROW_ARRAY(fg->outputs, fg->nb_outputs);
681 if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
683 fg->outputs[fg->nb_outputs - 1]->graph = fg;
684 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
686 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
693 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
696 for (i = 0; i < fg->nb_inputs; i++)
697 if (fg->inputs[i]->ist == ist)