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