avfiltergraph: simplify inserting conversion filters.
[ffmpeg.git] / libavfilter / avfiltergraph.c
1 /*
2  * filter graphs
3  * Copyright (c) 2008 Vitor Sessak
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of Libav.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <string.h>
24
25 #include "libavutil/avassert.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/common.h"
29 #include "libavutil/log.h"
30 #include "avfilter.h"
31 #include "formats.h"
32 #include "internal.h"
33
34 static const AVClass filtergraph_class = {
35     .class_name = "AVFilterGraph",
36     .item_name  = av_default_item_name,
37     .version    = LIBAVUTIL_VERSION_INT,
38 };
39
40 AVFilterGraph *avfilter_graph_alloc(void)
41 {
42     AVFilterGraph *ret = av_mallocz(sizeof(*ret));
43     if (!ret)
44         return NULL;
45     ret->av_class = &filtergraph_class;
46     return ret;
47 }
48
49 void ff_filter_graph_remove_filter(AVFilterGraph *graph, AVFilterContext *filter)
50 {
51     int i;
52     for (i = 0; i < graph->nb_filters; i++) {
53         if (graph->filters[i] == filter) {
54             FFSWAP(AVFilterContext*, graph->filters[i],
55                    graph->filters[graph->nb_filters - 1]);
56             graph->nb_filters--;
57             return;
58         }
59     }
60 }
61
62 void avfilter_graph_free(AVFilterGraph **graph)
63 {
64     if (!*graph)
65         return;
66
67     while ((*graph)->nb_filters)
68         avfilter_free((*graph)->filters[0]);
69
70     av_freep(&(*graph)->scale_sws_opts);
71     av_freep(&(*graph)->resample_lavr_opts);
72     av_freep(&(*graph)->filters);
73     av_freep(graph);
74 }
75
76 #if FF_API_AVFILTER_OPEN
77 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
78 {
79     AVFilterContext **filters = av_realloc(graph->filters,
80                                            sizeof(*filters) * (graph->nb_filters + 1));
81     if (!filters)
82         return AVERROR(ENOMEM);
83
84     graph->filters = filters;
85     graph->filters[graph->nb_filters++] = filter;
86
87 #if FF_API_FOO_COUNT
88     graph->filter_count = graph->nb_filters;
89 #endif
90
91     filter->graph = graph;
92
93     return 0;
94 }
95 #endif
96
97 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
98                                  const char *name, const char *args, void *opaque,
99                                  AVFilterGraph *graph_ctx)
100 {
101     int ret;
102
103     *filt_ctx = avfilter_graph_alloc_filter(graph_ctx, filt, name);
104     if (!*filt_ctx)
105         return AVERROR(ENOMEM);
106
107     ret = avfilter_init_str(*filt_ctx, args);
108     if (ret < 0)
109         goto fail;
110
111     return 0;
112
113 fail:
114     if (*filt_ctx)
115         avfilter_free(*filt_ctx);
116     *filt_ctx = NULL;
117     return ret;
118 }
119
120 AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph,
121                                              const AVFilter *filter,
122                                              const char *name)
123 {
124     AVFilterContext **filters, *s;
125
126     s = ff_filter_alloc(filter, name);
127     if (!s)
128         return NULL;
129
130     filters = av_realloc(graph->filters, sizeof(*filters) * (graph->nb_filters + 1));
131     if (!filters) {
132         avfilter_free(s);
133         return NULL;
134     }
135
136     graph->filters = filters;
137     graph->filters[graph->nb_filters++] = s;
138
139 #if FF_API_FOO_COUNT
140     graph->filter_count = graph->nb_filters;
141 #endif
142
143     s->graph = graph;
144
145     return s;
146 }
147
148 /**
149  * Check for the validity of graph.
150  *
151  * A graph is considered valid if all its input and output pads are
152  * connected.
153  *
154  * @return 0 in case of success, a negative value otherwise
155  */
156 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
157 {
158     AVFilterContext *filt;
159     int i, j;
160
161     for (i = 0; i < graph->nb_filters; i++) {
162         filt = graph->filters[i];
163
164         for (j = 0; j < filt->nb_inputs; j++) {
165             if (!filt->inputs[j] || !filt->inputs[j]->src) {
166                 av_log(log_ctx, AV_LOG_ERROR,
167                        "Input pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any source\n",
168                        filt->input_pads[j].name, filt->name, filt->filter->name);
169                 return AVERROR(EINVAL);
170             }
171         }
172
173         for (j = 0; j < filt->nb_outputs; j++) {
174             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
175                 av_log(log_ctx, AV_LOG_ERROR,
176                        "Output pad \"%s\" for the filter \"%s\" of type \"%s\" not connected to any destination\n",
177                        filt->output_pads[j].name, filt->name, filt->filter->name);
178                 return AVERROR(EINVAL);
179             }
180         }
181     }
182
183     return 0;
184 }
185
186 /**
187  * Configure all the links of graphctx.
188  *
189  * @return 0 in case of success, a negative value otherwise
190  */
191 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
192 {
193     AVFilterContext *filt;
194     int i, ret;
195
196     for (i = 0; i < graph->nb_filters; i++) {
197         filt = graph->filters[i];
198
199         if (!filt->nb_outputs) {
200             if ((ret = avfilter_config_links(filt)))
201                 return ret;
202         }
203     }
204
205     return 0;
206 }
207
208 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
209 {
210     int i;
211
212     for (i = 0; i < graph->nb_filters; i++)
213         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
214             return graph->filters[i];
215
216     return NULL;
217 }
218
219 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
220 {
221     int i, j, ret;
222     int scaler_count = 0, resampler_count = 0;
223
224     /* ask all the sub-filters for their supported media formats */
225     for (i = 0; i < graph->nb_filters; i++) {
226         if (graph->filters[i]->filter->query_formats)
227             graph->filters[i]->filter->query_formats(graph->filters[i]);
228         else
229             ff_default_query_formats(graph->filters[i]);
230     }
231
232     /* go through and merge as many format lists as possible */
233     for (i = 0; i < graph->nb_filters; i++) {
234         AVFilterContext *filter = graph->filters[i];
235
236         for (j = 0; j < filter->nb_inputs; j++) {
237             AVFilterLink *link = filter->inputs[j];
238             int convert_needed = 0;
239
240             if (!link)
241                 continue;
242
243             if (link->in_formats != link->out_formats &&
244                 !ff_merge_formats(link->in_formats,
245                                         link->out_formats))
246                 convert_needed = 1;
247             if (link->type == AVMEDIA_TYPE_AUDIO) {
248                 if (link->in_channel_layouts != link->out_channel_layouts &&
249                     !ff_merge_channel_layouts(link->in_channel_layouts,
250                                               link->out_channel_layouts))
251                     convert_needed = 1;
252                 if (link->in_samplerates != link->out_samplerates &&
253                     !ff_merge_samplerates(link->in_samplerates,
254                                           link->out_samplerates))
255                     convert_needed = 1;
256             }
257
258             if (convert_needed) {
259                 AVFilterContext *convert;
260                 AVFilter *filter;
261                 AVFilterLink *inlink, *outlink;
262                 char scale_args[256];
263                 char inst_name[30];
264
265                 /* couldn't merge format lists. auto-insert conversion filter */
266                 switch (link->type) {
267                 case AVMEDIA_TYPE_VIDEO:
268                     if (!(filter = avfilter_get_by_name("scale"))) {
269                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
270                                "not present, cannot convert pixel formats.\n");
271                         return AVERROR(EINVAL);
272                     }
273
274                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
275                              scaler_count++);
276
277                     if ((ret = avfilter_graph_create_filter(&convert, filter,
278                                                             inst_name, graph->scale_sws_opts, NULL,
279                                                             graph)) < 0)
280                         return ret;
281                     break;
282                 case AVMEDIA_TYPE_AUDIO:
283                     if (!(filter = avfilter_get_by_name("resample"))) {
284                         av_log(log_ctx, AV_LOG_ERROR, "'resample' filter "
285                                "not present, cannot convert audio formats.\n");
286                         return AVERROR(EINVAL);
287                     }
288
289                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
290                              resampler_count++);
291                     scale_args[0] = '\0';
292                     if (graph->resample_lavr_opts)
293                         snprintf(scale_args, sizeof(scale_args), "%s",
294                                  graph->resample_lavr_opts);
295                     if ((ret = avfilter_graph_create_filter(&convert, filter,
296                                                             inst_name, scale_args,
297                                                             NULL, graph)) < 0)
298                         return ret;
299                     break;
300                 default:
301                     return AVERROR(EINVAL);
302                 }
303
304                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
305                     return ret;
306
307                 convert->filter->query_formats(convert);
308                 inlink  = convert->inputs[0];
309                 outlink = convert->outputs[0];
310                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats) ||
311                     !ff_merge_formats(outlink->in_formats, outlink->out_formats))
312                     ret |= AVERROR(ENOSYS);
313                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
314                     (!ff_merge_samplerates(inlink->in_samplerates,
315                                            inlink->out_samplerates) ||
316                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
317                                                inlink->out_channel_layouts)))
318                     ret |= AVERROR(ENOSYS);
319                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
320                     (!ff_merge_samplerates(outlink->in_samplerates,
321                                            outlink->out_samplerates) ||
322                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
323                                                outlink->out_channel_layouts)))
324                     ret |= AVERROR(ENOSYS);
325
326                 if (ret < 0) {
327                     av_log(log_ctx, AV_LOG_ERROR,
328                            "Impossible to convert between the formats supported by the filter "
329                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
330                     return ret;
331                 }
332             }
333         }
334     }
335
336     return 0;
337 }
338
339 static int pick_format(AVFilterLink *link)
340 {
341     if (!link || !link->in_formats)
342         return 0;
343
344     link->in_formats->format_count = 1;
345     link->format = link->in_formats->formats[0];
346
347     if (link->type == AVMEDIA_TYPE_AUDIO) {
348         if (!link->in_samplerates->format_count) {
349             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
350                    " the link between filters %s and %s.\n", link->src->name,
351                    link->dst->name);
352             return AVERROR(EINVAL);
353         }
354         link->in_samplerates->format_count = 1;
355         link->sample_rate = link->in_samplerates->formats[0];
356
357         if (!link->in_channel_layouts->nb_channel_layouts) {
358             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
359                    "the link between filters %s and %s.\n", link->src->name,
360                    link->dst->name);
361             return AVERROR(EINVAL);
362         }
363         link->in_channel_layouts->nb_channel_layouts = 1;
364         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
365     }
366
367     ff_formats_unref(&link->in_formats);
368     ff_formats_unref(&link->out_formats);
369     ff_formats_unref(&link->in_samplerates);
370     ff_formats_unref(&link->out_samplerates);
371     ff_channel_layouts_unref(&link->in_channel_layouts);
372     ff_channel_layouts_unref(&link->out_channel_layouts);
373
374     return 0;
375 }
376
377 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
378 do {                                                                   \
379     for (i = 0; i < filter->nb_inputs; i++) {                          \
380         AVFilterLink *link = filter->inputs[i];                        \
381         fmt_type fmt;                                                  \
382                                                                        \
383         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
384             continue;                                                  \
385         fmt = link->out_ ## list->var[0];                              \
386                                                                        \
387         for (j = 0; j < filter->nb_outputs; j++) {                     \
388             AVFilterLink *out_link = filter->outputs[j];               \
389             list_type *fmts;                                           \
390                                                                        \
391             if (link->type != out_link->type ||                        \
392                 out_link->in_ ## list->nb == 1)                        \
393                 continue;                                              \
394             fmts = out_link->in_ ## list;                              \
395                                                                        \
396             if (!out_link->in_ ## list->nb) {                          \
397                 add_format(&out_link->in_ ##list, fmt);                \
398                 break;                                                 \
399             }                                                          \
400                                                                        \
401             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
402                 if (fmts->var[k] == fmt) {                             \
403                     fmts->var[0]  = fmt;                               \
404                     fmts->nb = 1;                                      \
405                     ret = 1;                                           \
406                     break;                                             \
407                 }                                                      \
408         }                                                              \
409     }                                                                  \
410 } while (0)
411
412 static int reduce_formats_on_filter(AVFilterContext *filter)
413 {
414     int i, j, k, ret = 0;
415
416     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
417                    format_count, ff_add_format);
418     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
419                    format_count, ff_add_format);
420     REDUCE_FORMATS(uint64_t, AVFilterChannelLayouts, channel_layouts,
421                    channel_layouts, nb_channel_layouts, ff_add_channel_layout);
422
423     return ret;
424 }
425
426 static void reduce_formats(AVFilterGraph *graph)
427 {
428     int i, reduced;
429
430     do {
431         reduced = 0;
432
433         for (i = 0; i < graph->nb_filters; i++)
434             reduced |= reduce_formats_on_filter(graph->filters[i]);
435     } while (reduced);
436 }
437
438 static void swap_samplerates_on_filter(AVFilterContext *filter)
439 {
440     AVFilterLink *link = NULL;
441     int sample_rate;
442     int i, j;
443
444     for (i = 0; i < filter->nb_inputs; i++) {
445         link = filter->inputs[i];
446
447         if (link->type == AVMEDIA_TYPE_AUDIO &&
448             link->out_samplerates->format_count == 1)
449             break;
450     }
451     if (i == filter->nb_inputs)
452         return;
453
454     sample_rate = link->out_samplerates->formats[0];
455
456     for (i = 0; i < filter->nb_outputs; i++) {
457         AVFilterLink *outlink = filter->outputs[i];
458         int best_idx, best_diff = INT_MAX;
459
460         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
461             outlink->in_samplerates->format_count < 2)
462             continue;
463
464         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
465             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
466
467             if (diff < best_diff) {
468                 best_diff = diff;
469                 best_idx  = j;
470             }
471         }
472         FFSWAP(int, outlink->in_samplerates->formats[0],
473                outlink->in_samplerates->formats[best_idx]);
474     }
475 }
476
477 static void swap_samplerates(AVFilterGraph *graph)
478 {
479     int i;
480
481     for (i = 0; i < graph->nb_filters; i++)
482         swap_samplerates_on_filter(graph->filters[i]);
483 }
484
485 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
486 #define CH_FRONT_PAIR  (AV_CH_FRONT_LEFT           | AV_CH_FRONT_RIGHT)
487 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT          | AV_CH_STEREO_RIGHT)
488 #define CH_WIDE_PAIR   (AV_CH_WIDE_LEFT            | AV_CH_WIDE_RIGHT)
489 #define CH_SIDE_PAIR   (AV_CH_SIDE_LEFT            | AV_CH_SIDE_RIGHT)
490 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
491 #define CH_BACK_PAIR   (AV_CH_BACK_LEFT            | AV_CH_BACK_RIGHT)
492
493 /* allowable substitutions for channel pairs when comparing layouts,
494  * ordered by priority for both values */
495 static const uint64_t ch_subst[][2] = {
496     { CH_FRONT_PAIR,      CH_CENTER_PAIR     },
497     { CH_FRONT_PAIR,      CH_WIDE_PAIR       },
498     { CH_FRONT_PAIR,      AV_CH_FRONT_CENTER },
499     { CH_CENTER_PAIR,     CH_FRONT_PAIR      },
500     { CH_CENTER_PAIR,     CH_WIDE_PAIR       },
501     { CH_CENTER_PAIR,     AV_CH_FRONT_CENTER },
502     { CH_WIDE_PAIR,       CH_FRONT_PAIR      },
503     { CH_WIDE_PAIR,       CH_CENTER_PAIR     },
504     { CH_WIDE_PAIR,       AV_CH_FRONT_CENTER },
505     { AV_CH_FRONT_CENTER, CH_FRONT_PAIR      },
506     { AV_CH_FRONT_CENTER, CH_CENTER_PAIR     },
507     { AV_CH_FRONT_CENTER, CH_WIDE_PAIR       },
508     { CH_SIDE_PAIR,       CH_DIRECT_PAIR     },
509     { CH_SIDE_PAIR,       CH_BACK_PAIR       },
510     { CH_SIDE_PAIR,       AV_CH_BACK_CENTER  },
511     { CH_BACK_PAIR,       CH_DIRECT_PAIR     },
512     { CH_BACK_PAIR,       CH_SIDE_PAIR       },
513     { CH_BACK_PAIR,       AV_CH_BACK_CENTER  },
514     { AV_CH_BACK_CENTER,  CH_BACK_PAIR       },
515     { AV_CH_BACK_CENTER,  CH_DIRECT_PAIR     },
516     { AV_CH_BACK_CENTER,  CH_SIDE_PAIR       },
517 };
518
519 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
520 {
521     AVFilterLink *link = NULL;
522     int i, j, k;
523
524     for (i = 0; i < filter->nb_inputs; i++) {
525         link = filter->inputs[i];
526
527         if (link->type == AVMEDIA_TYPE_AUDIO &&
528             link->out_channel_layouts->nb_channel_layouts == 1)
529             break;
530     }
531     if (i == filter->nb_inputs)
532         return;
533
534     for (i = 0; i < filter->nb_outputs; i++) {
535         AVFilterLink *outlink = filter->outputs[i];
536         int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
537
538         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
539             outlink->in_channel_layouts->nb_channel_layouts < 2)
540             continue;
541
542         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
543             uint64_t  in_chlayout = link->out_channel_layouts->channel_layouts[0];
544             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
545             int  in_channels      = av_get_channel_layout_nb_channels(in_chlayout);
546             int out_channels      = av_get_channel_layout_nb_channels(out_chlayout);
547             int count_diff        = out_channels - in_channels;
548             int matched_channels, extra_channels;
549             int score = 0;
550
551             /* channel substitution */
552             for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
553                 uint64_t cmp0 = ch_subst[k][0];
554                 uint64_t cmp1 = ch_subst[k][1];
555                 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
556                     (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
557                     in_chlayout  &= ~cmp0;
558                     out_chlayout &= ~cmp1;
559                     /* add score for channel match, minus a deduction for
560                        having to do the substitution */
561                     score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
562                 }
563             }
564
565             /* no penalty for LFE channel mismatch */
566             if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
567                 (out_chlayout & AV_CH_LOW_FREQUENCY))
568                 score += 10;
569             in_chlayout  &= ~AV_CH_LOW_FREQUENCY;
570             out_chlayout &= ~AV_CH_LOW_FREQUENCY;
571
572             matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
573                                                                  out_chlayout);
574             extra_channels   = av_get_channel_layout_nb_channels(out_chlayout &
575                                                                  (~in_chlayout));
576             score += 10 * matched_channels - 5 * extra_channels;
577
578             if (score > best_score ||
579                 (count_diff < best_count_diff && score == best_score)) {
580                 best_score = score;
581                 best_idx   = j;
582                 best_count_diff = count_diff;
583             }
584         }
585         av_assert0(best_idx >= 0);
586         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
587                outlink->in_channel_layouts->channel_layouts[best_idx]);
588     }
589
590 }
591
592 static void swap_channel_layouts(AVFilterGraph *graph)
593 {
594     int i;
595
596     for (i = 0; i < graph->nb_filters; i++)
597         swap_channel_layouts_on_filter(graph->filters[i]);
598 }
599
600 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
601 {
602     AVFilterLink *link = NULL;
603     int format, bps;
604     int i, j;
605
606     for (i = 0; i < filter->nb_inputs; i++) {
607         link = filter->inputs[i];
608
609         if (link->type == AVMEDIA_TYPE_AUDIO &&
610             link->out_formats->format_count == 1)
611             break;
612     }
613     if (i == filter->nb_inputs)
614         return;
615
616     format = link->out_formats->formats[0];
617     bps    = av_get_bytes_per_sample(format);
618
619     for (i = 0; i < filter->nb_outputs; i++) {
620         AVFilterLink *outlink = filter->outputs[i];
621         int best_idx = -1, best_score = INT_MIN;
622
623         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
624             outlink->in_formats->format_count < 2)
625             continue;
626
627         for (j = 0; j < outlink->in_formats->format_count; j++) {
628             int out_format = outlink->in_formats->formats[j];
629             int out_bps    = av_get_bytes_per_sample(out_format);
630             int score;
631
632             if (av_get_packed_sample_fmt(out_format) == format ||
633                 av_get_planar_sample_fmt(out_format) == format) {
634                 best_idx   = j;
635                 break;
636             }
637
638             /* for s32 and float prefer double to prevent loss of information */
639             if (bps == 4 && out_bps == 8) {
640                 best_idx = j;
641                 break;
642             }
643
644             /* prefer closest higher or equal bps */
645             score = -abs(out_bps - bps);
646             if (out_bps >= bps)
647                 score += INT_MAX/2;
648
649             if (score > best_score) {
650                 best_score = score;
651                 best_idx   = j;
652             }
653         }
654         av_assert0(best_idx >= 0);
655         FFSWAP(int, outlink->in_formats->formats[0],
656                outlink->in_formats->formats[best_idx]);
657     }
658 }
659
660 static void swap_sample_fmts(AVFilterGraph *graph)
661 {
662     int i;
663
664     for (i = 0; i < graph->nb_filters; i++)
665         swap_sample_fmts_on_filter(graph->filters[i]);
666
667 }
668
669 static int pick_formats(AVFilterGraph *graph)
670 {
671     int i, j, ret;
672
673     for (i = 0; i < graph->nb_filters; i++) {
674         AVFilterContext *filter = graph->filters[i];
675
676         for (j = 0; j < filter->nb_inputs; j++)
677             if ((ret = pick_format(filter->inputs[j])) < 0)
678                 return ret;
679         for (j = 0; j < filter->nb_outputs; j++)
680             if ((ret = pick_format(filter->outputs[j])) < 0)
681                 return ret;
682     }
683     return 0;
684 }
685
686 /**
687  * Configure the formats of all the links in the graph.
688  */
689 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
690 {
691     int ret;
692
693     /* find supported formats from sub-filters, and merge along links */
694     if ((ret = query_formats(graph, log_ctx)) < 0)
695         return ret;
696
697     /* Once everything is merged, it's possible that we'll still have
698      * multiple valid media format choices. We try to minimize the amount
699      * of format conversion inside filters */
700     reduce_formats(graph);
701
702     /* for audio filters, ensure the best format, sample rate and channel layout
703      * is selected */
704     swap_sample_fmts(graph);
705     swap_samplerates(graph);
706     swap_channel_layouts(graph);
707
708     if ((ret = pick_formats(graph)) < 0)
709         return ret;
710
711     return 0;
712 }
713
714 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
715 {
716     AVFilterContext *f;
717     int i, j, ret;
718     int fifo_count = 0;
719
720     for (i = 0; i < graph->nb_filters; i++) {
721         f = graph->filters[i];
722
723         for (j = 0; j < f->nb_inputs; j++) {
724             AVFilterLink *link = f->inputs[j];
725             AVFilterContext *fifo_ctx;
726             AVFilter *fifo;
727             char name[32];
728
729             if (!link->dstpad->needs_fifo)
730                 continue;
731
732             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
733                    avfilter_get_by_name("fifo") :
734                    avfilter_get_by_name("afifo");
735
736             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
737
738             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
739                                                NULL, graph);
740             if (ret < 0)
741                 return ret;
742
743             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
744             if (ret < 0)
745                 return ret;
746         }
747     }
748
749     return 0;
750 }
751
752 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
753 {
754     int ret;
755
756     if ((ret = graph_check_validity(graphctx, log_ctx)))
757         return ret;
758     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
759         return ret;
760     if ((ret = graph_config_formats(graphctx, log_ctx)))
761         return ret;
762     if ((ret = graph_config_links(graphctx, log_ctx)))
763         return ret;
764
765     return 0;
766 }