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