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