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"
26 #include "libavfilter/buffersrc.h"
28 #include "libavresample/avresample.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/display.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/pixdesc.h"
36 #include "libavutil/pixfmt.h"
37 #include "libavutil/samplefmt.h"
39 /* Define a function for building a string containing a list of
41 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name) \
42 static char *choose_ ## var ## s(OutputStream *ost) \
44 if (ost->enc_ctx->var != none) { \
45 get_name(ost->enc_ctx->var); \
46 return av_strdup(name); \
47 } else if (ost->enc && ost->enc->supported_list) { \
49 AVIOContext *s = NULL; \
53 if (avio_open_dyn_buf(&s) < 0) \
56 for (p = ost->enc->supported_list; *p != none; p++) { \
58 avio_printf(s, "%s|", name); \
60 len = avio_close_dyn_buf(s, &ret); \
67 DEF_CHOOSE_FORMAT(enum AVPixelFormat, pix_fmt, pix_fmts, AV_PIX_FMT_NONE,
70 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
71 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME)
73 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
76 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
79 FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
81 FilterGraph *fg = av_mallocz(sizeof(*fg));
85 fg->index = nb_filtergraphs;
87 GROW_ARRAY(fg->outputs, fg->nb_outputs);
88 if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
90 fg->outputs[0]->ost = ost;
91 fg->outputs[0]->graph = fg;
93 ost->filter = fg->outputs[0];
95 GROW_ARRAY(fg->inputs, fg->nb_inputs);
96 if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
98 fg->inputs[0]->ist = ist;
99 fg->inputs[0]->graph = fg;
101 GROW_ARRAY(ist->filters, ist->nb_filters);
102 ist->filters[ist->nb_filters - 1] = fg->inputs[0];
104 GROW_ARRAY(filtergraphs, nb_filtergraphs);
105 filtergraphs[nb_filtergraphs - 1] = fg;
110 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
112 InputStream *ist = NULL;
113 enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
116 // TODO: support other filter types
117 if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
118 av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
127 int file_idx = strtol(in->name, &p, 0);
129 if (file_idx < 0 || file_idx >= nb_input_files) {
130 av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
131 file_idx, fg->graph_desc);
134 s = input_files[file_idx]->ctx;
136 for (i = 0; i < s->nb_streams; i++) {
137 if (s->streams[i]->codecpar->codec_type != type)
139 if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
145 av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
146 "matches no streams.\n", p, fg->graph_desc);
149 ist = input_streams[input_files[file_idx]->ist_index + st->index];
151 /* find the first unused stream of corresponding type */
152 for (i = 0; i < nb_input_streams; i++) {
153 ist = input_streams[i];
154 if (ist->dec_ctx->codec_type == type && ist->discard)
157 if (i == nb_input_streams) {
158 av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
159 "unlabeled input pad %d on filter %s\n", in->pad_idx,
160 in->filter_ctx->name);
167 ist->decoding_needed = 1;
168 ist->st->discard = AVDISCARD_NONE;
170 GROW_ARRAY(fg->inputs, fg->nb_inputs);
171 if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
173 fg->inputs[fg->nb_inputs - 1]->ist = ist;
174 fg->inputs[fg->nb_inputs - 1]->graph = fg;
176 GROW_ARRAY(ist->filters, ist->nb_filters);
177 ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
180 int init_complex_filtergraph(FilterGraph *fg)
182 AVFilterInOut *inputs, *outputs, *cur;
183 AVFilterGraph *graph;
186 /* this graph is only used for determining the kinds of inputs
187 * and outputs we have, and is discarded on exit from this function */
188 graph = avfilter_graph_alloc();
190 return AVERROR(ENOMEM);
192 ret = avfilter_graph_parse2(graph, fg->graph_desc, &inputs, &outputs);
196 for (cur = inputs; cur; cur = cur->next)
197 init_input_filter(fg, cur);
199 for (cur = outputs; cur;) {
200 GROW_ARRAY(fg->outputs, fg->nb_outputs);
201 fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]));
202 if (!fg->outputs[fg->nb_outputs - 1])
205 fg->outputs[fg->nb_outputs - 1]->graph = fg;
206 fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
207 fg->outputs[fg->nb_outputs - 1]->type = avfilter_pad_get_type(cur->filter_ctx->output_pads,
210 fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
214 avfilter_inout_free(&inputs);
215 avfilter_graph_free(&graph);
219 static int insert_trim(int64_t start_time, int64_t duration,
220 AVFilterContext **last_filter, int *pad_idx,
221 const char *filter_name)
223 AVFilterGraph *graph = (*last_filter)->graph;
224 AVFilterContext *ctx;
225 const AVFilter *trim;
226 enum AVMediaType type = avfilter_pad_get_type((*last_filter)->output_pads, *pad_idx);
227 const char *name = (type == AVMEDIA_TYPE_VIDEO) ? "trim" : "atrim";
230 if (duration == INT64_MAX && start_time == AV_NOPTS_VALUE)
233 trim = avfilter_get_by_name(name);
235 av_log(NULL, AV_LOG_ERROR, "%s filter not present, cannot limit "
236 "recording time.\n", name);
237 return AVERROR_FILTER_NOT_FOUND;
240 ctx = avfilter_graph_alloc_filter(graph, trim, filter_name);
242 return AVERROR(ENOMEM);
244 if (duration != INT64_MAX) {
245 ret = av_opt_set_double(ctx, "duration", (double)duration / 1e6,
246 AV_OPT_SEARCH_CHILDREN);
248 if (ret >= 0 && start_time != AV_NOPTS_VALUE) {
249 ret = av_opt_set_double(ctx, "start", (double)start_time / 1e6,
250 AV_OPT_SEARCH_CHILDREN);
253 av_log(ctx, AV_LOG_ERROR, "Error configuring the %s filter", name);
257 ret = avfilter_init_str(ctx, NULL);
261 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
270 static int insert_filter(AVFilterContext **last_filter, int *pad_idx,
271 const char *filter_name, const char *args)
273 AVFilterGraph *graph = (*last_filter)->graph;
274 AVFilterContext *ctx;
277 ret = avfilter_graph_create_filter(&ctx,
278 avfilter_get_by_name(filter_name),
279 filter_name, args, NULL, graph);
283 ret = avfilter_link(*last_filter, *pad_idx, ctx, 0);
292 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
295 OutputStream *ost = ofilter->ost;
296 OutputFile *of = output_files[ost->file_index];
297 AVCodecContext *codec = ost->enc_ctx;
298 AVFilterContext *last_filter = out->filter_ctx;
299 int pad_idx = out->pad_idx;
303 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
304 ret = avfilter_graph_create_filter(&ofilter->filter,
305 avfilter_get_by_name("buffersink"),
306 name, NULL, NULL, fg->graph);
310 if (!hw_device_ctx && (codec->width || codec->height)) {
312 AVFilterContext *filter;
314 snprintf(args, sizeof(args), "%d:%d:0x%X",
317 (unsigned)ost->sws_flags);
318 snprintf(name, sizeof(name), "scaler for output stream %d:%d",
319 ost->file_index, ost->index);
320 if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
321 name, args, NULL, fg->graph)) < 0)
323 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
326 last_filter = filter;
330 if ((pix_fmts = choose_pix_fmts(ost))) {
331 AVFilterContext *filter;
332 snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
333 ost->file_index, ost->index);
334 ret = avfilter_graph_create_filter(&filter,
335 avfilter_get_by_name("format"),
336 "format", pix_fmts, NULL, fg->graph);
340 if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
343 last_filter = filter;
347 if (ost->frame_rate.num) {
348 AVFilterContext *fps;
351 snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
352 ost->frame_rate.den);
353 snprintf(name, sizeof(name), "fps for output stream %d:%d",
354 ost->file_index, ost->index);
355 ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
356 name, args, NULL, fg->graph);
360 ret = avfilter_link(last_filter, pad_idx, fps, 0);
367 snprintf(name, sizeof(name), "trim for output stream %d:%d",
368 ost->file_index, ost->index);
369 ret = insert_trim(of->start_time, of->recording_time,
370 &last_filter, &pad_idx, name);
375 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
381 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
383 OutputStream *ost = ofilter->ost;
384 OutputFile *of = output_files[ost->file_index];
385 AVCodecContext *codec = ost->enc_ctx;
386 AVFilterContext *last_filter = out->filter_ctx;
387 int pad_idx = out->pad_idx;
388 char *sample_fmts, *sample_rates, *channel_layouts;
393 snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
394 ret = avfilter_graph_create_filter(&ofilter->filter,
395 avfilter_get_by_name("abuffersink"),
396 name, NULL, NULL, fg->graph);
400 if (codec->channels && !codec->channel_layout)
401 codec->channel_layout = av_get_default_channel_layout(codec->channels);
403 sample_fmts = choose_sample_fmts(ost);
404 sample_rates = choose_sample_rates(ost);
405 channel_layouts = choose_channel_layouts(ost);
406 if (sample_fmts || sample_rates || channel_layouts) {
407 AVFilterContext *format;
412 len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
415 len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
418 len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
422 av_freep(&sample_fmts);
423 av_freep(&sample_rates);
424 av_freep(&channel_layouts);
426 snprintf(name, sizeof(name), "audio format for output stream %d:%d",
427 ost->file_index, ost->index);
428 ret = avfilter_graph_create_filter(&format,
429 avfilter_get_by_name("aformat"),
430 name, args, NULL, fg->graph);
434 ret = avfilter_link(last_filter, pad_idx, format, 0);
438 last_filter = format;
442 snprintf(name, sizeof(name), "trim for output stream %d:%d",
443 ost->file_index, ost->index);
444 ret = insert_trim(of->start_time, of->recording_time,
445 &last_filter, &pad_idx, name);
449 if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
455 #define DESCRIBE_FILTER_LINK(f, inout, in) \
457 AVFilterContext *ctx = inout->filter_ctx; \
458 AVFilterPad *pads = in ? ctx->input_pads : ctx->output_pads; \
459 int nb_pads = in ? ctx->nb_inputs : ctx->nb_outputs; \
462 if (avio_open_dyn_buf(&pb) < 0) \
465 avio_printf(pb, "%s", ctx->filter->name); \
467 avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
469 avio_close_dyn_buf(pb, &f->name); \
472 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
474 av_freep(&ofilter->name);
475 DESCRIBE_FILTER_LINK(ofilter, out, 0);
477 switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
478 case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
479 case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
480 default: av_assert0(0);
484 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
487 AVFilterContext *last_filter;
488 const AVFilter *buffer_filt = avfilter_get_by_name("buffer");
489 InputStream *ist = ifilter->ist;
490 InputFile *f = input_files[ist->file_index];
491 AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
493 AVBufferSrcParameters *par;
495 int ret, pad_idx = 0;
497 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
498 ist->file_index, ist->st->index);
500 ifilter->filter = avfilter_graph_alloc_filter(fg->graph, buffer_filt, name);
501 if (!ifilter->filter)
502 return AVERROR(ENOMEM);
504 par = av_buffersrc_parameters_alloc();
506 return AVERROR(ENOMEM);
508 par->sample_aspect_ratio = ist->st->sample_aspect_ratio.num ?
509 ist->st->sample_aspect_ratio :
510 ist->dec_ctx->sample_aspect_ratio;
511 par->width = ist->dec_ctx->width;
512 par->height = ist->dec_ctx->height;
513 par->format = ist->hwaccel_retrieve_data ?
514 ist->hwaccel_retrieved_pix_fmt : ist->dec_ctx->pix_fmt;
516 par->hw_frames_ctx = ist->hw_frames_ctx;
518 ret = av_buffersrc_parameters_set(ifilter->filter, par);
523 ret = avfilter_init_str(ifilter->filter, NULL);
527 last_filter = ifilter->filter;
529 if (ist->autorotate) {
530 uint8_t* displaymatrix = av_stream_get_side_data(ist->st,
531 AV_PKT_DATA_DISPLAYMATRIX, NULL);
533 double rot = av_display_rotation_get((int32_t*) displaymatrix);
534 if (rot < -135 || rot > 135) {
535 ret = insert_filter(&last_filter, &pad_idx, "vflip", NULL);
538 ret = insert_filter(&last_filter, &pad_idx, "hflip", NULL);
539 } else if (rot < -45) {
540 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=clock");
541 } else if (rot > 45) {
542 ret = insert_filter(&last_filter, &pad_idx, "transpose", "dir=cclock");
549 if (ist->framerate.num) {
550 AVFilterContext *setpts;
552 snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
553 ist->file_index, ist->st->index);
554 if ((ret = avfilter_graph_create_filter(&setpts,
555 avfilter_get_by_name("setpts"),
560 if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)
563 last_filter = setpts;
566 snprintf(name, sizeof(name), "trim for input stream %d:%d",
567 ist->file_index, ist->st->index);
568 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
569 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
573 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
578 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
581 AVFilterContext *last_filter;
582 const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");
583 InputStream *ist = ifilter->ist;
584 InputFile *f = input_files[ist->file_index];
585 AVBufferSrcParameters *par;
586 char args[255], name[255];
587 int ret, pad_idx = 0;
589 snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
590 ist->file_index, ist->st->index);
592 ifilter->filter = avfilter_graph_alloc_filter(fg->graph, abuffer_filt, name);
593 if (!ifilter->filter)
594 return AVERROR(ENOMEM);
596 par = av_buffersrc_parameters_alloc();
598 return AVERROR(ENOMEM);
600 par->time_base = (AVRational){ 1, ist->dec_ctx->sample_rate };
601 par->sample_rate = ist->dec_ctx->sample_rate;
602 par->format = ist->dec_ctx->sample_fmt;
603 par->channel_layout = ist->dec_ctx->channel_layout;
605 ret = av_buffersrc_parameters_set(ifilter->filter, par);
610 ret = avfilter_init_str(ifilter->filter, NULL);
613 last_filter = ifilter->filter;
615 if (audio_sync_method > 0) {
616 AVFilterContext *async;
619 av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
620 "asyncts audio filter instead.\n");
622 if (audio_sync_method > 1)
623 len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
624 "max_comp=%d:", audio_sync_method);
625 snprintf(args + len, sizeof(args) - len, "min_delta=%f",
626 audio_drift_threshold);
628 snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
629 fg->index, ist->file_index, ist->st->index);
630 ret = avfilter_graph_create_filter(&async,
631 avfilter_get_by_name("asyncts"),
632 name, args, NULL, fg->graph);
636 ret = avfilter_link(last_filter, 0, async, 0);
642 if (audio_volume != 256) {
643 AVFilterContext *volume;
645 av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "
646 "audio filter instead.\n");
648 snprintf(args, sizeof(args), "volume=%f", audio_volume / 256.0);
650 snprintf(name, sizeof(name), "graph %d volume for input stream %d:%d",
651 fg->index, ist->file_index, ist->st->index);
652 ret = avfilter_graph_create_filter(&volume,
653 avfilter_get_by_name("volume"),
654 name, args, NULL, fg->graph);
658 ret = avfilter_link(last_filter, 0, volume, 0);
662 last_filter = volume;
665 snprintf(name, sizeof(name), "trim for input stream %d:%d",
666 ist->file_index, ist->st->index);
667 ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?
668 AV_NOPTS_VALUE : 0, f->recording_time, &last_filter, &pad_idx, name);
672 if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)
678 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
681 av_freep(&ifilter->name);
682 DESCRIBE_FILTER_LINK(ifilter, in, 1);
684 switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
685 case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
686 case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
687 default: av_assert0(0);
691 int configure_filtergraph(FilterGraph *fg)
693 AVFilterInOut *inputs, *outputs, *cur;
694 int ret, i, simple = !fg->graph_desc;
695 const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
698 avfilter_graph_free(&fg->graph);
699 if (!(fg->graph = avfilter_graph_alloc()))
700 return AVERROR(ENOMEM);
703 OutputStream *ost = fg->outputs[0]->ost;
705 AVDictionaryEntry *e = NULL;
707 snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
708 fg->graph->scale_sws_opts = av_strdup(args);
711 while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,
712 AV_DICT_IGNORE_SUFFIX))) {
713 av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);
716 args[strlen(args) - 1] = '\0';
717 fg->graph->resample_lavr_opts = av_strdup(args);
720 if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
724 for (i = 0; i < fg->graph->nb_filters; i++) {
725 fg->graph->filters[i]->hw_device_ctx = av_buffer_ref(hw_device_ctx);
729 if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
730 av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
731 "exactly one input and output.\n", graph_desc);
732 return AVERROR(EINVAL);
735 for (cur = inputs, i = 0; cur; cur = cur->next, i++)
736 if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
738 avfilter_inout_free(&inputs);
740 for (cur = outputs, i = 0; cur; cur = cur->next, i++) {
741 OutputFilter *ofilter = fg->outputs[i];
743 configure_output_filter(fg, ofilter, cur);
746 avfilter_inout_free(&outputs);
748 if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
754 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
757 for (i = 0; i < fg->nb_inputs; i++)
758 if (fg->inputs[i]->ist == ist)