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