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