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 int init_complex_filtergraph(FilterGraph *fg)
181 AVFilterInOut *inputs, *outputs, *cur;
182 AVFilterGraph *graph;
185 /* this graph is only used for determining the kinds of inputs
186 * and outputs we have, and is discarded on exit from this function */
187 graph = avfilter_graph_alloc();
189 return AVERROR(ENOMEM);
191 ret = avfilter_graph_parse2(graph, fg->graph_desc, &inputs, &outputs);
195 for (cur = inputs; cur; cur = cur->next)
196 init_input_filter(fg, cur);
198 for (cur = outputs; cur;) {
199 GROW_ARRAY(fg->outputs, fg->nb_outputs);
200 fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]));
201 if (!fg->outputs[fg->nb_outputs - 1])
204 fg->outputs[fg->nb_outputs - 1]->graph = fg;
205 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
206 fg->outputs[fg->nb_outputs - 1]->type = avfilter_pad_get_type(cur->filter_ctx->output_pads,
209 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
213 avfilter_inout_free(&inputs);
214 avfilter_graph_free(&graph);
218 static int insert_trim(int64_t start_time, int64_t duration,
219 AVFilterContext **last_filter, int *pad_idx,
220 const char *filter_name)
222 AVFilterGraph *graph = (*last_filter)->graph;
223 AVFilterContext *ctx;
224 const AVFilter *trim;
225 enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
226 const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
229 if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
232 trim = avfilter_get_by_name(name);
234 av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
235 "recording time.\n", name);
236 return AVERROR_FILTER_NOT_FOUND;
239 ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
241 return AVERROR(ENOMEM);
243 if (duration != INT64_MAX) {
244 ret = av_opt_set_double(ctx, "duration", (double)duration / 1e6,
245 AV_OPT_SEARCH_CHILDREN);
247 if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
248 ret = av_opt_set_double(ctx, "start", (double)start_time / 1e6,
249 AV_OPT_SEARCH_CHILDREN);
252 av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
256 ret = avfilter_init_str(ctx, NULL);
260 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
269 static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
270 const char *filter_name, const char *args)
272 AVFilterGraph *graph = (*last_filter)->graph;
273 AVFilterContext *ctx;
276 ret = avfilter_graph_create_filter(&ctx,
277 avfilter_get_by_name(filter_name),
278 filter_name, args, NULL, graph);
282 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
291 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
294 OutputStream *ost = ofilter->ost;
295 OutputFile *of = output_files[ost->file_index];
296 AVCodecContext *codec = ost->enc_ctx;
297 AVFilterContext *last_filter = out->filter_ctx;
298 int pad_idx = out->pad_idx;
302 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
303 ret = avfilter_graph_create_filter(&ofilter->filter,
304 avfilter_get_by_name("buffersink"),
305 name, NULL, NULL, fg->graph);
309 if (codec->width || codec->height) {
311 AVFilterContext *filter;
313 snprintf(args, sizeof(args), "%d:%d:0x%X",
316 (unsigned)ost->sws_flags);
317 snprintf(name, sizeof(name), "scaler for output stream %d:%d",
318 ost->file_index, ost->index);
319 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
320 name, args, NULL, fg->graph)) < 0)
322 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
325 last_filter = filter;
329 if ((pix_fmts = choose_pix_fmts(ost))) {
330 AVFilterContext *filter;
331 snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
332 ost->file_index, ost->index);
333 ret = avfilter_graph_create_filter(&filter,
334 avfilter_get_by_name("format"),
335 "format", pix_fmts, NULL, fg->graph);
339 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
342 last_filter = filter;
346 if (ost->frame_rate.num) {
347 AVFilterContext *fps;
350 snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
351 ost->frame_rate.den);
352 snprintf(name, sizeof(name), "fps for output stream %d:%d",
353 ost->file_index, ost->index);
354 ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
355 name, args, NULL, fg->graph);
359 ret = avfilter_link(last_filter, pad_idx, fps, 0);
366 snprintf(name, sizeof(name), "trim for output stream %d:%d",
367 ost->file_index, ost->index);
368 ret = insert_trim(of->start_time, of->recording_time,
369 &last_filter, &pad_idx, name);
374 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
380 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
382 OutputStream *ost = ofilter->ost;
383 OutputFile *of = output_files[ost->file_index];
384 AVCodecContext *codec = ost->enc_ctx;
385 AVFilterContext *last_filter = out->filter_ctx;
386 int pad_idx = out->pad_idx;
387 char *sample_fmts, *sample_rates, *channel_layouts;
392 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
393 ret = avfilter_graph_create_filter(&ofilter->filter,
394 avfilter_get_by_name("abuffersink"),
395 name, NULL, NULL, fg->graph);
399 if (codec->channels && !codec->channel_layout)
400 codec->channel_layout = av_get_default_channel_layout(codec->channels);
402 sample_fmts = choose_sample_fmts(ost);
403 sample_rates = choose_sample_rates(ost);
404 channel_layouts = choose_channel_layouts(ost);
405 if (sample_fmts || sample_rates || channel_layouts) {
406 AVFilterContext *format;
411 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
414 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
417 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
421 av_freep(&sample_fmts);
422 av_freep(&sample_rates);
423 av_freep(&channel_layouts);
425 snprintf(name, sizeof(name), "audio format for output stream %d:%d",
426 ost->file_index, ost->index);
427 ret = avfilter_graph_create_filter(&format,
428 avfilter_get_by_name("aformat"),
429 name, args, NULL, fg->graph);
433 ret = avfilter_link(last_filter, pad_idx, format, 0);
437 last_filter = format;
441 snprintf(name, sizeof(name), "trim for output stream %d:%d",
442 ost->file_index, ost->index);
443 ret = insert_trim(of->start_time, of->recording_time,
444 &last_filter, &pad_idx, name);
448 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
454 #define DESCRIBE_FILTER_LINK(f, inout, in) \
456 AVFilterContext *ctx = inout->filter_ctx; \
457 AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
458 int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs; \
461 if (avio_open_dyn_buf(&pb) < 0) \
464 avio_printf(pb, "%s", ctx->filter->name); \
466 avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
468 avio_close_dyn_buf(pb, &f->name); \
471 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
473 av_freep(&ofilter->name);
474 DESCRIBE_FILTER_LINK(ofilter, out, 0);
476 switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
477 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
478 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
479 default: av_assert0(0);
483 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
486 AVFilterContext *last_filter;
487 const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
488 InputStream *ist = ifilter->ist;
489 InputFile *f = input_files[ist->file_index];
490 AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
493 char args[255], name[255];
494 int ret, pad_idx = 0;
496 sar = ist->st->sample_aspect_ratio.num ?
497 ist->st->sample_aspect_ratio :
498 ist->dec_ctx->sample_aspect_ratio;
499 snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->dec_ctx->width,
500 ist->dec_ctx->height,
501 ist->hwaccel_retrieve_data ? ist->hwaccel_retrieved_pix_fmt : ist->dec_ctx->pix_fmt,
502 tb.num, tb.den, sar.num, sar.den);
503 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
504 ist->file_index, ist->st->index);
506 if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,
507 args, NULL, fg->graph)) < 0)
509 last_filter = ifilter->filter;
511 if (ist->autorotate) {
512 uint8_t* displaymatrix = av_stream_get_side_data(ist->st,
513 AV_PKT_DATA_DISPLAYMATRIX, NULL);
515 double rot = av_display_rotation_get((int32_t*) displaymatrix);
516 if (rot < -135 || rot > 135) {
517 ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
520 ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
521 } else if (rot < -45) {
522 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=clock");
523 } else if (rot > 45) {
524 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=cclock");
531 if (ist->framerate.num) {
532 AVFilterContext *setpts;
534 snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
535 ist->file_index, ist->st->index);
536 if ((ret = avfilter_graph_create_filter(&setpts,
537 avfilter_get_by_name("setpts"),
542 if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
545 last_filter = setpts;
548 snprintf(name, sizeof(name), "trim for input stream %d:%d",
549 ist->file_index, ist->st->index);
550 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
551 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
555 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
560 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
563 AVFilterContext *last_filter;
564 const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
565 InputStream *ist = ifilter->ist;
566 InputFile *f = input_files[ist->file_index];
567 char args[255], name[255];
568 int ret, pad_idx = 0;
570 snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
571 ":channel_layout=0x%"PRIx64,
572 1, ist->dec_ctx->sample_rate,
573 ist->dec_ctx->sample_rate,
574 av_get_sample_fmt_name(ist->dec_ctx->sample_fmt),
575 ist->dec_ctx->channel_layout);
576 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
577 ist->file_index, ist->st->index);
579 if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,
583 last_filter = ifilter->filter;
585 if (audio_sync_method > 0) {
586 AVFilterContext *async;
589 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
590 "asyncts audio filter instead.\n");
592 if (audio_sync_method > 1)
593 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
594 "max_comp=%d:", audio_sync_method);
595 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
596 audio_drift_threshold);
598 snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
599 fg->index, ist->file_index, ist->st->index);
600 ret = avfilter_graph_create_filter(&async,
601 avfilter_get_by_name("asyncts"),
602 name, args, NULL, fg->graph);
606 ret = avfilter_link(last_filter, 0, async, 0);
612 if (audio_volume != 256) {
613 AVFilterContext *volume;
615 av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
616 "audio filter instead.\n");
618 snprintf(args, sizeof(args), "volume=%f", audio_volume / 256.0);
620 snprintf(name, sizeof(name), "graph %d volume for input stream %d:%d",
621 fg->index, ist->file_index, ist->st->index);
622 ret = avfilter_graph_create_filter(&volume,
623 avfilter_get_by_name("volume"),
624 name, args, NULL, fg->graph);
628 ret = avfilter_link(last_filter, 0, volume, 0);
632 last_filter = volume;
635 snprintf(name, sizeof(name), "trim for input stream %d:%d",
636 ist->file_index, ist->st->index);
637 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
638 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
642 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
648 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
651 av_freep(&ifilter->name);
652 DESCRIBE_FILTER_LINK(ifilter, in, 1);
654 switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
655 case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
656 case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
657 default: av_assert0(0);
661 int configure_filtergraph(FilterGraph *fg)
663 AVFilterInOut *inputs, *outputs, *cur;
664 int ret, i, simple = !fg->graph_desc;
665 const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
668 avfilter_graph_free(&fg->graph);
669 if (!(fg->graph = avfilter_graph_alloc()))
670 return AVERROR(ENOMEM);
673 OutputStream *ost = fg->outputs[0]->ost;
675 AVDictionaryEntry *e = NULL;
677 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
678 fg->graph->scale_sws_opts = av_strdup(args);
681 while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
682 AV_DICT_IGNORE_SUFFIX))) {
683 av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
686 args[strlen(args) - 1] = '\0';
687 fg->graph->resample_lavr_opts = av_strdup(args);
690 if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
693 if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
694 av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
695 "exactly one input and output.\n", graph_desc);
696 return AVERROR(EINVAL);
699 for (cur = inputs, i = 0; cur; cur = cur->next, i++)
700 if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
702 avfilter_inout_free(&inputs);
704 for (cur = outputs, i = 0; cur; cur = cur->next, i++)
705 configure_output_filter(fg, fg->outputs[i], cur);
706 avfilter_inout_free(&outputs);
708 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
714 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
717 for (i = 0; i < fg->nb_inputs; i++)
718 if (fg->inputs[i]->ist == ist)