3 * Copyright (c) 2008 Vitor Sessak
4 * Copyright (c) 2007 Bobby Bingham
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/common.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/log.h"
33 #include "libavutil/opt.h"
40 #define OFFSET(x) offsetof(AVFilterGraph, x)
41 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM
42 static const AVOption filtergraph_options[] = {
43 { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
44 { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
45 { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .flags = FLAGS, .unit = "thread_type" },
46 { "threads", "Maximum number of threads", OFFSET(nb_threads),
47 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
51 static const AVClass filtergraph_class = {
52 .class_name = "AVFilterGraph",
53 .item_name = av_default_item_name,
54 .version = LIBAVUTIL_VERSION_INT,
55 .option = filtergraph_options,
59 void ff_graph_thread_free(AVFilterGraph *graph)
63 int ff_graph_thread_init(AVFilterGraph *graph)
65 graph->thread_type = 0;
66 graph->nb_threads = 1;
71 AVFilterGraph *avfilter_graph_alloc(void)
73 AVFilterGraph *ret = av_mallocz(sizeof(*ret));
77 ret->internal = av_mallocz(sizeof(*ret->internal));
83 ret->av_class = &filtergraph_class;
84 av_opt_set_defaults(ret);
89 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
92 for (i = 0; i < graph->nb_filters; i++) {
93 if (graph->filters[i] == filter) {
94 FFSWAP(AVFilterContext*, graph->filters[i],
95 graph->filters[graph->nb_filters - 1]);
102 void avfilter_graph_free(AVFilterGraph **graph)
107 while ((*graph)->nb_filters)
108 avfilter_free((*graph)->filters[0]);
110 ff_graph_thread_free(*graph);
112 av_freep(&(*graph)->scale_sws_opts);
113 av_freep(&(*graph)->resample_lavr_opts);
114 av_freep(&(*graph)->filters);
115 av_freep(&(*graph)->internal);
119 #if FF_API_AVFILTER_OPEN
120 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
122 AVFilterContext **filters = av_realloc(graph->filters,
123 sizeof(*filters) * (graph->nb_filters + 1));
125 return AVERROR(ENOMEM);
127 graph->filters = filters;
128 graph->filters[graph->nb_filters++] = filter;
131 FF_DISABLE_DEPRECATION_WARNINGS
132 graph->filter_count = graph->nb_filters;
133 FF_ENABLE_DEPRECATION_WARNINGS
136 filter->graph = graph;
142 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, const AVFilter *filt,
143 const char *name, const char *args, void *opaque,
144 AVFilterGraph *graph_ctx)
148 *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
150 return AVERROR(ENOMEM);
152 ret = avfilter_init_str(*filt_ctx, args);
160 avfilter_free(*filt_ctx);
165 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
166 const AVFilter *filter,
169 AVFilterContext **filters, *s;
171 if (graph->thread_type && !graph->internal->thread_execute) {
172 if (graph->execute) {
173 graph->internal->thread_execute = graph->execute;
175 int ret = ff_graph_thread_init(graph);
177 av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
183 s = ff_filter_alloc(filter, name);
187 filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
193 graph->filters = filters;
194 graph->filters[graph->nb_filters++] = s;
197 FF_DISABLE_DEPRECATION_WARNINGS
198 graph->filter_count = graph->nb_filters;
199 FF_ENABLE_DEPRECATION_WARNINGS
208 * Check for the validity of graph.
210 * A graph is considered valid if all its input and output pads are
213 * @return 0 in case of success, a negative value otherwise
215 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
217 AVFilterContext *filt;
220 for (i = 0; i < graph->nb_filters; i++) {
221 filt = graph->filters[i];
223 for (j = 0; j < filt->nb_inputs; j++) {
224 if (!filt->inputs[j] || !filt->inputs[j]->src) {
225 av_log(log_ctx, AV_LOG_ERROR,
226 "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
227 filt->input_pads[j].name, filt->name, filt->filter->name);
228 return AVERROR(EINVAL);
232 for (j = 0; j < filt->nb_outputs; j++) {
233 if (!filt->outputs[j] || !filt->outputs[j]->dst) {
234 av_log(log_ctx, AV_LOG_ERROR,
235 "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
236 filt->output_pads[j].name, filt->name, filt->filter->name);
237 return AVERROR(EINVAL);
246 * Configure all the links of graphctx.
248 * @return 0 in case of success, a negative value otherwise
250 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
252 AVFilterContext *filt;
255 for (i = 0; i < graph->nb_filters; i++) {
256 filt = graph->filters[i];
258 if (!filt->nb_outputs) {
259 if ((ret = avfilter_config_links(filt)))
267 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
271 for (i = 0; i < graph->nb_filters; i++)
272 if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
273 return graph->filters[i];
278 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
281 int scaler_count = 0, resampler_count = 0;
283 /* ask all the sub-filters for their supported media formats */
284 for (i = 0; i < graph->nb_filters; i++) {
285 if (graph->filters[i]->filter->query_formats)
286 graph->filters[i]->filter->query_formats(graph->filters[i]);
288 ff_default_query_formats(graph->filters[i]);
291 /* go through and merge as many format lists as possible */
292 for (i = 0; i < graph->nb_filters; i++) {
293 AVFilterContext *filter = graph->filters[i];
295 for (j = 0; j < filter->nb_inputs; j++) {
296 AVFilterLink *link = filter->inputs[j];
297 int convert_needed = 0;
302 if (link->in_formats != link->out_formats &&
303 !ff_merge_formats(link->in_formats,
306 if (link->type == AVMEDIA_TYPE_AUDIO) {
307 if (link->in_channel_layouts != link->out_channel_layouts &&
308 !ff_merge_channel_layouts(link->in_channel_layouts,
309 link->out_channel_layouts))
311 if (link->in_samplerates != link->out_samplerates &&
312 !ff_merge_samplerates(link->in_samplerates,
313 link->out_samplerates))
317 if (convert_needed) {
318 AVFilterContext *convert;
320 AVFilterLink *inlink, *outlink;
321 char scale_args[256];
324 /* couldn't merge format lists. auto-insert conversion filter */
325 switch (link->type) {
326 case AVMEDIA_TYPE_VIDEO:
327 if (!(filter = avfilter_get_by_name("scale"))) {
328 av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
329 "not present, cannot convert pixel formats.\n");
330 return AVERROR(EINVAL);
333 snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
336 if ((ret = avfilter_graph_create_filter(&convert, filter,
337 inst_name, graph->scale_sws_opts, NULL,
341 case AVMEDIA_TYPE_AUDIO:
342 if (!(filter = avfilter_get_by_name("resample"))) {
343 av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
344 "not present, cannot convert audio formats.\n");
345 return AVERROR(EINVAL);
348 snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
350 scale_args[0] = '\0';
351 if (graph->resample_lavr_opts)
352 snprintf(scale_args, sizeof(scale_args), "%s",
353 graph->resample_lavr_opts);
354 if ((ret = avfilter_graph_create_filter(&convert, filter,
355 inst_name, scale_args,
360 return AVERROR(EINVAL);
363 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
366 convert->filter->query_formats(convert);
367 inlink = convert->inputs[0];
368 outlink = convert->outputs[0];
369 if (!ff_merge_formats( inlink->in_formats, inlink->out_formats) ||
370 !ff_merge_formats(outlink->in_formats, outlink->out_formats))
371 ret |= AVERROR(ENOSYS);
372 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
373 (!ff_merge_samplerates(inlink->in_samplerates,
374 inlink->out_samplerates) ||
375 !ff_merge_channel_layouts(inlink->in_channel_layouts,
376 inlink->out_channel_layouts)))
377 ret |= AVERROR(ENOSYS);
378 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
379 (!ff_merge_samplerates(outlink->in_samplerates,
380 outlink->out_samplerates) ||
381 !ff_merge_channel_layouts(outlink->in_channel_layouts,
382 outlink->out_channel_layouts)))
383 ret |= AVERROR(ENOSYS);
386 av_log(log_ctx, AV_LOG_ERROR,
387 "Impossible to convert between the formats supported by the filter "
388 "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
398 static int pick_format(AVFilterLink *link)
400 if (!link || !link->in_formats)
403 link->in_formats->nb_formats = 1;
404 link->format = link->in_formats->formats[0];
406 if (link->type == AVMEDIA_TYPE_AUDIO) {
407 if (!link->in_samplerates->nb_formats) {
408 av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
409 " the link between filters %s and %s.\n", link->src->name,
411 return AVERROR(EINVAL);
413 link->in_samplerates->nb_formats = 1;
414 link->sample_rate = link->in_samplerates->formats[0];
416 if (!link->in_channel_layouts->nb_channel_layouts) {
417 av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
418 "the link between filters %s and %s.\n", link->src->name,
420 return AVERROR(EINVAL);
422 link->in_channel_layouts->nb_channel_layouts = 1;
423 link->channel_layout = link->in_channel_layouts->channel_layouts[0];
426 ff_formats_unref(&link->in_formats);
427 ff_formats_unref(&link->out_formats);
428 ff_formats_unref(&link->in_samplerates);
429 ff_formats_unref(&link->out_samplerates);
430 ff_channel_layouts_unref(&link->in_channel_layouts);
431 ff_channel_layouts_unref(&link->out_channel_layouts);
436 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
438 for (i = 0; i < filter->nb_inputs; i++) { \
439 AVFilterLink *link = filter->inputs[i]; \
442 if (!link->out_ ## list || link->out_ ## list->nb != 1) \
444 fmt = link->out_ ## list->var[0]; \
446 for (j = 0; j < filter->nb_outputs; j++) { \
447 AVFilterLink *out_link = filter->outputs[j]; \
450 if (link->type != out_link->type || \
451 out_link->in_ ## list->nb == 1) \
453 fmts = out_link->in_ ## list; \
455 if (!out_link->in_ ## list->nb) { \
456 add_format(&out_link->in_ ##list, fmt); \
460 for (k = 0; k < out_link->in_ ## list->nb; k++) \
461 if (fmts->var[k] == fmt) { \
462 fmts->var[0] = fmt; \
471 static int reduce_formats_on_filter(AVFilterContext *filter)
473 int i, j, k, ret = 0;
475 REDUCE_FORMATS(int, AVFilterFormats, formats, formats,
476 nb_formats, ff_add_format);
477 REDUCE_FORMATS(int, AVFilterFormats, samplerates, formats,
478 nb_formats, ff_add_format);
479 REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
480 channel_layouts, nb_channel_layouts, ff_add_channel_layout);
485 static void reduce_formats(AVFilterGraph *graph)
492 for (i = 0; i < graph->nb_filters; i++)
493 reduced |= reduce_formats_on_filter(graph->filters[i]);
497 static void swap_samplerates_on_filter(AVFilterContext *filter)
499 AVFilterLink *link = NULL;
503 for (i = 0; i < filter->nb_inputs; i++) {
504 link = filter->inputs[i];
506 if (link->type == AVMEDIA_TYPE_AUDIO &&
507 link->out_samplerates->nb_formats== 1)
510 if (i == filter->nb_inputs)
513 sample_rate = link->out_samplerates->formats[0];
515 for (i = 0; i < filter->nb_outputs; i++) {
516 AVFilterLink *outlink = filter->outputs[i];
517 int best_idx, best_diff = INT_MAX;
519 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
520 outlink->in_samplerates->nb_formats < 2)
523 for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
524 int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
526 if (diff < best_diff) {
531 FFSWAP(int, outlink->in_samplerates->formats[0],
532 outlink->in_samplerates->formats[best_idx]);
536 static void swap_samplerates(AVFilterGraph *graph)
540 for (i = 0; i < graph->nb_filters; i++)
541 swap_samplerates_on_filter(graph->filters[i]);
544 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
545 #define CH_FRONT_PAIR (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT)
546 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT | AV_CH_STEREO_RIGHT)
547 #define CH_WIDE_PAIR (AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT)
548 #define CH_SIDE_PAIR (AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
549 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
550 #define CH_BACK_PAIR (AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT)
552 /* allowable substitutions for channel pairs when comparing layouts,
553 * ordered by priority for both values */
554 static const uint64_t ch_subst[][2] = {
555 { CH_FRONT_PAIR, CH_CENTER_PAIR },
556 { CH_FRONT_PAIR, CH_WIDE_PAIR },
557 { CH_FRONT_PAIR, AV_CH_FRONT_CENTER },
558 { CH_CENTER_PAIR, CH_FRONT_PAIR },
559 { CH_CENTER_PAIR, CH_WIDE_PAIR },
560 { CH_CENTER_PAIR, AV_CH_FRONT_CENTER },
561 { CH_WIDE_PAIR, CH_FRONT_PAIR },
562 { CH_WIDE_PAIR, CH_CENTER_PAIR },
563 { CH_WIDE_PAIR, AV_CH_FRONT_CENTER },
564 { AV_CH_FRONT_CENTER, CH_FRONT_PAIR },
565 { AV_CH_FRONT_CENTER, CH_CENTER_PAIR },
566 { AV_CH_FRONT_CENTER, CH_WIDE_PAIR },
567 { CH_SIDE_PAIR, CH_DIRECT_PAIR },
568 { CH_SIDE_PAIR, CH_BACK_PAIR },
569 { CH_SIDE_PAIR, AV_CH_BACK_CENTER },
570 { CH_BACK_PAIR, CH_DIRECT_PAIR },
571 { CH_BACK_PAIR, CH_SIDE_PAIR },
572 { CH_BACK_PAIR, AV_CH_BACK_CENTER },
573 { AV_CH_BACK_CENTER, CH_BACK_PAIR },
574 { AV_CH_BACK_CENTER, CH_DIRECT_PAIR },
575 { AV_CH_BACK_CENTER, CH_SIDE_PAIR },
578 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
580 AVFilterLink *link = NULL;
583 for (i = 0; i < filter->nb_inputs; i++) {
584 link = filter->inputs[i];
586 if (link->type == AVMEDIA_TYPE_AUDIO &&
587 link->out_channel_layouts->nb_channel_layouts == 1)
590 if (i == filter->nb_inputs)
593 for (i = 0; i < filter->nb_outputs; i++) {
594 AVFilterLink *outlink = filter->outputs[i];
595 int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
597 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
598 outlink->in_channel_layouts->nb_channel_layouts < 2)
601 for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
602 uint64_t in_chlayout = link->out_channel_layouts->channel_layouts[0];
603 uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
604 int in_channels = av_get_channel_layout_nb_channels(in_chlayout);
605 int out_channels = av_get_channel_layout_nb_channels(out_chlayout);
606 int count_diff = out_channels - in_channels;
607 int matched_channels, extra_channels;
610 /* channel substitution */
611 for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
612 uint64_t cmp0 = ch_subst[k][0];
613 uint64_t cmp1 = ch_subst[k][1];
614 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
615 (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
616 in_chlayout &= ~cmp0;
617 out_chlayout &= ~cmp1;
618 /* add score for channel match, minus a deduction for
619 having to do the substitution */
620 score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
624 /* no penalty for LFE channel mismatch */
625 if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
626 (out_chlayout & AV_CH_LOW_FREQUENCY))
628 in_chlayout &= ~AV_CH_LOW_FREQUENCY;
629 out_chlayout &= ~AV_CH_LOW_FREQUENCY;
631 matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
633 extra_channels = av_get_channel_layout_nb_channels(out_chlayout &
635 score += 10 * matched_channels - 5 * extra_channels;
637 if (score > best_score ||
638 (count_diff < best_count_diff && score == best_score)) {
641 best_count_diff = count_diff;
644 av_assert0(best_idx >= 0);
645 FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
646 outlink->in_channel_layouts->channel_layouts[best_idx]);
651 static void swap_channel_layouts(AVFilterGraph *graph)
655 for (i = 0; i < graph->nb_filters; i++)
656 swap_channel_layouts_on_filter(graph->filters[i]);
659 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
661 AVFilterLink *link = NULL;
665 for (i = 0; i < filter->nb_inputs; i++) {
666 link = filter->inputs[i];
668 if (link->type == AVMEDIA_TYPE_AUDIO &&
669 link->out_formats->nb_formats == 1)
672 if (i == filter->nb_inputs)
675 format = link->out_formats->formats[0];
676 bps = av_get_bytes_per_sample(format);
678 for (i = 0; i < filter->nb_outputs; i++) {
679 AVFilterLink *outlink = filter->outputs[i];
680 int best_idx = -1, best_score = INT_MIN;
682 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
683 outlink->in_formats->nb_formats < 2)
686 for (j = 0; j < outlink->in_formats->nb_formats; j++) {
687 int out_format = outlink->in_formats->formats[j];
688 int out_bps = av_get_bytes_per_sample(out_format);
691 if (av_get_packed_sample_fmt(out_format) == format ||
692 av_get_planar_sample_fmt(out_format) == format) {
697 /* for s32 and float prefer double to prevent loss of information */
698 if (bps == 4 && out_bps == 8) {
703 /* prefer closest higher or equal bps */
704 score = -abs(out_bps - bps);
708 if (score > best_score) {
713 av_assert0(best_idx >= 0);
714 FFSWAP(int, outlink->in_formats->formats[0],
715 outlink->in_formats->formats[best_idx]);
719 static void swap_sample_fmts(AVFilterGraph *graph)
723 for (i = 0; i < graph->nb_filters; i++)
724 swap_sample_fmts_on_filter(graph->filters[i]);
728 static int pick_formats(AVFilterGraph *graph)
732 for (i = 0; i < graph->nb_filters; i++) {
733 AVFilterContext *filter = graph->filters[i];
735 for (j = 0; j < filter->nb_inputs; j++)
736 if ((ret = pick_format(filter->inputs[j])) < 0)
738 for (j = 0; j < filter->nb_outputs; j++)
739 if ((ret = pick_format(filter->outputs[j])) < 0)
746 * Configure the formats of all the links in the graph.
748 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
752 /* find supported formats from sub-filters, and merge along links */
753 if ((ret = query_formats(graph, log_ctx)) < 0)
756 /* Once everything is merged, it's possible that we'll still have
757 * multiple valid media format choices. We try to minimize the amount
758 * of format conversion inside filters */
759 reduce_formats(graph);
761 /* for audio filters, ensure the best format, sample rate and channel layout
763 swap_sample_fmts(graph);
764 swap_samplerates(graph);
765 swap_channel_layouts(graph);
767 if ((ret = pick_formats(graph)) < 0)
773 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
779 for (i = 0; i < graph->nb_filters; i++) {
780 f = graph->filters[i];
782 for (j = 0; j < f->nb_inputs; j++) {
783 AVFilterLink *link = f->inputs[j];
784 AVFilterContext *fifo_ctx;
788 if (!link->dstpad->needs_fifo)
791 fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
792 avfilter_get_by_name("fifo") :
793 avfilter_get_by_name("afifo");
795 snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
797 ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
802 ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
811 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
815 if ((ret = graph_check_validity(graphctx, log_ctx)))
817 if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
819 if ((ret = graph_config_formats(graphctx, log_ctx)))
821 if ((ret = graph_config_links(graphctx, log_ctx)))