]> git.sesse.net Git - ffmpeg/blob - libavfilter/avfiltergraph.c
4b7d1942757643c4c334ab926e3c5807e297e03f
[ffmpeg] / 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 FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <ctype.h>
24 #include <string.h>
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavcodec/avcodec.h" // avcodec_find_best_pix_fmt_of_2()
31 #include "avfilter.h"
32 #include "avfiltergraph.h"
33 #include "formats.h"
34 #include "internal.h"
35
36 #define OFFSET(x) offsetof(AVFilterGraph,x)
37
38 static const AVOption options[]={
39 {"scale_sws_opts"       , "default scale filter options"        , OFFSET(scale_sws_opts)        ,  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, 0 },
40 {"aresample_swr_opts"   , "default aresample filter options"    , OFFSET(aresample_swr_opts)    ,  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, 0 },
41 {0}
42 };
43
44
45 static const AVClass filtergraph_class = {
46     .class_name = "AVFilterGraph",
47     .item_name  = av_default_item_name,
48     .option     = options,
49     .version    = LIBAVUTIL_VERSION_INT,
50     .category   = AV_CLASS_CATEGORY_FILTER,
51 };
52
53 AVFilterGraph *avfilter_graph_alloc(void)
54 {
55     AVFilterGraph *ret = av_mallocz(sizeof(AVFilterGraph));
56     if (!ret)
57         return NULL;
58     ret->av_class = &filtergraph_class;
59     return ret;
60 }
61
62 void avfilter_graph_free(AVFilterGraph **graph)
63 {
64     if (!*graph)
65         return;
66     for (; (*graph)->filter_count > 0; (*graph)->filter_count--)
67         avfilter_free((*graph)->filters[(*graph)->filter_count - 1]);
68     av_freep(&(*graph)->sink_links);
69     av_freep(&(*graph)->scale_sws_opts);
70     av_freep(&(*graph)->aresample_swr_opts);
71     av_freep(&(*graph)->filters);
72     av_freep(graph);
73 }
74
75 int avfilter_graph_add_filter(AVFilterGraph *graph, AVFilterContext *filter)
76 {
77     AVFilterContext **filters = av_realloc(graph->filters,
78                                            sizeof(AVFilterContext*) * (graph->filter_count+1));
79     if (!filters)
80         return AVERROR(ENOMEM);
81
82     graph->filters = filters;
83     graph->filters[graph->filter_count++] = filter;
84
85     return 0;
86 }
87
88 int avfilter_graph_create_filter(AVFilterContext **filt_ctx, AVFilter *filt,
89                                  const char *name, const char *args, void *opaque,
90                                  AVFilterGraph *graph_ctx)
91 {
92     int ret;
93
94     if ((ret = avfilter_open(filt_ctx, filt, name)) < 0)
95         goto fail;
96     if ((ret = avfilter_init_filter(*filt_ctx, args, opaque)) < 0)
97         goto fail;
98     if ((ret = avfilter_graph_add_filter(graph_ctx, *filt_ctx)) < 0)
99         goto fail;
100     return 0;
101
102 fail:
103     if (*filt_ctx)
104         avfilter_free(*filt_ctx);
105     *filt_ctx = NULL;
106     return ret;
107 }
108
109 void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags)
110 {
111     graph->disable_auto_convert = flags;
112 }
113
114 /**
115  * Check for the validity of graph.
116  *
117  * A graph is considered valid if all its input and output pads are
118  * connected.
119  *
120  * @return 0 in case of success, a negative value otherwise
121  */
122 static int graph_check_validity(AVFilterGraph *graph, AVClass *log_ctx)
123 {
124     AVFilterContext *filt;
125     int i, j;
126
127     for (i = 0; i < graph->filter_count; i++) {
128         const AVFilterPad *pad;
129         filt = graph->filters[i];
130
131         for (j = 0; j < filt->nb_inputs; j++) {
132             if (!filt->inputs[j] || !filt->inputs[j]->src) {
133                 pad = &filt->input_pads[j];
134                 av_log(log_ctx, AV_LOG_ERROR,
135                        "Input pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any source\n",
136                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
137                 return AVERROR(EINVAL);
138             }
139         }
140
141         for (j = 0; j < filt->nb_outputs; j++) {
142             if (!filt->outputs[j] || !filt->outputs[j]->dst) {
143                 pad = &filt->output_pads[j];
144                 av_log(log_ctx, AV_LOG_ERROR,
145                        "Output pad \"%s\" with type %s of the filter instance \"%s\" of %s not connected to any destination\n",
146                        pad->name, av_get_media_type_string(pad->type), filt->name, filt->filter->name);
147                 return AVERROR(EINVAL);
148             }
149         }
150     }
151
152     return 0;
153 }
154
155 /**
156  * Configure all the links of graphctx.
157  *
158  * @return 0 in case of success, a negative value otherwise
159  */
160 static int graph_config_links(AVFilterGraph *graph, AVClass *log_ctx)
161 {
162     AVFilterContext *filt;
163     int i, ret;
164
165     for (i=0; i < graph->filter_count; i++) {
166         filt = graph->filters[i];
167
168         if (!filt->nb_outputs) {
169             if ((ret = avfilter_config_links(filt)))
170                 return ret;
171         }
172     }
173
174     return 0;
175 }
176
177 AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, char *name)
178 {
179     int i;
180
181     for (i = 0; i < graph->filter_count; i++)
182         if (graph->filters[i]->name && !strcmp(name, graph->filters[i]->name))
183             return graph->filters[i];
184
185     return NULL;
186 }
187
188 static void sanitize_channel_layouts(void *log, AVFilterChannelLayouts *l)
189 {
190     if (!l)
191         return;
192     if (l->nb_channel_layouts) {
193         if (l->all_layouts || l->all_counts)
194             av_log(log, AV_LOG_WARNING, "All layouts set on non-empty list\n");
195         l->all_layouts = l->all_counts = 0;
196     } else {
197         if (l->all_counts && !l->all_layouts)
198             av_log(log, AV_LOG_WARNING, "All counts without all layouts\n");
199         l->all_layouts = 1;
200     }
201 }
202
203 static int filter_query_formats(AVFilterContext *ctx)
204 {
205     int ret, i;
206     AVFilterFormats *formats;
207     AVFilterChannelLayouts *chlayouts;
208     AVFilterFormats *samplerates;
209     enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :
210                             ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :
211                             AVMEDIA_TYPE_VIDEO;
212
213     if ((ret = ctx->filter->query_formats(ctx)) < 0) {
214         av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",
215                ctx->name, av_err2str(ret));
216         return ret;
217     }
218
219     for (i = 0; i < ctx->nb_inputs; i++)
220         sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);
221     for (i = 0; i < ctx->nb_outputs; i++)
222         sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);
223
224     formats = ff_all_formats(type);
225     if (!formats)
226         return AVERROR(ENOMEM);
227     ff_set_common_formats(ctx, formats);
228     if (type == AVMEDIA_TYPE_AUDIO) {
229         samplerates = ff_all_samplerates();
230         if (!samplerates)
231             return AVERROR(ENOMEM);
232         ff_set_common_samplerates(ctx, samplerates);
233         chlayouts = ff_all_channel_layouts();
234         if (!chlayouts)
235             return AVERROR(ENOMEM);
236         ff_set_common_channel_layouts(ctx, chlayouts);
237     }
238     return 0;
239 }
240
241 static int insert_conv_filter(AVFilterGraph *graph, AVFilterLink *link,
242                               const char *filt_name, const char *filt_args)
243 {
244     static int auto_count = 0, ret;
245     char inst_name[32];
246     AVFilterContext *filt_ctx;
247
248     if (graph->disable_auto_convert) {
249         av_log(NULL, AV_LOG_ERROR,
250                "The filters '%s' and '%s' do not have a common format "
251                "and automatic conversion is disabled.\n",
252                link->src->name, link->dst->name);
253         return AVERROR(EINVAL);
254     }
255
256     snprintf(inst_name, sizeof(inst_name), "auto-inserted %s %d",
257             filt_name, auto_count++);
258
259     if ((ret = avfilter_graph_create_filter(&filt_ctx,
260                                             avfilter_get_by_name(filt_name),
261                                             inst_name, filt_args, NULL, graph)) < 0)
262         return ret;
263     if ((ret = avfilter_insert_filter(link, filt_ctx, 0, 0)) < 0)
264         return ret;
265
266     filter_query_formats(filt_ctx);
267
268     if ( ((link = filt_ctx-> inputs[0]) &&
269            !ff_merge_formats(link->in_formats, link->out_formats)) ||
270          ((link = filt_ctx->outputs[0]) &&
271            !ff_merge_formats(link->in_formats, link->out_formats))
272        ) {
273         av_log(NULL, AV_LOG_ERROR,
274                "Impossible to convert between the formats supported by the filter "
275                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
276         return AVERROR(EINVAL);
277     }
278
279     if (link->type == AVMEDIA_TYPE_AUDIO &&
280          (((link = filt_ctx-> inputs[0]) &&
281            !ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts)) ||
282          ((link = filt_ctx->outputs[0]) &&
283            !ff_merge_channel_layouts(link->in_channel_layouts, link->out_channel_layouts)))
284        ) {
285         av_log(NULL, AV_LOG_ERROR,
286                "Impossible to convert between the channel layouts formats supported by the filter "
287                "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
288         return AVERROR(EINVAL);
289     }
290
291     return 0;
292 }
293
294 static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
295 {
296     int i, j, ret;
297 #if 0
298     char filt_args[128];
299     AVFilterFormats *formats;
300     AVFilterChannelLayouts *chlayouts;
301     AVFilterFormats *samplerates;
302 #endif
303     int scaler_count = 0, resampler_count = 0;
304
305     for (j = 0; j < 2; j++) {
306     /* ask all the sub-filters for their supported media formats */
307     for (i = 0; i < graph->filter_count; i++) {
308         /* Call query_formats on sources first.
309            This is a temporary workaround for amerge,
310            until format renegociation is implemented. */
311         if (!graph->filters[i]->nb_inputs == j)
312             continue;
313         if (graph->filters[i]->filter->query_formats)
314             ret = filter_query_formats(graph->filters[i]);
315         else
316             ret = ff_default_query_formats(graph->filters[i]);
317         if (ret < 0)
318             return ret;
319     }
320     }
321
322     /* go through and merge as many format lists as possible */
323     for (i = 0; i < graph->filter_count; i++) {
324         AVFilterContext *filter = graph->filters[i];
325
326         for (j = 0; j < filter->nb_inputs; j++) {
327             AVFilterLink *link = filter->inputs[j];
328 #if 0
329             if (!link) continue;
330
331             if (!link->in_formats || !link->out_formats)
332                 return AVERROR(EINVAL);
333
334             if (link->type == AVMEDIA_TYPE_VIDEO &&
335                 !ff_merge_formats(link->in_formats, link->out_formats)) {
336
337                 /* couldn't merge format lists, auto-insert scale filter */
338                 snprintf(filt_args, sizeof(filt_args), "0:0:%s",
339                          graph->scale_sws_opts);
340                 if (ret = insert_conv_filter(graph, link, "scale", filt_args))
341                     return ret;
342             }
343             else if (link->type == AVMEDIA_TYPE_AUDIO) {
344                 if (!link->in_channel_layouts || !link->out_channel_layouts)
345                     return AVERROR(EINVAL);
346
347                 /* Merge all three list before checking: that way, in all
348                  * three categories, aconvert will use a common format
349                  * whenever possible. */
350                 formats     = ff_merge_formats(link->in_formats,   link->out_formats);
351                 chlayouts   = ff_merge_channel_layouts(link->in_channel_layouts  , link->out_channel_layouts);
352                 samplerates = ff_merge_samplerates    (link->in_samplerates, link->out_samplerates);
353
354                 if (!formats || !chlayouts || !samplerates)
355                     if (ret = insert_conv_filter(graph, link, "aresample", NULL))
356                        return ret;
357 #else
358             int convert_needed = 0;
359
360             if (!link)
361                 continue;
362
363             if (link->in_formats != link->out_formats &&
364                 !ff_merge_formats(link->in_formats,
365                                         link->out_formats))
366                 convert_needed = 1;
367             if (link->type == AVMEDIA_TYPE_AUDIO) {
368                 if (link->in_channel_layouts != link->out_channel_layouts &&
369                     !ff_merge_channel_layouts(link->in_channel_layouts,
370                                               link->out_channel_layouts))
371                     convert_needed = 1;
372                 if (link->in_samplerates != link->out_samplerates &&
373                     !ff_merge_samplerates(link->in_samplerates,
374                                           link->out_samplerates))
375                     convert_needed = 1;
376             }
377
378             if (convert_needed) {
379                 AVFilterContext *convert;
380                 AVFilter *filter;
381                 AVFilterLink *inlink, *outlink;
382                 char scale_args[256];
383                 char inst_name[30];
384
385                 /* couldn't merge format lists. auto-insert conversion filter */
386                 switch (link->type) {
387                 case AVMEDIA_TYPE_VIDEO:
388                     if (!(filter = avfilter_get_by_name("scale"))) {
389                         av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "
390                                "not present, cannot convert pixel formats.\n");
391                         return AVERROR(EINVAL);
392                     }
393
394                     snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",
395                              scaler_count++);
396                     if (graph->scale_sws_opts)
397                         snprintf(scale_args, sizeof(scale_args), "0:0:%s", graph->scale_sws_opts);
398                     else
399                         snprintf(scale_args, sizeof(scale_args), "0:0");
400
401                     if ((ret = avfilter_graph_create_filter(&convert, filter,
402                                                             inst_name, scale_args, NULL,
403                                                             graph)) < 0)
404                         return ret;
405                     break;
406                 case AVMEDIA_TYPE_AUDIO:
407                     if (!(filter = avfilter_get_by_name("aresample"))) {
408                         av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "
409                                "not present, cannot convert audio formats.\n");
410                         return AVERROR(EINVAL);
411                     }
412
413                     snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",
414                              resampler_count++);
415                     if ((ret = avfilter_graph_create_filter(&convert, filter,
416                                                             inst_name, graph->aresample_swr_opts, NULL, graph)) < 0)
417                         return ret;
418                     break;
419                 default:
420                     return AVERROR(EINVAL);
421                 }
422
423                 if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)
424                     return ret;
425
426                 filter_query_formats(convert);
427                 inlink  = convert->inputs[0];
428                 outlink = convert->outputs[0];
429                 if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats) ||
430                     !ff_merge_formats(outlink->in_formats, outlink->out_formats))
431                     ret |= AVERROR(ENOSYS);
432                 if (inlink->type == AVMEDIA_TYPE_AUDIO &&
433                     (!ff_merge_samplerates(inlink->in_samplerates,
434                                            inlink->out_samplerates) ||
435                      !ff_merge_channel_layouts(inlink->in_channel_layouts,
436                                                inlink->out_channel_layouts)))
437                     ret |= AVERROR(ENOSYS);
438                 if (outlink->type == AVMEDIA_TYPE_AUDIO &&
439                     (!ff_merge_samplerates(outlink->in_samplerates,
440                                            outlink->out_samplerates) ||
441                      !ff_merge_channel_layouts(outlink->in_channel_layouts,
442                                                outlink->out_channel_layouts)))
443                     ret |= AVERROR(ENOSYS);
444
445                 if (ret < 0) {
446                     av_log(log_ctx, AV_LOG_ERROR,
447                            "Impossible to convert between the formats supported by the filter "
448                            "'%s' and the filter '%s'\n", link->src->name, link->dst->name);
449                     return ret;
450                 }
451 #endif
452             }
453         }
454     }
455
456     return 0;
457 }
458
459 static int pick_format(AVFilterLink *link, AVFilterLink *ref)
460 {
461     if (!link || !link->in_formats)
462         return 0;
463
464     if (link->type == AVMEDIA_TYPE_VIDEO) {
465         if(ref && ref->type == AVMEDIA_TYPE_VIDEO){
466             int has_alpha= av_pix_fmt_desc_get(ref->format)->nb_components % 2 == 0;
467             enum AVPixelFormat best= AV_PIX_FMT_NONE;
468             int i;
469             for (i=0; i<link->in_formats->format_count; i++) {
470                 enum AVPixelFormat p = link->in_formats->formats[i];
471                 best= avcodec_find_best_pix_fmt_of_2(best, p, ref->format, has_alpha, NULL);
472             }
473             av_log(link->src,AV_LOG_DEBUG, "picking %s out of %d ref:%s alpha:%d\n",
474                    av_get_pix_fmt_name(best), link->in_formats->format_count,
475                    av_get_pix_fmt_name(ref->format), has_alpha);
476             link->in_formats->formats[0] = best;
477         }
478     }
479
480     link->in_formats->format_count = 1;
481     link->format = link->in_formats->formats[0];
482
483     if (link->type == AVMEDIA_TYPE_AUDIO) {
484         if (!link->in_samplerates->format_count) {
485             av_log(link->src, AV_LOG_ERROR, "Cannot select sample rate for"
486                    " the link between filters %s and %s.\n", link->src->name,
487                    link->dst->name);
488             return AVERROR(EINVAL);
489         }
490         link->in_samplerates->format_count = 1;
491         link->sample_rate = link->in_samplerates->formats[0];
492
493         if (link->in_channel_layouts->all_layouts) {
494             av_log(link->src, AV_LOG_ERROR, "Cannot select channel layout for"
495                    "the link between filters %s and %s.\n", link->src->name,
496                    link->dst->name);
497             return AVERROR(EINVAL);
498         }
499         link->in_channel_layouts->nb_channel_layouts = 1;
500         link->channel_layout = link->in_channel_layouts->channel_layouts[0];
501         if ((link->channels = FF_LAYOUT2COUNT(link->channel_layout)))
502             link->channel_layout = 0;
503         else
504             link->channels = av_get_channel_layout_nb_channels(link->channel_layout);
505     }
506
507     ff_formats_unref(&link->in_formats);
508     ff_formats_unref(&link->out_formats);
509     ff_formats_unref(&link->in_samplerates);
510     ff_formats_unref(&link->out_samplerates);
511     ff_channel_layouts_unref(&link->in_channel_layouts);
512     ff_channel_layouts_unref(&link->out_channel_layouts);
513
514     return 0;
515 }
516
517 #define REDUCE_FORMATS(fmt_type, list_type, list, var, nb, add_format) \
518 do {                                                                   \
519     for (i = 0; i < filter->nb_inputs; i++) {                          \
520         AVFilterLink *link = filter->inputs[i];                        \
521         fmt_type fmt;                                                  \
522                                                                        \
523         if (!link->out_ ## list || link->out_ ## list->nb != 1)        \
524             continue;                                                  \
525         fmt = link->out_ ## list->var[0];                              \
526                                                                        \
527         for (j = 0; j < filter->nb_outputs; j++) {                     \
528             AVFilterLink *out_link = filter->outputs[j];               \
529             list_type *fmts;                                           \
530                                                                        \
531             if (link->type != out_link->type ||                        \
532                 out_link->in_ ## list->nb == 1)                        \
533                 continue;                                              \
534             fmts = out_link->in_ ## list;                              \
535                                                                        \
536             if (!out_link->in_ ## list->nb) {                          \
537                 add_format(&out_link->in_ ##list, fmt);                \
538                 break;                                                 \
539             }                                                          \
540                                                                        \
541             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
542                 if (fmts->var[k] == fmt) {                             \
543                     fmts->var[0]  = fmt;                               \
544                     fmts->nb = 1;                                      \
545                     ret = 1;                                           \
546                     break;                                             \
547                 }                                                      \
548         }                                                              \
549     }                                                                  \
550 } while (0)
551
552 static int reduce_formats_on_filter(AVFilterContext *filter)
553 {
554     int i, j, k, ret = 0;
555
556     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
557                    format_count, ff_add_format);
558     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
559                    format_count, ff_add_format);
560
561     /* reduce channel layouts */
562     for (i = 0; i < filter->nb_inputs; i++) {
563         AVFilterLink *inlink = filter->inputs[i];
564         uint64_t fmt;
565
566         if (!inlink->out_channel_layouts ||
567             inlink->out_channel_layouts->nb_channel_layouts != 1)
568             continue;
569         fmt = inlink->out_channel_layouts->channel_layouts[0];
570
571         for (j = 0; j < filter->nb_outputs; j++) {
572             AVFilterLink *outlink = filter->outputs[j];
573             AVFilterChannelLayouts *fmts;
574
575             fmts = outlink->in_channel_layouts;
576             if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
577                 continue;
578
579             if (fmts->all_layouts) {
580                 /* Turn the infinite list into a singleton */
581                 fmts->all_layouts = fmts->all_counts  = 0;
582                 ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
583                 break;
584             }
585
586             for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
587                 if (fmts->channel_layouts[k] == fmt) {
588                     fmts->channel_layouts[0]  = fmt;
589                     fmts->nb_channel_layouts = 1;
590                     ret = 1;
591                     break;
592                 }
593             }
594         }
595     }
596
597     return ret;
598 }
599
600 static void reduce_formats(AVFilterGraph *graph)
601 {
602     int i, reduced;
603
604     do {
605         reduced = 0;
606
607         for (i = 0; i < graph->filter_count; i++)
608             reduced |= reduce_formats_on_filter(graph->filters[i]);
609     } while (reduced);
610 }
611
612 static void swap_samplerates_on_filter(AVFilterContext *filter)
613 {
614     AVFilterLink *link = NULL;
615     int sample_rate;
616     int i, j;
617
618     for (i = 0; i < filter->nb_inputs; i++) {
619         link = filter->inputs[i];
620
621         if (link->type == AVMEDIA_TYPE_AUDIO &&
622             link->out_samplerates->format_count == 1)
623             break;
624     }
625     if (i == filter->nb_inputs)
626         return;
627
628     sample_rate = link->out_samplerates->formats[0];
629
630     for (i = 0; i < filter->nb_outputs; i++) {
631         AVFilterLink *outlink = filter->outputs[i];
632         int best_idx, best_diff = INT_MAX;
633
634         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
635             outlink->in_samplerates->format_count < 2)
636             continue;
637
638         for (j = 0; j < outlink->in_samplerates->format_count; j++) {
639             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
640
641             if (diff < best_diff) {
642                 best_diff = diff;
643                 best_idx  = j;
644             }
645         }
646         FFSWAP(int, outlink->in_samplerates->formats[0],
647                outlink->in_samplerates->formats[best_idx]);
648     }
649 }
650
651 static void swap_samplerates(AVFilterGraph *graph)
652 {
653     int i;
654
655     for (i = 0; i < graph->filter_count; i++)
656         swap_samplerates_on_filter(graph->filters[i]);
657 }
658
659 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
660 #define CH_FRONT_PAIR  (AV_CH_FRONT_LEFT           | AV_CH_FRONT_RIGHT)
661 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT          | AV_CH_STEREO_RIGHT)
662 #define CH_WIDE_PAIR   (AV_CH_WIDE_LEFT            | AV_CH_WIDE_RIGHT)
663 #define CH_SIDE_PAIR   (AV_CH_SIDE_LEFT            | AV_CH_SIDE_RIGHT)
664 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
665 #define CH_BACK_PAIR   (AV_CH_BACK_LEFT            | AV_CH_BACK_RIGHT)
666
667 /* allowable substitutions for channel pairs when comparing layouts,
668  * ordered by priority for both values */
669 static const uint64_t ch_subst[][2] = {
670     { CH_FRONT_PAIR,      CH_CENTER_PAIR     },
671     { CH_FRONT_PAIR,      CH_WIDE_PAIR       },
672     { CH_FRONT_PAIR,      AV_CH_FRONT_CENTER },
673     { CH_CENTER_PAIR,     CH_FRONT_PAIR      },
674     { CH_CENTER_PAIR,     CH_WIDE_PAIR       },
675     { CH_CENTER_PAIR,     AV_CH_FRONT_CENTER },
676     { CH_WIDE_PAIR,       CH_FRONT_PAIR      },
677     { CH_WIDE_PAIR,       CH_CENTER_PAIR     },
678     { CH_WIDE_PAIR,       AV_CH_FRONT_CENTER },
679     { AV_CH_FRONT_CENTER, CH_FRONT_PAIR      },
680     { AV_CH_FRONT_CENTER, CH_CENTER_PAIR     },
681     { AV_CH_FRONT_CENTER, CH_WIDE_PAIR       },
682     { CH_SIDE_PAIR,       CH_DIRECT_PAIR     },
683     { CH_SIDE_PAIR,       CH_BACK_PAIR       },
684     { CH_SIDE_PAIR,       AV_CH_BACK_CENTER  },
685     { CH_BACK_PAIR,       CH_DIRECT_PAIR     },
686     { CH_BACK_PAIR,       CH_SIDE_PAIR       },
687     { CH_BACK_PAIR,       AV_CH_BACK_CENTER  },
688     { AV_CH_BACK_CENTER,  CH_BACK_PAIR       },
689     { AV_CH_BACK_CENTER,  CH_DIRECT_PAIR     },
690     { AV_CH_BACK_CENTER,  CH_SIDE_PAIR       },
691 };
692
693 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
694 {
695     AVFilterLink *link = NULL;
696     int i, j, k;
697
698     for (i = 0; i < filter->nb_inputs; i++) {
699         link = filter->inputs[i];
700
701         if (link->type == AVMEDIA_TYPE_AUDIO &&
702             link->out_channel_layouts->nb_channel_layouts == 1)
703             break;
704     }
705     if (i == filter->nb_inputs)
706         return;
707
708     for (i = 0; i < filter->nb_outputs; i++) {
709         AVFilterLink *outlink = filter->outputs[i];
710         int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
711
712         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
713             outlink->in_channel_layouts->nb_channel_layouts < 2)
714             continue;
715
716         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
717             uint64_t  in_chlayout = link->out_channel_layouts->channel_layouts[0];
718             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
719             int  in_channels      = av_get_channel_layout_nb_channels(in_chlayout);
720             int out_channels      = av_get_channel_layout_nb_channels(out_chlayout);
721             int count_diff        = out_channels - in_channels;
722             int matched_channels, extra_channels;
723             int score = 100000;
724
725             if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
726                 /* Compute score in case the input or output layout encodes
727                    a channel count; in this case the score is not altered by
728                    the computation afterwards, as in_chlayout and
729                    out_chlayout have both been set to 0 */
730                 if (FF_LAYOUT2COUNT(in_chlayout))
731                     in_channels = FF_LAYOUT2COUNT(in_chlayout);
732                 if (FF_LAYOUT2COUNT(out_chlayout))
733                     out_channels = FF_LAYOUT2COUNT(out_chlayout);
734                 score -= 10000 + FFABS(out_channels - in_channels) +
735                          (in_channels > out_channels ? 10000 : 0);
736                 in_chlayout = out_chlayout = 0;
737                 /* Let the remaining computation run, even if the score
738                    value is not altered */
739             }
740
741             /* channel substitution */
742             for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
743                 uint64_t cmp0 = ch_subst[k][0];
744                 uint64_t cmp1 = ch_subst[k][1];
745                 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
746                     (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
747                     in_chlayout  &= ~cmp0;
748                     out_chlayout &= ~cmp1;
749                     /* add score for channel match, minus a deduction for
750                        having to do the substitution */
751                     score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
752                 }
753             }
754
755             /* no penalty for LFE channel mismatch */
756             if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
757                 (out_chlayout & AV_CH_LOW_FREQUENCY))
758                 score += 10;
759             in_chlayout  &= ~AV_CH_LOW_FREQUENCY;
760             out_chlayout &= ~AV_CH_LOW_FREQUENCY;
761
762             matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
763                                                                  out_chlayout);
764             extra_channels   = av_get_channel_layout_nb_channels(out_chlayout &
765                                                                  (~in_chlayout));
766             score += 10 * matched_channels - 5 * extra_channels;
767
768             if (score > best_score ||
769                 (count_diff < best_count_diff && score == best_score)) {
770                 best_score = score;
771                 best_idx   = j;
772                 best_count_diff = count_diff;
773             }
774         }
775         av_assert0(best_idx >= 0);
776         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
777                outlink->in_channel_layouts->channel_layouts[best_idx]);
778     }
779
780 }
781
782 static void swap_channel_layouts(AVFilterGraph *graph)
783 {
784     int i;
785
786     for (i = 0; i < graph->filter_count; i++)
787         swap_channel_layouts_on_filter(graph->filters[i]);
788 }
789
790 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
791 {
792     AVFilterLink *link = NULL;
793     int format, bps;
794     int i, j;
795
796     for (i = 0; i < filter->nb_inputs; i++) {
797         link = filter->inputs[i];
798
799         if (link->type == AVMEDIA_TYPE_AUDIO &&
800             link->out_formats->format_count == 1)
801             break;
802     }
803     if (i == filter->nb_inputs)
804         return;
805
806     format = link->out_formats->formats[0];
807     bps    = av_get_bytes_per_sample(format);
808
809     for (i = 0; i < filter->nb_outputs; i++) {
810         AVFilterLink *outlink = filter->outputs[i];
811         int best_idx = -1, best_score = INT_MIN;
812
813         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
814             outlink->in_formats->format_count < 2)
815             continue;
816
817         for (j = 0; j < outlink->in_formats->format_count; j++) {
818             int out_format = outlink->in_formats->formats[j];
819             int out_bps    = av_get_bytes_per_sample(out_format);
820             int score;
821
822             if (av_get_packed_sample_fmt(out_format) == format ||
823                 av_get_planar_sample_fmt(out_format) == format) {
824                 best_idx   = j;
825                 break;
826             }
827
828             /* for s32 and float prefer double to prevent loss of information */
829             if (bps == 4 && out_bps == 8) {
830                 best_idx = j;
831                 break;
832             }
833
834             /* prefer closest higher or equal bps */
835             score = -abs(out_bps - bps);
836             if (out_bps >= bps)
837                 score += INT_MAX/2;
838
839             if (score > best_score) {
840                 best_score = score;
841                 best_idx   = j;
842             }
843         }
844         av_assert0(best_idx >= 0);
845         FFSWAP(int, outlink->in_formats->formats[0],
846                outlink->in_formats->formats[best_idx]);
847     }
848 }
849
850 static void swap_sample_fmts(AVFilterGraph *graph)
851 {
852     int i;
853
854     for (i = 0; i < graph->filter_count; i++)
855         swap_sample_fmts_on_filter(graph->filters[i]);
856
857 }
858
859 static int pick_formats(AVFilterGraph *graph)
860 {
861     int i, j, ret;
862     int change;
863
864     do{
865         change = 0;
866         for (i = 0; i < graph->filter_count; i++) {
867             AVFilterContext *filter = graph->filters[i];
868             if (filter->nb_inputs){
869                 for (j = 0; j < filter->nb_inputs; j++){
870                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->format_count == 1) {
871                         if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
872                             return ret;
873                         change = 1;
874                     }
875                 }
876             }
877             if (filter->nb_outputs){
878                 for (j = 0; j < filter->nb_outputs; j++){
879                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->format_count == 1) {
880                         if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
881                             return ret;
882                         change = 1;
883                     }
884                 }
885             }
886             if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
887                 for (j = 0; j < filter->nb_outputs; j++) {
888                     if(filter->outputs[j]->format<0) {
889                         if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
890                             return ret;
891                         change = 1;
892                     }
893                 }
894             }
895         }
896     }while(change);
897
898     for (i = 0; i < graph->filter_count; i++) {
899         AVFilterContext *filter = graph->filters[i];
900
901         for (j = 0; j < filter->nb_inputs; j++)
902             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
903                 return ret;
904         for (j = 0; j < filter->nb_outputs; j++)
905             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
906                 return ret;
907     }
908     return 0;
909 }
910
911 /**
912  * Configure the formats of all the links in the graph.
913  */
914 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
915 {
916     int ret;
917
918     /* find supported formats from sub-filters, and merge along links */
919     if ((ret = query_formats(graph, log_ctx)) < 0)
920         return ret;
921
922     /* Once everything is merged, it's possible that we'll still have
923      * multiple valid media format choices. We try to minimize the amount
924      * of format conversion inside filters */
925     reduce_formats(graph);
926
927     /* for audio filters, ensure the best format, sample rate and channel layout
928      * is selected */
929     swap_sample_fmts(graph);
930     swap_samplerates(graph);
931     swap_channel_layouts(graph);
932
933     if ((ret = pick_formats(graph)) < 0)
934         return ret;
935
936     return 0;
937 }
938
939 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
940                                              AVClass *log_ctx)
941 {
942     unsigned i, j;
943     int sink_links_count = 0, n = 0;
944     AVFilterContext *f;
945     AVFilterLink **sinks;
946
947     for (i = 0; i < graph->filter_count; i++) {
948         f = graph->filters[i];
949         for (j = 0; j < f->nb_inputs; j++) {
950             f->inputs[j]->graph     = graph;
951             f->inputs[j]->age_index = -1;
952         }
953         for (j = 0; j < f->nb_outputs; j++) {
954             f->outputs[j]->graph    = graph;
955             f->outputs[j]->age_index= -1;
956         }
957         if (!f->nb_outputs) {
958             if (f->nb_inputs > INT_MAX - sink_links_count)
959                 return AVERROR(EINVAL);
960             sink_links_count += f->nb_inputs;
961         }
962     }
963     sinks = av_calloc(sink_links_count, sizeof(*sinks));
964     if (!sinks)
965         return AVERROR(ENOMEM);
966     for (i = 0; i < graph->filter_count; i++) {
967         f = graph->filters[i];
968         if (!f->nb_outputs) {
969             for (j = 0; j < f->nb_inputs; j++) {
970                 sinks[n] = f->inputs[j];
971                 f->inputs[j]->age_index = n++;
972             }
973         }
974     }
975     av_assert0(n == sink_links_count);
976     graph->sink_links       = sinks;
977     graph->sink_links_count = sink_links_count;
978     return 0;
979 }
980
981 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
982 {
983     AVFilterContext *f;
984     int i, j, ret;
985     int fifo_count = 0;
986
987     for (i = 0; i < graph->filter_count; i++) {
988         f = graph->filters[i];
989
990         for (j = 0; j < f->nb_inputs; j++) {
991             AVFilterLink *link = f->inputs[j];
992             AVFilterContext *fifo_ctx;
993             AVFilter *fifo;
994             char name[32];
995
996             if (!link->dstpad->needs_fifo)
997                 continue;
998
999             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
1000                    avfilter_get_by_name("fifo") :
1001                    avfilter_get_by_name("afifo");
1002
1003             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
1004
1005             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
1006                                                NULL, graph);
1007             if (ret < 0)
1008                 return ret;
1009
1010             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
1011             if (ret < 0)
1012                 return ret;
1013         }
1014     }
1015
1016     return 0;
1017 }
1018
1019 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
1020 {
1021     int ret;
1022
1023     if ((ret = graph_check_validity(graphctx, log_ctx)))
1024         return ret;
1025     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
1026         return ret;
1027     if ((ret = graph_config_formats(graphctx, log_ctx)))
1028         return ret;
1029     if ((ret = graph_config_links(graphctx, log_ctx)))
1030         return ret;
1031     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
1032         return ret;
1033
1034     return 0;
1035 }
1036
1037 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
1038 {
1039     int i, r = AVERROR(ENOSYS);
1040
1041     if(!graph)
1042         return r;
1043
1044     if((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
1045         r=avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
1046         if(r != AVERROR(ENOSYS))
1047             return r;
1048     }
1049
1050     if(res_len && res)
1051         res[0]= 0;
1052
1053     for (i = 0; i < graph->filter_count; i++) {
1054         AVFilterContext *filter = graph->filters[i];
1055         if(!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)){
1056             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
1057             if(r != AVERROR(ENOSYS)) {
1058                 if((flags & AVFILTER_CMD_FLAG_ONE) || r<0)
1059                     return r;
1060             }
1061         }
1062     }
1063
1064     return r;
1065 }
1066
1067 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
1068 {
1069     int i;
1070
1071     if(!graph)
1072         return 0;
1073
1074     for (i = 0; i < graph->filter_count; i++) {
1075         AVFilterContext *filter = graph->filters[i];
1076         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
1077             AVFilterCommand **queue = &filter->command_queue, *next;
1078             while (*queue && (*queue)->time <= ts)
1079                 queue = &(*queue)->next;
1080             next = *queue;
1081             *queue = av_mallocz(sizeof(AVFilterCommand));
1082             (*queue)->command = av_strdup(command);
1083             (*queue)->arg     = av_strdup(arg);
1084             (*queue)->time    = ts;
1085             (*queue)->flags   = flags;
1086             (*queue)->next    = next;
1087             if(flags & AVFILTER_CMD_FLAG_ONE)
1088                 return 0;
1089         }
1090     }
1091
1092     return 0;
1093 }
1094
1095 static void heap_bubble_up(AVFilterGraph *graph,
1096                            AVFilterLink *link, int index)
1097 {
1098     AVFilterLink **links = graph->sink_links;
1099
1100     while (index) {
1101         int parent = (index - 1) >> 1;
1102         if (links[parent]->current_pts >= link->current_pts)
1103             break;
1104         links[index] = links[parent];
1105         links[index]->age_index = index;
1106         index = parent;
1107     }
1108     links[index] = link;
1109     link->age_index = index;
1110 }
1111
1112 static void heap_bubble_down(AVFilterGraph *graph,
1113                              AVFilterLink *link, int index)
1114 {
1115     AVFilterLink **links = graph->sink_links;
1116
1117     while (1) {
1118         int child = 2 * index + 1;
1119         if (child >= graph->sink_links_count)
1120             break;
1121         if (child + 1 < graph->sink_links_count &&
1122             links[child + 1]->current_pts < links[child]->current_pts)
1123             child++;
1124         if (link->current_pts < links[child]->current_pts)
1125             break;
1126         links[index] = links[child];
1127         links[index]->age_index = index;
1128         index = child;
1129     }
1130     links[index] = link;
1131     link->age_index = index;
1132 }
1133
1134 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
1135 {
1136     heap_bubble_up  (graph, link, link->age_index);
1137     heap_bubble_down(graph, link, link->age_index);
1138 }
1139
1140
1141 int avfilter_graph_request_oldest(AVFilterGraph *graph)
1142 {
1143     while (graph->sink_links_count) {
1144         AVFilterLink *oldest = graph->sink_links[0];
1145         int r = ff_request_frame(oldest);
1146         if (r != AVERROR_EOF)
1147             return r;
1148         av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
1149                oldest->dst ? oldest->dst->name : "unknown",
1150                oldest->dstpad ? oldest->dstpad->name : "unknown");
1151         /* EOF: remove the link from the heap */
1152         if (oldest->age_index < --graph->sink_links_count)
1153             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
1154                              oldest->age_index);
1155         oldest->age_index = -1;
1156     }
1157     return AVERROR_EOF;
1158 }