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