avfilter/REDUCE_FORMATS: fix bug that ended reducing too early
[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                 ret = 1;                                               \
620                 break;                                                 \
621             }                                                          \
622                                                                        \
623             for (k = 0; k < out_link->in_ ## list->nb; k++)            \
624                 if (fmts->var[k] == fmt) {                             \
625                     fmts->var[0]  = fmt;                               \
626                     fmts->nb = 1;                                      \
627                     ret = 1;                                           \
628                     break;                                             \
629                 }                                                      \
630         }                                                              \
631     }                                                                  \
632 } while (0)
633
634 static int reduce_formats_on_filter(AVFilterContext *filter)
635 {
636     int i, j, k, ret = 0;
637
638     REDUCE_FORMATS(int,      AVFilterFormats,        formats,         formats,
639                    nb_formats, ff_add_format);
640     REDUCE_FORMATS(int,      AVFilterFormats,        samplerates,     formats,
641                    nb_formats, ff_add_format);
642
643     /* reduce channel layouts */
644     for (i = 0; i < filter->nb_inputs; i++) {
645         AVFilterLink *inlink = filter->inputs[i];
646         uint64_t fmt;
647
648         if (!inlink->out_channel_layouts ||
649             inlink->out_channel_layouts->nb_channel_layouts != 1)
650             continue;
651         fmt = inlink->out_channel_layouts->channel_layouts[0];
652
653         for (j = 0; j < filter->nb_outputs; j++) {
654             AVFilterLink *outlink = filter->outputs[j];
655             AVFilterChannelLayouts *fmts;
656
657             fmts = outlink->in_channel_layouts;
658             if (inlink->type != outlink->type || fmts->nb_channel_layouts == 1)
659                 continue;
660
661             if (fmts->all_layouts) {
662                 /* Turn the infinite list into a singleton */
663                 fmts->all_layouts = fmts->all_counts  = 0;
664                 ff_add_channel_layout(&outlink->in_channel_layouts, fmt);
665                 break;
666             }
667
668             for (k = 0; k < outlink->in_channel_layouts->nb_channel_layouts; k++) {
669                 if (fmts->channel_layouts[k] == fmt) {
670                     fmts->channel_layouts[0]  = fmt;
671                     fmts->nb_channel_layouts = 1;
672                     ret = 1;
673                     break;
674                 }
675             }
676         }
677     }
678
679     return ret;
680 }
681
682 static void reduce_formats(AVFilterGraph *graph)
683 {
684     int i, reduced;
685
686     do {
687         reduced = 0;
688
689         for (i = 0; i < graph->nb_filters; i++)
690             reduced |= reduce_formats_on_filter(graph->filters[i]);
691     } while (reduced);
692 }
693
694 static void swap_samplerates_on_filter(AVFilterContext *filter)
695 {
696     AVFilterLink *link = NULL;
697     int sample_rate;
698     int i, j;
699
700     for (i = 0; i < filter->nb_inputs; i++) {
701         link = filter->inputs[i];
702
703         if (link->type == AVMEDIA_TYPE_AUDIO &&
704             link->out_samplerates->nb_formats== 1)
705             break;
706     }
707     if (i == filter->nb_inputs)
708         return;
709
710     sample_rate = link->out_samplerates->formats[0];
711
712     for (i = 0; i < filter->nb_outputs; i++) {
713         AVFilterLink *outlink = filter->outputs[i];
714         int best_idx, best_diff = INT_MAX;
715
716         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
717             outlink->in_samplerates->nb_formats < 2)
718             continue;
719
720         for (j = 0; j < outlink->in_samplerates->nb_formats; j++) {
721             int diff = abs(sample_rate - outlink->in_samplerates->formats[j]);
722
723             if (diff < best_diff) {
724                 best_diff = diff;
725                 best_idx  = j;
726             }
727         }
728         FFSWAP(int, outlink->in_samplerates->formats[0],
729                outlink->in_samplerates->formats[best_idx]);
730     }
731 }
732
733 static void swap_samplerates(AVFilterGraph *graph)
734 {
735     int i;
736
737     for (i = 0; i < graph->nb_filters; i++)
738         swap_samplerates_on_filter(graph->filters[i]);
739 }
740
741 #define CH_CENTER_PAIR (AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)
742 #define CH_FRONT_PAIR  (AV_CH_FRONT_LEFT           | AV_CH_FRONT_RIGHT)
743 #define CH_STEREO_PAIR (AV_CH_STEREO_LEFT          | AV_CH_STEREO_RIGHT)
744 #define CH_WIDE_PAIR   (AV_CH_WIDE_LEFT            | AV_CH_WIDE_RIGHT)
745 #define CH_SIDE_PAIR   (AV_CH_SIDE_LEFT            | AV_CH_SIDE_RIGHT)
746 #define CH_DIRECT_PAIR (AV_CH_SURROUND_DIRECT_LEFT | AV_CH_SURROUND_DIRECT_RIGHT)
747 #define CH_BACK_PAIR   (AV_CH_BACK_LEFT            | AV_CH_BACK_RIGHT)
748
749 /* allowable substitutions for channel pairs when comparing layouts,
750  * ordered by priority for both values */
751 static const uint64_t ch_subst[][2] = {
752     { CH_FRONT_PAIR,      CH_CENTER_PAIR     },
753     { CH_FRONT_PAIR,      CH_WIDE_PAIR       },
754     { CH_FRONT_PAIR,      AV_CH_FRONT_CENTER },
755     { CH_CENTER_PAIR,     CH_FRONT_PAIR      },
756     { CH_CENTER_PAIR,     CH_WIDE_PAIR       },
757     { CH_CENTER_PAIR,     AV_CH_FRONT_CENTER },
758     { CH_WIDE_PAIR,       CH_FRONT_PAIR      },
759     { CH_WIDE_PAIR,       CH_CENTER_PAIR     },
760     { CH_WIDE_PAIR,       AV_CH_FRONT_CENTER },
761     { AV_CH_FRONT_CENTER, CH_FRONT_PAIR      },
762     { AV_CH_FRONT_CENTER, CH_CENTER_PAIR     },
763     { AV_CH_FRONT_CENTER, CH_WIDE_PAIR       },
764     { CH_SIDE_PAIR,       CH_DIRECT_PAIR     },
765     { CH_SIDE_PAIR,       CH_BACK_PAIR       },
766     { CH_SIDE_PAIR,       AV_CH_BACK_CENTER  },
767     { CH_BACK_PAIR,       CH_DIRECT_PAIR     },
768     { CH_BACK_PAIR,       CH_SIDE_PAIR       },
769     { CH_BACK_PAIR,       AV_CH_BACK_CENTER  },
770     { AV_CH_BACK_CENTER,  CH_BACK_PAIR       },
771     { AV_CH_BACK_CENTER,  CH_DIRECT_PAIR     },
772     { AV_CH_BACK_CENTER,  CH_SIDE_PAIR       },
773 };
774
775 static void swap_channel_layouts_on_filter(AVFilterContext *filter)
776 {
777     AVFilterLink *link = NULL;
778     int i, j, k;
779
780     for (i = 0; i < filter->nb_inputs; i++) {
781         link = filter->inputs[i];
782
783         if (link->type == AVMEDIA_TYPE_AUDIO &&
784             link->out_channel_layouts->nb_channel_layouts == 1)
785             break;
786     }
787     if (i == filter->nb_inputs)
788         return;
789
790     for (i = 0; i < filter->nb_outputs; i++) {
791         AVFilterLink *outlink = filter->outputs[i];
792         int best_idx = -1, best_score = INT_MIN, best_count_diff = INT_MAX;
793
794         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
795             outlink->in_channel_layouts->nb_channel_layouts < 2)
796             continue;
797
798         for (j = 0; j < outlink->in_channel_layouts->nb_channel_layouts; j++) {
799             uint64_t  in_chlayout = link->out_channel_layouts->channel_layouts[0];
800             uint64_t out_chlayout = outlink->in_channel_layouts->channel_layouts[j];
801             int  in_channels      = av_get_channel_layout_nb_channels(in_chlayout);
802             int out_channels      = av_get_channel_layout_nb_channels(out_chlayout);
803             int count_diff        = out_channels - in_channels;
804             int matched_channels, extra_channels;
805             int score = 100000;
806
807             if (FF_LAYOUT2COUNT(in_chlayout) || FF_LAYOUT2COUNT(out_chlayout)) {
808                 /* Compute score in case the input or output layout encodes
809                    a channel count; in this case the score is not altered by
810                    the computation afterwards, as in_chlayout and
811                    out_chlayout have both been set to 0 */
812                 if (FF_LAYOUT2COUNT(in_chlayout))
813                     in_channels = FF_LAYOUT2COUNT(in_chlayout);
814                 if (FF_LAYOUT2COUNT(out_chlayout))
815                     out_channels = FF_LAYOUT2COUNT(out_chlayout);
816                 score -= 10000 + FFABS(out_channels - in_channels) +
817                          (in_channels > out_channels ? 10000 : 0);
818                 in_chlayout = out_chlayout = 0;
819                 /* Let the remaining computation run, even if the score
820                    value is not altered */
821             }
822
823             /* channel substitution */
824             for (k = 0; k < FF_ARRAY_ELEMS(ch_subst); k++) {
825                 uint64_t cmp0 = ch_subst[k][0];
826                 uint64_t cmp1 = ch_subst[k][1];
827                 if (( in_chlayout & cmp0) && (!(out_chlayout & cmp0)) &&
828                     (out_chlayout & cmp1) && (!( in_chlayout & cmp1))) {
829                     in_chlayout  &= ~cmp0;
830                     out_chlayout &= ~cmp1;
831                     /* add score for channel match, minus a deduction for
832                        having to do the substitution */
833                     score += 10 * av_get_channel_layout_nb_channels(cmp1) - 2;
834                 }
835             }
836
837             /* no penalty for LFE channel mismatch */
838             if ( (in_chlayout & AV_CH_LOW_FREQUENCY) &&
839                 (out_chlayout & AV_CH_LOW_FREQUENCY))
840                 score += 10;
841             in_chlayout  &= ~AV_CH_LOW_FREQUENCY;
842             out_chlayout &= ~AV_CH_LOW_FREQUENCY;
843
844             matched_channels = av_get_channel_layout_nb_channels(in_chlayout &
845                                                                  out_chlayout);
846             extra_channels   = av_get_channel_layout_nb_channels(out_chlayout &
847                                                                  (~in_chlayout));
848             score += 10 * matched_channels - 5 * extra_channels;
849
850             if (score > best_score ||
851                 (count_diff < best_count_diff && score == best_score)) {
852                 best_score = score;
853                 best_idx   = j;
854                 best_count_diff = count_diff;
855             }
856         }
857         av_assert0(best_idx >= 0);
858         FFSWAP(uint64_t, outlink->in_channel_layouts->channel_layouts[0],
859                outlink->in_channel_layouts->channel_layouts[best_idx]);
860     }
861
862 }
863
864 static void swap_channel_layouts(AVFilterGraph *graph)
865 {
866     int i;
867
868     for (i = 0; i < graph->nb_filters; i++)
869         swap_channel_layouts_on_filter(graph->filters[i]);
870 }
871
872 static void swap_sample_fmts_on_filter(AVFilterContext *filter)
873 {
874     AVFilterLink *link = NULL;
875     int format, bps;
876     int i, j;
877
878     for (i = 0; i < filter->nb_inputs; i++) {
879         link = filter->inputs[i];
880
881         if (link->type == AVMEDIA_TYPE_AUDIO &&
882             link->out_formats->nb_formats == 1)
883             break;
884     }
885     if (i == filter->nb_inputs)
886         return;
887
888     format = link->out_formats->formats[0];
889     bps    = av_get_bytes_per_sample(format);
890
891     for (i = 0; i < filter->nb_outputs; i++) {
892         AVFilterLink *outlink = filter->outputs[i];
893         int best_idx = -1, best_score = INT_MIN;
894
895         if (outlink->type != AVMEDIA_TYPE_AUDIO ||
896             outlink->in_formats->nb_formats < 2)
897             continue;
898
899         for (j = 0; j < outlink->in_formats->nb_formats; j++) {
900             int out_format = outlink->in_formats->formats[j];
901             int out_bps    = av_get_bytes_per_sample(out_format);
902             int score;
903
904             if (av_get_packed_sample_fmt(out_format) == format ||
905                 av_get_planar_sample_fmt(out_format) == format) {
906                 best_idx   = j;
907                 break;
908             }
909
910             /* for s32 and float prefer double to prevent loss of information */
911             if (bps == 4 && out_bps == 8) {
912                 best_idx = j;
913                 break;
914             }
915
916             /* prefer closest higher or equal bps */
917             score = -abs(out_bps - bps);
918             if (out_bps >= bps)
919                 score += INT_MAX/2;
920
921             if (score > best_score) {
922                 best_score = score;
923                 best_idx   = j;
924             }
925         }
926         av_assert0(best_idx >= 0);
927         FFSWAP(int, outlink->in_formats->formats[0],
928                outlink->in_formats->formats[best_idx]);
929     }
930 }
931
932 static void swap_sample_fmts(AVFilterGraph *graph)
933 {
934     int i;
935
936     for (i = 0; i < graph->nb_filters; i++)
937         swap_sample_fmts_on_filter(graph->filters[i]);
938
939 }
940
941 static int pick_formats(AVFilterGraph *graph)
942 {
943     int i, j, ret;
944     int change;
945
946     do{
947         change = 0;
948         for (i = 0; i < graph->nb_filters; i++) {
949             AVFilterContext *filter = graph->filters[i];
950             if (filter->nb_inputs){
951                 for (j = 0; j < filter->nb_inputs; j++){
952                     if(filter->inputs[j]->in_formats && filter->inputs[j]->in_formats->nb_formats == 1) {
953                         if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
954                             return ret;
955                         change = 1;
956                     }
957                 }
958             }
959             if (filter->nb_outputs){
960                 for (j = 0; j < filter->nb_outputs; j++){
961                     if(filter->outputs[j]->in_formats && filter->outputs[j]->in_formats->nb_formats == 1) {
962                         if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
963                             return ret;
964                         change = 1;
965                     }
966                 }
967             }
968             if (filter->nb_inputs && filter->nb_outputs && filter->inputs[0]->format>=0) {
969                 for (j = 0; j < filter->nb_outputs; j++) {
970                     if(filter->outputs[j]->format<0) {
971                         if ((ret = pick_format(filter->outputs[j], filter->inputs[0])) < 0)
972                             return ret;
973                         change = 1;
974                     }
975                 }
976             }
977         }
978     }while(change);
979
980     for (i = 0; i < graph->nb_filters; i++) {
981         AVFilterContext *filter = graph->filters[i];
982
983         for (j = 0; j < filter->nb_inputs; j++)
984             if ((ret = pick_format(filter->inputs[j], NULL)) < 0)
985                 return ret;
986         for (j = 0; j < filter->nb_outputs; j++)
987             if ((ret = pick_format(filter->outputs[j], NULL)) < 0)
988                 return ret;
989     }
990     return 0;
991 }
992
993 /**
994  * Configure the formats of all the links in the graph.
995  */
996 static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)
997 {
998     int ret;
999
1000     /* find supported formats from sub-filters, and merge along links */
1001     while ((ret = query_formats(graph, log_ctx)) == AVERROR(EAGAIN))
1002         av_log(graph, AV_LOG_DEBUG, "query_formats not finished\n");
1003     if (ret < 0)
1004         return ret;
1005
1006     /* Once everything is merged, it's possible that we'll still have
1007      * multiple valid media format choices. We try to minimize the amount
1008      * of format conversion inside filters */
1009     reduce_formats(graph);
1010
1011     /* for audio filters, ensure the best format, sample rate and channel layout
1012      * is selected */
1013     swap_sample_fmts(graph);
1014     swap_samplerates(graph);
1015     swap_channel_layouts(graph);
1016
1017     if ((ret = pick_formats(graph)) < 0)
1018         return ret;
1019
1020     return 0;
1021 }
1022
1023 static int ff_avfilter_graph_config_pointers(AVFilterGraph *graph,
1024                                              AVClass *log_ctx)
1025 {
1026     unsigned i, j;
1027     int sink_links_count = 0, n = 0;
1028     AVFilterContext *f;
1029     AVFilterLink **sinks;
1030
1031     for (i = 0; i < graph->nb_filters; i++) {
1032         f = graph->filters[i];
1033         for (j = 0; j < f->nb_inputs; j++) {
1034             f->inputs[j]->graph     = graph;
1035             f->inputs[j]->age_index = -1;
1036         }
1037         for (j = 0; j < f->nb_outputs; j++) {
1038             f->outputs[j]->graph    = graph;
1039             f->outputs[j]->age_index= -1;
1040         }
1041         if (!f->nb_outputs) {
1042             if (f->nb_inputs > INT_MAX - sink_links_count)
1043                 return AVERROR(EINVAL);
1044             sink_links_count += f->nb_inputs;
1045         }
1046     }
1047     sinks = av_calloc(sink_links_count, sizeof(*sinks));
1048     if (!sinks)
1049         return AVERROR(ENOMEM);
1050     for (i = 0; i < graph->nb_filters; i++) {
1051         f = graph->filters[i];
1052         if (!f->nb_outputs) {
1053             for (j = 0; j < f->nb_inputs; j++) {
1054                 sinks[n] = f->inputs[j];
1055                 f->inputs[j]->age_index = n++;
1056             }
1057         }
1058     }
1059     av_assert0(n == sink_links_count);
1060     graph->sink_links       = sinks;
1061     graph->sink_links_count = sink_links_count;
1062     return 0;
1063 }
1064
1065 static int graph_insert_fifos(AVFilterGraph *graph, AVClass *log_ctx)
1066 {
1067     AVFilterContext *f;
1068     int i, j, ret;
1069     int fifo_count = 0;
1070
1071     for (i = 0; i < graph->nb_filters; i++) {
1072         f = graph->filters[i];
1073
1074         for (j = 0; j < f->nb_inputs; j++) {
1075             AVFilterLink *link = f->inputs[j];
1076             AVFilterContext *fifo_ctx;
1077             AVFilter *fifo;
1078             char name[32];
1079
1080             if (!link->dstpad->needs_fifo)
1081                 continue;
1082
1083             fifo = f->inputs[j]->type == AVMEDIA_TYPE_VIDEO ?
1084                    avfilter_get_by_name("fifo") :
1085                    avfilter_get_by_name("afifo");
1086
1087             snprintf(name, sizeof(name), "auto-inserted fifo %d", fifo_count++);
1088
1089             ret = avfilter_graph_create_filter(&fifo_ctx, fifo, name, NULL,
1090                                                NULL, graph);
1091             if (ret < 0)
1092                 return ret;
1093
1094             ret = avfilter_insert_filter(link, fifo_ctx, 0, 0);
1095             if (ret < 0)
1096                 return ret;
1097         }
1098     }
1099
1100     return 0;
1101 }
1102
1103 int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
1104 {
1105     int ret;
1106
1107     if ((ret = graph_check_validity(graphctx, log_ctx)))
1108         return ret;
1109     if ((ret = graph_insert_fifos(graphctx, log_ctx)) < 0)
1110         return ret;
1111     if ((ret = graph_config_formats(graphctx, log_ctx)))
1112         return ret;
1113     if ((ret = graph_config_links(graphctx, log_ctx)))
1114         return ret;
1115     if ((ret = ff_avfilter_graph_config_pointers(graphctx, log_ctx)))
1116         return ret;
1117
1118     return 0;
1119 }
1120
1121 int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
1122 {
1123     int i, r = AVERROR(ENOSYS);
1124
1125     if (!graph)
1126         return r;
1127
1128     if ((flags & AVFILTER_CMD_FLAG_ONE) && !(flags & AVFILTER_CMD_FLAG_FAST)) {
1129         r = avfilter_graph_send_command(graph, target, cmd, arg, res, res_len, flags | AVFILTER_CMD_FLAG_FAST);
1130         if (r != AVERROR(ENOSYS))
1131             return r;
1132     }
1133
1134     if (res_len && res)
1135         res[0] = 0;
1136
1137     for (i = 0; i < graph->nb_filters; i++) {
1138         AVFilterContext *filter = graph->filters[i];
1139         if (!strcmp(target, "all") || (filter->name && !strcmp(target, filter->name)) || !strcmp(target, filter->filter->name)) {
1140             r = avfilter_process_command(filter, cmd, arg, res, res_len, flags);
1141             if (r != AVERROR(ENOSYS)) {
1142                 if ((flags & AVFILTER_CMD_FLAG_ONE) || r < 0)
1143                     return r;
1144             }
1145         }
1146     }
1147
1148     return r;
1149 }
1150
1151 int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *command, const char *arg, int flags, double ts)
1152 {
1153     int i;
1154
1155     if(!graph)
1156         return 0;
1157
1158     for (i = 0; i < graph->nb_filters; i++) {
1159         AVFilterContext *filter = graph->filters[i];
1160         if(filter && (!strcmp(target, "all") || !strcmp(target, filter->name) || !strcmp(target, filter->filter->name))){
1161             AVFilterCommand **queue = &filter->command_queue, *next;
1162             while (*queue && (*queue)->time <= ts)
1163                 queue = &(*queue)->next;
1164             next = *queue;
1165             *queue = av_mallocz(sizeof(AVFilterCommand));
1166             (*queue)->command = av_strdup(command);
1167             (*queue)->arg     = av_strdup(arg);
1168             (*queue)->time    = ts;
1169             (*queue)->flags   = flags;
1170             (*queue)->next    = next;
1171             if(flags & AVFILTER_CMD_FLAG_ONE)
1172                 return 0;
1173         }
1174     }
1175
1176     return 0;
1177 }
1178
1179 static void heap_bubble_up(AVFilterGraph *graph,
1180                            AVFilterLink *link, int index)
1181 {
1182     AVFilterLink **links = graph->sink_links;
1183
1184     while (index) {
1185         int parent = (index - 1) >> 1;
1186         if (links[parent]->current_pts >= link->current_pts)
1187             break;
1188         links[index] = links[parent];
1189         links[index]->age_index = index;
1190         index = parent;
1191     }
1192     links[index] = link;
1193     link->age_index = index;
1194 }
1195
1196 static void heap_bubble_down(AVFilterGraph *graph,
1197                              AVFilterLink *link, int index)
1198 {
1199     AVFilterLink **links = graph->sink_links;
1200
1201     while (1) {
1202         int child = 2 * index + 1;
1203         if (child >= graph->sink_links_count)
1204             break;
1205         if (child + 1 < graph->sink_links_count &&
1206             links[child + 1]->current_pts < links[child]->current_pts)
1207             child++;
1208         if (link->current_pts < links[child]->current_pts)
1209             break;
1210         links[index] = links[child];
1211         links[index]->age_index = index;
1212         index = child;
1213     }
1214     links[index] = link;
1215     link->age_index = index;
1216 }
1217
1218 void ff_avfilter_graph_update_heap(AVFilterGraph *graph, AVFilterLink *link)
1219 {
1220     heap_bubble_up  (graph, link, link->age_index);
1221     heap_bubble_down(graph, link, link->age_index);
1222 }
1223
1224
1225 int avfilter_graph_request_oldest(AVFilterGraph *graph)
1226 {
1227     while (graph->sink_links_count) {
1228         AVFilterLink *oldest = graph->sink_links[0];
1229         int r = ff_request_frame(oldest);
1230         if (r != AVERROR_EOF)
1231             return r;
1232         av_log(oldest->dst, AV_LOG_DEBUG, "EOF on sink link %s:%s.\n",
1233                oldest->dst ? oldest->dst->name : "unknown",
1234                oldest->dstpad ? oldest->dstpad->name : "unknown");
1235         /* EOF: remove the link from the heap */
1236         if (oldest->age_index < --graph->sink_links_count)
1237             heap_bubble_down(graph, graph->sink_links[graph->sink_links_count],
1238                              oldest->age_index);
1239         oldest->age_index = -1;
1240     }
1241     return AVERROR_EOF;
1242 }