3 * Copyright (c) 2008 Vitor Sessak
4 * Copyright (c) 2007 Bobby Bingham
6 * This file is part of FFmpeg.
8 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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/bprint.h"
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavcodec/avcodec.h" // avcodec_find_best_pix_fmt_of_2()
40 #define OFFSET(x) offsetof(AVFilterGraph, x)
41 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_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 },
48 {"scale_sws_opts" , "default scale filter options" , OFFSET(scale_sws_opts) ,
49 AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
50 {"aresample_swr_opts" , "default aresample filter options" , OFFSET(aresample_swr_opts) ,
51 AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
55 static const AVClass filtergraph_class = {
56 .class_name = "AVFilterGraph",
57 .item_name = av_default_item_name,
58 .version = LIBAVUTIL_VERSION_INT,
59 .option = filtergraph_options,
60 .category = AV_CLASS_CATEGORY_FILTER,
64 void ff_graph_thread_free(AVFilterGraph *graph)
68 int ff_graph_thread_init(AVFilterGraph *graph)
70 graph->thread_type = 0;
71 graph->nb_threads = 1;
76 AVFilterGraph *avfilter_graph_alloc(void)
78 AVFilterGraph *ret = av_mallocz(sizeof(*ret));
82 ret->internal = av_mallocz(sizeof(*ret->internal));
88 ret->av_class = &filtergraph_class;
89 av_opt_set_defaults(ret);
94 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
97 for (i = 0; i < graph->nb_filters; i++) {
98 if (graph->filters[i] == filter) {
99 FFSWAP(AVFilterContext*, graph->filters[i],
100 graph->filters[graph->nb_filters - 1]);
107 void avfilter_graph_free(AVFilterGraph **graph)
112 while ((*graph)->nb_filters)
113 avfilter_free((*graph)->filters[0]);
115 ff_graph_thread_free(*graph);
117 av_freep(&(*graph)->sink_links);
119 av_freep(&(*graph)->scale_sws_opts);
120 av_freep(&(*graph)->aresample_swr_opts);
121 av_freep(&(*graph)->resample_lavr_opts);
122 av_freep(&(*graph)->filters);
123 av_freep(&(*graph)->internal);
127 #if FF_API_AVFILTER_OPEN
128 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
130 AVFilterContext **filters = av_realloc(graph->filters,
131 sizeof(*filters) * (graph->nb_filters + 1));
133 return AVERROR(ENOMEM);
135 graph->filters = filters;
136 graph->filters[graph->nb_filters++] = filter;
139 graph->filter_count_unused = graph->nb_filters;
142 filter->graph = graph;
148 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
149 const char *name, const char *args, void *opaque,
150 AVFilterGraph *graph_ctx)
154 *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
156 return AVERROR(ENOMEM);
158 ret = avfilter_init_str(*filt_ctx, args);
166 avfilter_free(*filt_ctx);
171 void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
173 graph->disable_auto_convert = flags;
176 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
177 const AVFilter *filter,
180 AVFilterContext **filters, *s;
182 if (graph->thread_type && !graph->internal->thread) {
183 int ret = ff_graph_thread_init(graph);
185 av_log(graph, AV_LOG_ERROR, "Error initializing threading.\n");
190 s = ff_filter_alloc(filter, name);
194 filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
200 graph->filters = filters;
201 graph->filters[graph->nb_filters++] = s;
204 graph->filter_count_unused = graph->nb_filters;
213 * Check for the validity of graph.
215 * A graph is considered valid if all its input and output pads are
218 * @return 0 in case of success, a negative value otherwise
220 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
222 AVFilterContext *filt;
225 for (i = 0; i < graph->nb_filters; i++) {
226 const AVFilterPad *pad;
227 filt = graph->filters[i];
229 for (j = 0; j < filt->nb_inputs; j++) {
230 if (!filt->inputs[j] || !filt->inputs[j]->src) {
231 pad = &filt->input_pads[j];
232 av_log(log_ctx, AV_LOG_ERROR,
233 "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
234 pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
235 return AVERROR(EINVAL);
239 for (j = 0; j < filt->nb_outputs; j++) {
240 if (!filt->outputs[j] || !filt->outputs[j]->dst) {
241 pad = &filt->output_pads[j];
242 av_log(log_ctx, AV_LOG_ERROR,
243 "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
244 pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
245 return AVERROR(EINVAL);
254 * Configure all the links of graphctx.
256 * @return 0 in case of success, a negative value otherwise
258 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
260 AVFilterContext *filt;
263 for (i = 0; i < graph->nb_filters; i++) {
264 filt = graph->filters[i];
266 if (!filt->nb_outputs) {
267 if ((ret = avfilter_config_links(filt)))
275 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
279 for (i = 0; i < graph->nb_filters; i++)
280 if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
281 return graph->filters[i];
286 static void sanitize_channel_layouts(void *log, AVFilterChannelLayouts *l)
290 if (l->nb_channel_layouts) {
291 if (l->all_layouts || l->all_counts)
292 av_log(log, AV_LOG_WARNING, "All layouts set on non-empty list\n");
293 l->all_layouts = l->all_counts = 0;
295 if (l->all_counts && !l->all_layouts)
296 av_log(log, AV_LOG_WARNING, "All counts without all layouts\n");
301 static int filter_query_formats(AVFilterContext *ctx)
304 AVFilterFormats *formats;
305 AVFilterChannelLayouts *chlayouts;
306 AVFilterFormats *samplerates;
307 enum AVMediaType type = ctx->inputs && ctx->inputs [0] ? ctx->inputs [0]->type :
308 ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
311 if ((ret = ctx->filter->query_formats(ctx)) < 0) {
312 if (ret != AVERROR(EAGAIN))
313 av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",
314 ctx->name, av_err2str(ret));
318 for (i = 0; i < ctx->nb_inputs; i++)
319 sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);
320 for (i = 0; i < ctx->nb_outputs; i++)
321 sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);
323 formats = ff_all_formats(type);
325 return AVERROR(ENOMEM);
326 ff_set_common_formats(ctx, formats);
327 if (type == AVMEDIA_TYPE_AUDIO) {
328 samplerates = ff_all_samplerates();
330 return AVERROR(ENOMEM);
331 ff_set_common_samplerates(ctx, samplerates);
332 chlayouts = ff_all_channel_layouts();
334 return AVERROR(ENOMEM);
335 ff_set_common_channel_layouts(ctx, chlayouts);
340 static int formats_declared(AVFilterContext *f)
344 for (i = 0; i < f->nb_inputs; i++) {
345 if (!f->inputs[i]->out_formats)
347 if (f->inputs[i]->type == AVMEDIA_TYPE_AUDIO &&
348 !(f->inputs[i]->out_samplerates &&
349 f->inputs[i]->out_channel_layouts))
352 for (i = 0; i < f->nb_outputs; i++) {
353 if (!f->outputs[i]->in_formats)
355 if (f->outputs[i]->type == AVMEDIA_TYPE_AUDIO &&
356 !(f->outputs[i]->in_samplerates &&
357 f->outputs[i]->in_channel_layouts))
364 * Perform one round of query_formats() and merging formats lists on the
366 * @return >=0 if all links formats lists could be queried and merged;
367 * AVERROR(EAGAIN) some progress was made in the queries or merging
368 * and a later call may succeed;
369 * AVERROR(EIO) (may be changed) plus a log message if no progress
370 * was made and the negotiation is stuck;
371 * a negative error code if some other error happened
373 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
376 int scaler_count = 0, resampler_count = 0;
377 int count_queried = 0; /* successful calls to query_formats() */
378 int count_merged = 0; /* successful merge of formats lists */
379 int count_already_merged = 0; /* lists already merged */
380 int count_delayed = 0; /* lists that need to be merged later */
382 for (i = 0; i < graph->nb_filters; i++) {
383 AVFilterContext *f = graph->filters[i];
384 if (formats_declared(f))
386 if (f->filter->query_formats)
387 ret = filter_query_formats(f);
389 ret = ff_default_query_formats(f);
390 if (ret < 0 && ret != AVERROR(EAGAIN))
392 /* note: EAGAIN could indicate a partial success, not counted yet */
393 count_queried += ret >= 0;
396 /* go through and merge as many format lists as possible */
397 for (i = 0; i < graph->nb_filters; i++) {
398 AVFilterContext *filter = graph->filters[i];
400 for (j = 0; j < filter->nb_inputs; j++) {
401 AVFilterLink *link = filter->inputs[j];
402 int convert_needed = 0;
407 #define MERGE_DISPATCH(field, statement) \
408 if (!(link->in_ ## field && link->out_ ## field)) { \
410 } else if (link->in_ ## field == link->out_ ## field) { \
411 count_already_merged++; \
416 MERGE_DISPATCH(formats,
417 if (!ff_merge_formats(link->in_formats, link->out_formats,
421 if (link->type == AVMEDIA_TYPE_AUDIO) {
422 MERGE_DISPATCH(channel_layouts,
423 if (!ff_merge_channel_layouts(link->in_channel_layouts,
424 link->out_channel_layouts))
427 MERGE_DISPATCH(samplerates,
428 if (!ff_merge_samplerates(link->in_samplerates,
429 link->out_samplerates))
433 #undef MERGE_DISPATCH
435 if (convert_needed) {
436 AVFilterContext *convert;
438 AVFilterLink *inlink, *outlink;
439 char scale_args[256];
442 /* couldn't merge format lists. auto-insert conversion filter */
443 switch (link->type) {
444 case AVMEDIA_TYPE_VIDEO:
445 if (!(filter = avfilter_get_by_name("scale"))) {
446 av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
447 "not present, cannot convert pixel formats.\n");
448 return AVERROR(EINVAL);
451 snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
454 if ((ret = avfilter_graph_create_filter(&convert, filter,
455 inst_name, graph->scale_sws_opts, NULL,
459 case AVMEDIA_TYPE_AUDIO:
460 if (!(filter = avfilter_get_by_name("aresample"))) {
461 av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "
462 "not present, cannot convert audio formats.\n");
463 return AVERROR(EINVAL);
466 snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
468 scale_args[0] = '\0';
469 if (graph->aresample_swr_opts)
470 snprintf(scale_args, sizeof(scale_args), "%s",
471 graph->aresample_swr_opts);
472 if ((ret = avfilter_graph_create_filter(&convert, filter,
473 inst_name, graph->aresample_swr_opts,
478 return AVERROR(EINVAL);
481 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
484 filter_query_formats(convert);
485 inlink = convert->inputs[0];
486 outlink = convert->outputs[0];
487 if (!ff_merge_formats( inlink->in_formats, inlink->out_formats, inlink->type) ||
488 !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type))
489 ret |= AVERROR(ENOSYS);
490 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
491 (!ff_merge_samplerates(inlink->in_samplerates,
492 inlink->out_samplerates) ||
493 !ff_merge_channel_layouts(inlink->in_channel_layouts,
494 inlink->out_channel_layouts)))
495 ret |= AVERROR(ENOSYS);
496 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
497 (!ff_merge_samplerates(outlink->in_samplerates,
498 outlink->out_samplerates) ||
499 !ff_merge_channel_layouts(outlink->in_channel_layouts,
500 outlink->out_channel_layouts)))
501 ret |= AVERROR(ENOSYS);
504 av_log(log_ctx, AV_LOG_ERROR,
505 "Impossible to convert between the formats supported by the filter "
506 "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
513 av_log(graph, AV_LOG_DEBUG, "query_formats: "
514 "%d queried, %d merged, %d already done, %d delayed\n",
515 count_queried, count_merged, count_already_merged, count_delayed);
519 /* if count_queried > 0, one filter at least did set its formats,
520 that will give additional information to its neighbour;
521 if count_merged > 0, one pair of formats lists at least was merged,
522 that will give additional information to all connected filters;
523 in both cases, progress was made and a new round must be done */
524 if (count_queried || count_merged)
525 return AVERROR(EAGAIN);
526 av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
527 for (i = 0; i < graph->nb_filters; i++)
528 if (!formats_declared(graph->filters[i]))
529 av_bprintf(&bp, "%s%s", bp.len ? ", " : "",
530 graph->filters[i]->name);
531 av_log(graph, AV_LOG_ERROR,
532 "The following filters could not choose their formats: %s\n"
533 "Consider inserting the (a)format filter near their input or "
534 "output.\n", bp.str);
540 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
542 if (!link || !link->in_formats)
545 if (link->type == AVMEDIA_TYPE_VIDEO) {
546 if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
547 int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
548 enum AVPixelFormat best= AV_PIX_FMT_NONE;
550 for (i=0; i<link->in_formats->nb_formats; i++) {
551 enum AVPixelFormat p = link->in_formats->formats[i];
552 best= avcodec_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
554 av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
555 av_get_pix_fmt_name(best), link->in_formats->nb_formats,
556 av_get_pix_fmt_name(ref->format), has_alpha);
557 link->in_formats->formats[0] = best;
561 link->in_formats->nb_formats = 1;
562 link->format = link->in_formats->formats[0];
564 if (link->type == AVMEDIA_TYPE_AUDIO) {
565 if (!link->in_samplerates->nb_formats) {
566 av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
567 " the link between filters %s and %s.\n", link->src->name,
569 return AVERROR(EINVAL);
571 link->in_samplerates->nb_formats = 1;
572 link->sample_rate = link->in_samplerates->formats[0];
574 if (link->in_channel_layouts->all_layouts) {
575 av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
576 " the link between filters %s and %s.\n", link->src->name,
578 return AVERROR(EINVAL);
580 link->in_channel_layouts->nb_channel_layouts = 1;
581 link->channel_layout = link->in_channel_layouts->channel_layouts[0];
582 if ((link->channels = FF_LAYOUT2COUNT(link->channel_layout)))
583 link->channel_layout = 0;
585 link->channels = av_get_channel_layout_nb_channels(link->channel_layout);
588 ff_formats_unref(&link->in_formats);
589 ff_formats_unref(&link->out_formats);
590 ff_formats_unref(&link->in_samplerates);
591 ff_formats_unref(&link->out_samplerates);
592 ff_channel_layouts_unref(&link->in_channel_layouts);
593 ff_channel_layouts_unref(&link->out_channel_layouts);
598 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
600 for (i = 0; i < filter->nb_inputs; i++) { \
601 AVFilterLink *link = filter->inputs[i]; \
604 if (!link->out_ ## list || link->out_ ## list->nb != 1) \
606 fmt = link->out_ ## list->var[0]; \
608 for (j = 0; j < filter->nb_outputs; j++) { \
609 AVFilterLink *out_link = filter->outputs[j]; \
612 if (link->type != out_link->type || \
613 out_link->in_ ## list->nb == 1) \
615 fmts = out_link->in_ ## list; \
617 if (!out_link->in_ ## list->nb) { \
618 add_format(&out_link->in_ ##list, fmt); \
622 for (k = 0; k < out_link->in_ ## list->nb; k++) \
623 if (fmts->var[k] == fmt) { \
624 fmts->var[0] = fmt; \
633 static int reduce_formats_on_filter(AVFilterContext *filter)
635 int i, j, k, ret = 0;
637 REDUCE_FORMATS(int, AVFilterFormats, formats, formats,
638 nb_formats, ff_add_format);
639 REDUCE_FORMATS(int, AVFilterFormats, samplerates, formats,
640 nb_formats, ff_add_format);
642 /* reduce channel layouts */
643 for (i = 0; i < filter->nb_inputs; i++) {
644 AVFilterLink *inlink = filter->inputs[i];
647 if (!inlink->out_channel_layouts ||
648 inlink->out_channel_layouts->nb_channel_layouts != 1)
650 fmt = inlink->out_channel_layouts->channel_layouts[0];
652 for (j = 0; j < filter->nb_outputs; j++) {
653 AVFilterLink *outlink = filter->outputs[j];
654 AVFilterChannelLayouts *fmts;
656 fmts = outlink->in_channel_layouts;
657 if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
660 if (fmts->all_layouts) {
661 /* Turn the infinite list into a singleton */
662 fmts->all_layouts = fmts->all_counts = 0;
663 ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
667 for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
668 if (fmts->channel_layouts[k] == fmt) {
669 fmts->channel_layouts[0] = fmt;
670 fmts->nb_channel_layouts = 1;
681 static void reduce_formats(AVFilterGraph *graph)
688 for (i = 0; i < graph->nb_filters; i++)
689 reduced |= reduce_formats_on_filter(graph->filters[i]);
693 static void swap_samplerates_on_filter(AVFilterContext *filter)
695 AVFilterLink *link = NULL;
699 for (i = 0; i < filter->nb_inputs; i++) {
700 link = filter->inputs[i];
702 if (link->type == AVMEDIA_TYPE_AUDIO &&
703 link->out_samplerates->nb_formats== 1)
706 if (i == filter->nb_inputs)
709 sample_rate = link->out_samplerates->formats[0];
711 for (i = 0; i < filter->nb_outputs; i++) {
712 AVFilterLink *outlink = filter->outputs[i];
713 int best_idx, best_diff = INT_MAX;
715 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
716 outlink->in_samplerates->nb_formats < 2)
719 for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
720 int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
722 if (diff < best_diff) {
727 FFSWAP(int, outlink->in_samplerates->formats[0],
728 outlink->in_samplerates->formats[best_idx]);
732 static void swap_samplerates(AVFilterGraph *graph)
736 for (i = 0; i < graph->nb_filters; i++)
737 swap_samplerates_on_filter(graph->filters[i]);
740 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
741 #define CH_FRONT_PAIR (AV_CH_FRONT_LEFT | AV_CH_FRONT_RIGHT)
742 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT | AV_CH_STEREO_RIGHT)
743 #define CH_WIDE_PAIR (AV_CH_WIDE_LEFT | AV_CH_WIDE_RIGHT)
744 #define CH_SIDE_PAIR (AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT)
745 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
746 #define CH_BACK_PAIR (AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT)
748 /* allowable substitutions for channel pairs when comparing layouts,
749 * ordered by priority for both values */
750 static const uint64_t ch_subst[][2] = {
751 { CH_FRONT_PAIR, CH_CENTER_PAIR },
752 { CH_FRONT_PAIR, CH_WIDE_PAIR },
753 { CH_FRONT_PAIR, AV_CH_FRONT_CENTER },
754 { CH_CENTER_PAIR, CH_FRONT_PAIR },
755 { CH_CENTER_PAIR, CH_WIDE_PAIR },
756 { CH_CENTER_PAIR, AV_CH_FRONT_CENTER },
757 { CH_WIDE_PAIR, CH_FRONT_PAIR },
758 { CH_WIDE_PAIR, CH_CENTER_PAIR },
759 { CH_WIDE_PAIR, AV_CH_FRONT_CENTER },
760 { AV_CH_FRONT_CENTER, CH_FRONT_PAIR },
761 { AV_CH_FRONT_CENTER, CH_CENTER_PAIR },
762 { AV_CH_FRONT_CENTER, CH_WIDE_PAIR },
763 { CH_SIDE_PAIR, CH_DIRECT_PAIR },
764 { CH_SIDE_PAIR, CH_BACK_PAIR },
765 { CH_SIDE_PAIR, AV_CH_BACK_CENTER },
766 { CH_BACK_PAIR, CH_DIRECT_PAIR },
767 { CH_BACK_PAIR, CH_SIDE_PAIR },
768 { CH_BACK_PAIR, AV_CH_BACK_CENTER },
769 { AV_CH_BACK_CENTER, CH_BACK_PAIR },
770 { AV_CH_BACK_CENTER, CH_DIRECT_PAIR },
771 { AV_CH_BACK_CENTER, CH_SIDE_PAIR },
774 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
776 AVFilterLink *link = NULL;
779 for (i = 0; i < filter->nb_inputs; i++) {
780 link = filter->inputs[i];
782 if (link->type == AVMEDIA_TYPE_AUDIO &&
783 link->out_channel_layouts->nb_channel_layouts == 1)
786 if (i == filter->nb_inputs)
789 for (i = 0; i < filter->nb_outputs; i++) {
790 AVFilterLink *outlink = filter->outputs[i];
791 int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
793 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
794 outlink->in_channel_layouts->nb_channel_layouts < 2)
797 for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
798 uint64_t in_chlayout = link->out_channel_layouts->channel_layouts[0];
799 uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
800 int in_channels = av_get_channel_layout_nb_channels(in_chlayout);
801 int out_channels = av_get_channel_layout_nb_channels(out_chlayout);
802 int count_diff = out_channels - in_channels;
803 int matched_channels, extra_channels;
806 if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
807 /* Compute score in case the input or output layout encodes
808 a channel count; in this case the score is not altered by
809 the computation afterwards, as in_chlayout and
810 out_chlayout have both been set to 0 */
811 if (FF_LAYOUT2COUNT(in_chlayout))
812 in_channels = FF_LAYOUT2COUNT(in_chlayout);
813 if (FF_LAYOUT2COUNT(out_chlayout))
814 out_channels = FF_LAYOUT2COUNT(out_chlayout);
815 score -= 10000 + FFABS(out_channels - in_channels) +
816 (in_channels > out_channels ? 10000 : 0);
817 in_chlayout = out_chlayout = 0;
818 /* Let the remaining computation run, even if the score
819 value is not altered */
822 /* channel substitution */
823 for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
824 uint64_t cmp0 = ch_subst[k][0];
825 uint64_t cmp1 = ch_subst[k][1];
826 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
827 (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
828 in_chlayout &= ~cmp0;
829 out_chlayout &= ~cmp1;
830 /* add score for channel match, minus a deduction for
831 having to do the substitution */
832 score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
836 /* no penalty for LFE channel mismatch */
837 if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
838 (out_chlayout & AV_CH_LOW_FREQUENCY))
840 in_chlayout &= ~AV_CH_LOW_FREQUENCY;
841 out_chlayout &= ~AV_CH_LOW_FREQUENCY;
843 matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
845 extra_channels = av_get_channel_layout_nb_channels(out_chlayout &
847 score += 10 * matched_channels - 5 * extra_channels;
849 if (score > best_score ||
850 (count_diff < best_count_diff && score == best_score)) {
853 best_count_diff = count_diff;
856 av_assert0(best_idx >= 0);
857 FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
858 outlink->in_channel_layouts->channel_layouts[best_idx]);
863 static void swap_channel_layouts(AVFilterGraph *graph)
867 for (i = 0; i < graph->nb_filters; i++)
868 swap_channel_layouts_on_filter(graph->filters[i]);
871 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
873 AVFilterLink *link = NULL;
877 for (i = 0; i < filter->nb_inputs; i++) {
878 link = filter->inputs[i];
880 if (link->type == AVMEDIA_TYPE_AUDIO &&
881 link->out_formats->nb_formats == 1)
884 if (i == filter->nb_inputs)
887 format = link->out_formats->formats[0];
888 bps = av_get_bytes_per_sample(format);
890 for (i = 0; i < filter->nb_outputs; i++) {
891 AVFilterLink *outlink = filter->outputs[i];
892 int best_idx = -1, best_score = INT_MIN;
894 if (outlink->type != AVMEDIA_TYPE_AUDIO ||
895 outlink->in_formats->nb_formats < 2)
898 for (j = 0; j < outlink->in_formats->nb_formats; j++) {
899 int out_format = outlink->in_formats->formats[j];
900 int out_bps = av_get_bytes_per_sample(out_format);
903 if (av_get_packed_sample_fmt(out_format) == format ||
904 av_get_planar_sample_fmt(out_format) == format) {
909 /* for s32 and float prefer double to prevent loss of information */
910 if (bps == 4 && out_bps == 8) {
915 /* prefer closest higher or equal bps */
916 score = -abs(out_bps - bps);
920 if (score > best_score) {
925 av_assert0(best_idx >= 0);
926 FFSWAP(int, outlink->in_formats->formats[0],
927 outlink->in_formats->formats[best_idx]);
931 static void swap_sample_fmts(AVFilterGraph *graph)
935 for (i = 0; i < graph->nb_filters; i++)
936 swap_sample_fmts_on_filter(graph->filters[i]);
940 static int pick_formats(AVFilterGraph *graph)
947 for (i = 0; i < graph->nb_filters; i++) {
948 AVFilterContext *filter = graph->filters[i];
949 if (filter->nb_inputs){
950 for (j = 0; j < filter->nb_inputs; j++){
951 if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
952 if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
958 if (filter->nb_outputs){
959 for (j = 0; j < filter->nb_outputs; j++){
960 if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
961 if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
967 if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
968 for (j = 0; j < filter->nb_outputs; j++) {
969 if(filter->outputs[j]->format<0) {
970 if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
979 for (i = 0; i < graph->nb_filters; i++) {
980 AVFilterContext *filter = graph->filters[i];
982 for (j = 0; j < filter->nb_inputs; j++)
983 if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
985 for (j = 0; j < filter->nb_outputs; j++)
986 if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
993 * Configure the formats of all the links in the graph.
995 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
999 /* find supported formats from sub-filters, and merge along links */
1000 while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
1001 av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
1005 /* Once everything is merged, it's possible that we'll still have
1006 * multiple valid media format choices. We try to minimize the amount
1007 * of format conversion inside filters */
1008 reduce_formats(graph);
1010 /* for audio filters, ensure the best format, sample rate and channel layout
1012 swap_sample_fmts(graph);
1013 swap_samplerates(graph);
1014 swap_channel_layouts(graph);
1016 if ((ret = pick_formats(graph)) < 0)
1022 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
1026 int sink_links_count = 0, n = 0;
1028 AVFilterLink **sinks;
1030 for (i = 0; i < graph->nb_filters; i++) {
1031 f = graph->filters[i];
1032 for (j = 0; j < f->nb_inputs; j++) {
1033 f->inputs[j]->graph = graph;
1034 f->inputs[j]->age_index = -1;
1036 for (j = 0; j < f->nb_outputs; j++) {
1037 f->outputs[j]->graph = graph;
1038 f->outputs[j]->age_index= -1;
1040 if (!f->nb_outputs) {
1041 if (f->nb_inputs > INT_MAX - sink_links_count)
1042 return AVERROR(EINVAL);
1043 sink_links_count += f->nb_inputs;
1046 sinks = av_calloc(sink_links_count, sizeof(*sinks));
1048 return AVERROR(ENOMEM);
1049 for (i = 0; i < graph->nb_filters; i++) {
1050 f = graph->filters[i];
1051 if (!f->nb_outputs) {
1052 for (j = 0; j < f->nb_inputs; j++) {
1053 sinks[n] = f->inputs[j];
1054 f->inputs[j]->age_index = n++;
1058 av_assert0(n == sink_links_count);
1059 graph->sink_links = sinks;
1060 graph->sink_links_count = sink_links_count;
1064 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
1070 for (i = 0; i < graph->nb_filters; i++) {
1071 f = graph->filters[i];
1073 for (j = 0; j < f->nb_inputs; j++) {
1074 AVFilterLink *link = f->inputs[j];
1075 AVFilterContext *fifo_ctx;
1079 if (!link->dstpad->needs_fifo)
1082 fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
1083 avfilter_get_by_name("fifo") :
1084 avfilter_get_by_name("afifo");
1086 snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
1088 ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
1093 ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
1102 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
1106 if ((ret = graph_check_validity(graphctx, log_ctx)))
1108 if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
1110 if ((ret = graph_config_formats(graphctx, log_ctx)))
1112 if ((ret = graph_config_links(graphctx, log_ctx)))
1114 if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
1120 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
1122 int i, r = AVERROR(ENOSYS);
1127 if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
1128 r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
1129 if (r != AVERROR(ENOSYS))
1136 for (i = 0; i < graph->nb_filters; i++) {
1137 AVFilterContext *filter = graph->filters[i];
1138 if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
1139 r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
1140 if (r != AVERROR(ENOSYS)) {
1141 if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
1150 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
1157 for (i = 0; i < graph->nb_filters; i++) {
1158 AVFilterContext *filter = graph->filters[i];
1159 if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
1160 AVFilterCommand **queue = &filter->command_queue, *next;
1161 while (*queue && (*queue)->time <= ts)
1162 queue = &(*queue)->next;
1164 *queue = av_mallocz(sizeof(AVFilterCommand));
1165 (*queue)->command = av_strdup(command);
1166 (*queue)->arg = av_strdup(arg);
1167 (*queue)->time = ts;
1168 (*queue)->flags = flags;
1169 (*queue)->next = next;
1170 if(flags & AVFILTER_CMD_FLAG_ONE)
1178 static void heap_bubble_up(AVFilterGraph *graph,
1179 AVFilterLink *link, int index)
1181 AVFilterLink **links = graph->sink_links;
1184 int parent = (index - 1) >> 1;
1185 if (links[parent]->current_pts >= link->current_pts)
1187 links[index] = links[parent];
1188 links[index]->age_index = index;
1191 links[index] = link;
1192 link->age_index = index;
1195 static void heap_bubble_down(AVFilterGraph *graph,
1196 AVFilterLink *link, int index)
1198 AVFilterLink **links = graph->sink_links;
1201 int child = 2 * index + 1;
1202 if (child >= graph->sink_links_count)
1204 if (child + 1 < graph->sink_links_count &&
1205 links[child + 1]->current_pts < links[child]->current_pts)
1207 if (link->current_pts < links[child]->current_pts)
1209 links[index] = links[child];
1210 links[index]->age_index = index;
1213 links[index] = link;
1214 link->age_index = index;
1217 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
1219 heap_bubble_up (graph, link, link->age_index);
1220 heap_bubble_down(graph, link, link->age_index);
1224 int avfilter_graph_request_oldest(AVFilterGraph *graph)
1226 while (graph->sink_links_count) {
1227 AVFilterLink *oldest = graph->sink_links[0];
1228 int r = ff_request_frame(oldest);
1229 if (r != AVERROR_EOF)
1231 av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
1232 oldest->dst ? oldest->dst->name : "unknown",
1233 oldest->dstpad ? oldest->dstpad->name : "unknown");
1234 /* EOF: remove the link from the heap */
1235 if (oldest->age_index < --graph->sink_links_count)
1236 heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
1238 oldest->age_index = -1;