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