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/log.h"
32 #include "libavutil/opt.h"
39 #define OFFSET(x) offsetof(AVFilterGraph, x)
40 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM
41 static const AVOption filtergraph_options[] = {
42 { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
43 { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
44 { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .flags = FLAGS, .unit = "thread_type" },
45 { "threads", "Maximum number of threads", OFFSET(nb_threads),
46 AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
50 static const AVClass filtergraph_class = {
51 .class_name = "AVFilterGraph",
52 .item_name = av_default_item_name,
53 .version = LIBAVUTIL_VERSION_INT,
54 .option = filtergraph_options,
58 void ff_graph_thread_free(AVFilterGraph *graph)
62 int ff_graph_thread_init(AVFilterGraph *graph)
64 graph->thread_type = 0;
65 graph->nb_threads = 1;
70 AVFilterGraph *avfilter_graph_alloc(void)
72 AVFilterGraph *ret = av_mallocz(sizeof(*ret));
76 ret->internal = av_mallocz(sizeof(*ret->internal));
82 ret->av_class = &filtergraph_class;
83 av_opt_set_defaults(ret);
88 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
91 for (i = 0; i < graph->nb_filters; i++) {
92 if (graph->filters[i] == filter) {
93 FFSWAP(AVFilterContext*, graph->filters[i],
94 graph->filters[graph->nb_filters - 1]);
101 void avfilter_graph_free(AVFilterGraph **graph)
106 while ((*graph)->nb_filters)
107 avfilter_free((*graph)->filters[0]);
109 ff_graph_thread_free(*graph);
111 av_freep(&(*graph)->scale_sws_opts);
112 av_freep(&(*graph)->resample_lavr_opts);
113 av_freep(&(*graph)->filters);
114 av_freep(&(*graph)->internal);
118 #if FF_API_AVFILTER_OPEN
119 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
121 AVFilterContext **filters = av_realloc(graph->filters,
122 sizeof(*filters) * (graph->nb_filters + 1));
124 return AVERROR(ENOMEM);
126 graph->filters = filters;
127 graph->filters[graph->nb_filters++] = filter;
130 graph->filter_count = graph->nb_filters;
133 filter->graph = graph;
139 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
140 const char *name, const char *args, void *opaque,
141 AVFilterGraph *graph_ctx)
145 *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
147 return AVERROR(ENOMEM);
149 ret = avfilter_init_str(*filt_ctx, args);
157 avfilter_free(*filt_ctx);
162 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
163 const AVFilter *filter,
166 AVFilterContext **filters, *s;
168 if (graph->thread_type && !graph->internal->thread) {
169 int ret = ff_graph_thread_init(graph);
171 av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
176 s = ff_filter_alloc(filter, name);
180 filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
186 graph->filters = filters;
187 graph->filters[graph->nb_filters++] = s;
190 graph->filter_count = graph->nb_filters;
199 * Check for the validity of graph.
201 * A graph is considered valid if all its input and output pads are
204 * @return 0 in case of success, a negative value otherwise
206 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
208 AVFilterContext *filt;
211 for (i = 0; i < graph->nb_filters; i++) {
212 filt = graph->filters[i];
214 for (j = 0; j < filt->nb_inputs; j++) {
215 if (!filt->inputs[j] || !filt->inputs[j]->src) {
216 av_log(log_ctx, AV_LOG_ERROR,
217 "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
218 filt->input_pads[j].name, filt->name, filt->filter->name);
219 return AVERROR(EINVAL);
223 for (j = 0; j < filt->nb_outputs; j++) {
224 if (!filt->outputs[j] || !filt->outputs[j]->dst) {
225 av_log(log_ctx, AV_LOG_ERROR,
226 "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
227 filt->output_pads[j].name, filt->name, filt->filter->name);
228 return AVERROR(EINVAL);
237 * Configure all the links of graphctx.
239 * @return 0 in case of success, a negative value otherwise
241 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
243 AVFilterContext *filt;
246 for (i = 0; i < graph->nb_filters; i++) {
247 filt = graph->filters[i];
249 if (!filt->nb_outputs) {
250 if ((ret = avfilter_config_links(filt)))
258 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
262 for (i = 0; i < graph->nb_filters; i++)
263 if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
264 return graph->filters[i];
269 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
272 int scaler_count = 0, resampler_count = 0;
274 /* ask all the sub-filters for their supported media formats */
275 for (i = 0; i < graph->nb_filters; i++) {
276 if (graph->filters[i]->filter->query_formats)
277 graph->filters[i]->filter->query_formats(graph->filters[i]);
279 ff_default_query_formats(graph->filters[i]);
282 /* go through and merge as many format lists as possible */
283 for (i = 0; i < graph->nb_filters; i++) {
284 AVFilterContext *filter = graph->filters[i];
286 for (j = 0; j < filter->nb_inputs; j++) {
287 AVFilterLink *link = filter->inputs[j];
288 int convert_needed = 0;
293 if (link->in_formats != link->out_formats &&
294 !ff_merge_formats(link->in_formats,
297 if (link->type == AVMEDIA_TYPE_AUDIO) {
298 if (link->in_channel_layouts != link->out_channel_layouts &&
299 !ff_merge_channel_layouts(link->in_channel_layouts,
300 link->out_channel_layouts))
302 if (link->in_samplerates != link->out_samplerates &&
303 !ff_merge_samplerates(link->in_samplerates,
304 link->out_samplerates))
308 if (convert_needed) {
309 AVFilterContext *convert;
311 AVFilterLink *inlink, *outlink;
312 char scale_args[256];
315 /* couldn't merge format lists. auto-insert conversion filter */
316 switch (link->type) {
317 case AVMEDIA_TYPE_VIDEO:
318 if (!(filter = avfilter_get_by_name("scale"))) {
319 av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
320 "not present, cannot convert pixel formats.\n");
321 return AVERROR(EINVAL);
324 snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
327 if ((ret = avfilter_graph_create_filter(&convert, filter,
328 inst_name, graph->scale_sws_opts, NULL,
332 case AVMEDIA_TYPE_AUDIO:
333 if (!(filter = avfilter_get_by_name("resample"))) {
334 av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
335 "not present, cannot convert audio formats.\n");
336 return AVERROR(EINVAL);
339 snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
341 scale_args[0] = '\0';
342 if (graph->resample_lavr_opts)
343 snprintf(scale_args, sizeof(scale_args), "%s",
344 graph->resample_lavr_opts);
345 if ((ret = avfilter_graph_create_filter(&convert, filter,
346 inst_name, scale_args,
351 return AVERROR(EINVAL);
354 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
357 convert->filter->query_formats(convert);
358 inlink = convert->inputs[0];
359 outlink = convert->outputs[0];
360 if (!ff_merge_formats( inlink->in_formats, inlink->out_formats) ||
361 !ff_merge_formats(outlink->in_formats, outlink->out_formats))
362 ret |= AVERROR(ENOSYS);
363 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
364 (!ff_merge_samplerates(inlink->in_samplerates,
365 inlink->out_samplerates) ||
366 !ff_merge_channel_layouts(inlink->in_channel_layouts,
367 inlink->out_channel_layouts)))
368 ret |= AVERROR(ENOSYS);
369 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
370 (!ff_merge_samplerates(outlink->in_samplerates,
371 outlink->out_samplerates) ||
372 !ff_merge_channel_layouts(outlink->in_channel_layouts,
373 outlink->out_channel_layouts)))
374 ret |= AVERROR(ENOSYS);
377 av_log(log_ctx, AV_LOG_ERROR,
378 "Impossible to convert between the formats supported by the filter "
379 "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
389 static int pick_format(AVFilterLink *link)
391 if (!link || !link->in_formats)
394 link->in_formats->nb_formats = 1;
395 link->format = link->in_formats->formats[0];
397 if (link->type == AVMEDIA_TYPE_AUDIO) {
398 if (!link->in_samplerates->nb_formats) {
399 av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
400 " the link between filters %s and %s.\n", link->src->name,
402 return AVERROR(EINVAL);
404 link->in_samplerates->nb_formats = 1;
405 link->sample_rate = link->in_samplerates->formats[0];
407 if (!link->in_channel_layouts->nb_channel_layouts) {
408 av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
409 "the link between filters %s and %s.\n", link->src->name,
411 return AVERROR(EINVAL);
413 link->in_channel_layouts->nb_channel_layouts = 1;
414 link->channel_layout = link->in_channel_layouts->channel_layouts[0];
417 ff_formats_unref(&link->in_formats);
418 ff_formats_unref(&link->out_formats);
419 ff_formats_unref(&link->in_samplerates);
420 ff_formats_unref(&link->out_samplerates);
421 ff_channel_layouts_unref(&link->in_channel_layouts);
422 ff_channel_layouts_unref(&link->out_channel_layouts);
427 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
429 for (i = 0; i < filter->nb_inputs; i++) { \
430 AVFilterLink *link = filter->inputs[i]; \
433 if (!link->out_ ## list || link->out_ ## list->nb != 1) \
435 fmt = link->out_ ## list->var[0]; \
437 for (j = 0; j < filter->nb_outputs; j++) { \
438 AVFilterLink *out_link = filter->outputs[j]; \
441 if (link->type != out_link->type || \
442 out_link->in_ ## list->nb == 1) \
444 fmts = out_link->in_ ## list; \
446 if (!out_link->in_ ## list->nb) { \
447 add_format(&out_link->in_ ##list, fmt); \
451 for (k = 0; k < out_link->in_ ## list->nb; k++) \
452 if (fmts->var[k] == fmt) { \
453 fmts->var[0] = fmt; \
462 static int reduce_formats_on_filter(AVFilterContext *filter)
464 int i, j, k, ret = 0;
466 REDUCE_FORMATS(int, AVFilterFormats, formats, formats,
467 nb_formats, ff_add_format);
468 REDUCE_FORMATS(int, AVFilterFormats, samplerates, formats,
469 nb_formats, ff_add_format);
470 REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
471 channel_layouts, nb_channel_layouts, ff_add_channel_layout);
476 static void reduce_formats(AVFilterGraph *graph)
483 for (i = 0; i < graph->nb_filters; i++)
484 reduced |= reduce_formats_on_filter(graph->filters[i]);
488 static void swap_samplerates_on_filter(AVFilterContext *filter)
490 AVFilterLink *link = NULL;
494 for (i = 0; i < filter->nb_inputs; i++) {
495 link = filter->inputs[i];
497 if (link->type == AVMEDIA_TYPE_AUDIO &&
498 link->out_samplerates->nb_formats== 1)
501 if (i == filter->nb_inputs)
504 sample_rate = link->out_samplerates->formats[0];
506 for (i = 0; i < filter->nb_outputs; i++) {
507 AVFilterLink *outlink = filter->outputs[i];
508 int best_idx, best_diff = INT_MAX;
510 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
511 outlink->in_samplerates->nb_formats < 2)
514 for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
515 int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
517 if (diff < best_diff) {
522 FFSWAP(int, outlink->in_samplerates->formats[0],
523 outlink->in_samplerates->formats[best_idx]);
527 static void swap_samplerates(AVFilterGraph *graph)
531 for (i = 0; i < graph->nb_filters; i++)
532 swap_samplerates_on_filter(graph->filters[i]);
535 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
536 #define CH_FRONT_PAIR (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT)
537 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT | AV_CH_STEREO_RIGHT)
538 #define CH_WIDE_PAIR (AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT)
539 #define CH_SIDE_PAIR (AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
540 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
541 #define CH_BACK_PAIR (AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT)
543 /* allowable substitutions for channel pairs when comparing layouts,
544 * ordered by priority for both values */
545 static const uint64_t ch_subst[][2] = {
546 { CH_FRONT_PAIR, CH_CENTER_PAIR },
547 { CH_FRONT_PAIR, CH_WIDE_PAIR },
548 { CH_FRONT_PAIR, AV_CH_FRONT_CENTER },
549 { CH_CENTER_PAIR, CH_FRONT_PAIR },
550 { CH_CENTER_PAIR, CH_WIDE_PAIR },
551 { CH_CENTER_PAIR, AV_CH_FRONT_CENTER },
552 { CH_WIDE_PAIR, CH_FRONT_PAIR },
553 { CH_WIDE_PAIR, CH_CENTER_PAIR },
554 { CH_WIDE_PAIR, AV_CH_FRONT_CENTER },
555 { AV_CH_FRONT_CENTER, CH_FRONT_PAIR },
556 { AV_CH_FRONT_CENTER, CH_CENTER_PAIR },
557 { AV_CH_FRONT_CENTER, CH_WIDE_PAIR },
558 { CH_SIDE_PAIR, CH_DIRECT_PAIR },
559 { CH_SIDE_PAIR, CH_BACK_PAIR },
560 { CH_SIDE_PAIR, AV_CH_BACK_CENTER },
561 { CH_BACK_PAIR, CH_DIRECT_PAIR },
562 { CH_BACK_PAIR, CH_SIDE_PAIR },
563 { CH_BACK_PAIR, AV_CH_BACK_CENTER },
564 { AV_CH_BACK_CENTER, CH_BACK_PAIR },
565 { AV_CH_BACK_CENTER, CH_DIRECT_PAIR },
566 { AV_CH_BACK_CENTER, CH_SIDE_PAIR },
569 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
571 AVFilterLink *link = NULL;
574 for (i = 0; i < filter->nb_inputs; i++) {
575 link = filter->inputs[i];
577 if (link->type == AVMEDIA_TYPE_AUDIO &&
578 link->out_channel_layouts->nb_channel_layouts == 1)
581 if (i == filter->nb_inputs)
584 for (i = 0; i < filter->nb_outputs; i++) {
585 AVFilterLink *outlink = filter->outputs[i];
586 int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
588 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
589 outlink->in_channel_layouts->nb_channel_layouts < 2)
592 for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
593 uint64_t in_chlayout = link->out_channel_layouts->channel_layouts[0];
594 uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
595 int in_channels = av_get_channel_layout_nb_channels(in_chlayout);
596 int out_channels = av_get_channel_layout_nb_channels(out_chlayout);
597 int count_diff = out_channels - in_channels;
598 int matched_channels, extra_channels;
601 /* channel substitution */
602 for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
603 uint64_t cmp0 = ch_subst[k][0];
604 uint64_t cmp1 = ch_subst[k][1];
605 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
606 (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
607 in_chlayout &= ~cmp0;
608 out_chlayout &= ~cmp1;
609 /* add score for channel match, minus a deduction for
610 having to do the substitution */
611 score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
615 /* no penalty for LFE channel mismatch */
616 if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
617 (out_chlayout & AV_CH_LOW_FREQUENCY))
619 in_chlayout &= ~AV_CH_LOW_FREQUENCY;
620 out_chlayout &= ~AV_CH_LOW_FREQUENCY;
622 matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
624 extra_channels = av_get_channel_layout_nb_channels(out_chlayout &
626 score += 10 * matched_channels - 5 * extra_channels;
628 if (score > best_score ||
629 (count_diff < best_count_diff && score == best_score)) {
632 best_count_diff = count_diff;
635 av_assert0(best_idx >= 0);
636 FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
637 outlink->in_channel_layouts->channel_layouts[best_idx]);
642 static void swap_channel_layouts(AVFilterGraph *graph)
646 for (i = 0; i < graph->nb_filters; i++)
647 swap_channel_layouts_on_filter(graph->filters[i]);
650 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
652 AVFilterLink *link = NULL;
656 for (i = 0; i < filter->nb_inputs; i++) {
657 link = filter->inputs[i];
659 if (link->type == AVMEDIA_TYPE_AUDIO &&
660 link->out_formats->nb_formats == 1)
663 if (i == filter->nb_inputs)
666 format = link->out_formats->formats[0];
667 bps = av_get_bytes_per_sample(format);
669 for (i = 0; i < filter->nb_outputs; i++) {
670 AVFilterLink *outlink = filter->outputs[i];
671 int best_idx = -1, best_score = INT_MIN;
673 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
674 outlink->in_formats->nb_formats < 2)
677 for (j = 0; j < outlink->in_formats->nb_formats; j++) {
678 int out_format = outlink->in_formats->formats[j];
679 int out_bps = av_get_bytes_per_sample(out_format);
682 if (av_get_packed_sample_fmt(out_format) == format ||
683 av_get_planar_sample_fmt(out_format) == format) {
688 /* for s32 and float prefer double to prevent loss of information */
689 if (bps == 4 && out_bps == 8) {
694 /* prefer closest higher or equal bps */
695 score = -abs(out_bps - bps);
699 if (score > best_score) {
704 av_assert0(best_idx >= 0);
705 FFSWAP(int, outlink->in_formats->formats[0],
706 outlink->in_formats->formats[best_idx]);
710 static void swap_sample_fmts(AVFilterGraph *graph)
714 for (i = 0; i < graph->nb_filters; i++)
715 swap_sample_fmts_on_filter(graph->filters[i]);
719 static int pick_formats(AVFilterGraph *graph)
723 for (i = 0; i < graph->nb_filters; i++) {
724 AVFilterContext *filter = graph->filters[i];
726 for (j = 0; j < filter->nb_inputs; j++)
727 if ((ret = pick_format(filter->inputs[j])) < 0)
729 for (j = 0; j < filter->nb_outputs; j++)
730 if ((ret = pick_format(filter->outputs[j])) < 0)
737 * Configure the formats of all the links in the graph.
739 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
743 /* find supported formats from sub-filters, and merge along links */
744 if ((ret = query_formats(graph, log_ctx)) < 0)
747 /* Once everything is merged, it's possible that we'll still have
748 * multiple valid media format choices. We try to minimize the amount
749 * of format conversion inside filters */
750 reduce_formats(graph);
752 /* for audio filters, ensure the best format, sample rate and channel layout
754 swap_sample_fmts(graph);
755 swap_samplerates(graph);
756 swap_channel_layouts(graph);
758 if ((ret = pick_formats(graph)) < 0)
764 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
770 for (i = 0; i < graph->nb_filters; i++) {
771 f = graph->filters[i];
773 for (j = 0; j < f->nb_inputs; j++) {
774 AVFilterLink *link = f->inputs[j];
775 AVFilterContext *fifo_ctx;
779 if (!link->dstpad->needs_fifo)
782 fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
783 avfilter_get_by_name("fifo") :
784 avfilter_get_by_name("afifo");
786 snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
788 ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
793 ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
802 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
806 if ((ret = graph_check_validity(graphctx, log_ctx)))
808 if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
810 if ((ret = graph_config_formats(graphctx, log_ctx)))
812 if ((ret = graph_config_links(graphctx, log_ctx)))