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