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